java - 在java中使用vigenere密码加密字节数组

标签 java file encryption byte vigenere

我必须使用 vigenere 密码加密一些文件 (jpg)。我编写了一些代码,但加密和解密后我的文件已损坏。图像的前 1/4 显示正常,但其余部分已损坏。这是我的代码:

@Override
public byte[] encryptFile(byte[] file, String key) {
    char[] keyChars = key.toCharArray();
    byte[] bytes = file;
    for (int i = 0; i < file.length; i++) {
        int keyNR = keyChars[i % keyChars.length] - 32;
        int c = bytes[i] & 255;
        if ((c >= 32) && (c <= 127)) {
            int x = c - 32;
            x = (x + keyNR) % 96;
            bytes[i] = (byte) (x + 32);
        }
    }
    return bytes;
}


@Override
public byte[] decryptFile(byte[] file, String key) {
    char[] keyChars = key.toCharArray();
    byte[] bytes = file;
    for (int i = 0; i < file.length; i++) {
        int keyNR = keyChars[i % keyChars.length] - 32;
        int c = bytes[i] & 255;
        if ((c >= 32) && (c <= 127)) {
            int x = c - 32;
            x = (x - keyNR + 96) % 96;
            bytes[i] = (byte) (x + 32);
        }
    }
    return bytes;
}

我做错了什么?

编辑:

读取和写入文件:

public void sendFile(String selectedFile, ICipher cipher, String key) {
    try {
        DataOutputStream outStream = new DataOutputStream(client
                .getOutputStream());
        outStream.flush();
        File file = new File(selectedFile);
        FileInputStream fileStream = new FileInputStream(file);
        long fileSize = file.length();
        long completed = 0;
        long bytesLeft = fileSize - completed;
        String msg = "SENDING_FILE:" + file.getName() + ":" + fileSize;
        outStream.writeUTF(cipher.encryptMsg(msg, key));
        while (completed < fileSize) {
            int step = (int) (bytesLeft > 150000 ? 150000 : bytesLeft);
            byte[] buffer = new byte[step];
            fileStream.read(buffer);
            buffer = cipher.encryptFile(buffer, key);
            outStream.write(buffer);
            completed += step;
            bytesLeft = fileSize - completed;
        }
        outStream.writeUTF(cipher.encryptMsg("SEND_COMPLETE", key));
        fileStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

    private void downloadFile(String fileName, int fileSize,DataInputStream input,ICipher cipher, String key) {
    try {
        FileOutputStream outStream = new FileOutputStream("C:\\" + fileName);
        int bytesRead = 0, counter = 0;

        while (counter < fileSize) {
            int step = (int) (fileSize > 150000 ? 150000 : fileSize);
            byte[] buffer = new byte[step];
            bytesRead = input.read(buffer);
            if (bytesRead >= 0) {
                buffer = cipher.decryptFile(buffer, key);
                outStream.write(buffer, 0, bytesRead);
                counter += bytesRead;
            }
            if (bytesRead < 1024) {
                outStream.flush();
                break;
            }
        }

        Display.getDefault().syncExec(new Runnable() {
            @Override
            public void run() {
                window.handleMessage("Download sucessfully");
            }
        });
        outStream.close();

    } catch (Exception e) {
        Display.getDefault().syncExec(new Runnable() {
            @Override
            public void run() {
                window.handleMessage("Error on downloading file!");
            }
        });
    }
}

最佳答案

您可以将文件编码为来自磁盘 I/O 的任何 block :

        int step = (int) (bytesLeft > 150000 ? 150000 : bytesLeft);
        byte[] buffer = new byte[step];
        fileStream.read(buffer);
        buffer = cipher.encryptFile(buffer, key);

但是您可以将文件解码为来自网络 I/O 的任何 block :

        bytesRead = input.read(buffer);
        if (bytesRead >= 0) {
            buffer = cipher.decryptFile(buffer, key);
            outStream.write(buffer, 0, bytesRead);
            counter += bytesRead;
        }

这些 block 可能会不一致。磁盘 I/O 可能总是为您提供完整的 block (对您来说幸运),但网络 I/O 可能会为您提供数据包大小的 block (1500 字节减去 header )。

密码应该在已经编码/解码的数据中获得一个偏移量(或者一次编码/解码所有内容),并使用它来适本地移动 key ,否则可能会发生这种情况:

original: ...LOREM IPSUM...
key     : ...abCde abCde...
encoded : ...MQUIR JRVYR...
key     : ...abCde Cdeab... <<note the key got shifted
decoded : ...LOREM GNQXP... <<output wrong after the first chunk.

由于数据包数据大小(对于以太网大小的 TCP/IP 数据包)按四个字节对齐,因此长度为 4 的 key 可能始终对齐。

<小时/>

另一个问题是您在上传文件时忽略了从磁盘读取的字节数。虽然磁盘 I/O 可能总是为您提供完整大小的 block (文件可能是内存映射的或底层 native API 确实提供了这种保证),但没有什么是理所当然的。始终使用实际读取的字节数:bytesRead = fileStream.read(buffer);

关于java - 在java中使用vigenere密码加密字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13386266/

相关文章:

java - 如何在 MongoTemplate 中使用多个 orOperator

java - 将参数传递给 Java 线程

java - 删除包含特定单词的 jsonnode

Java文件编码从ANSI到UTF8的转换

java - 在运行时更新或更改 View 中的图像

python - 通读非结构化 xls 文件

Python 文件 io 缓冲

c++ - 基本加密程序无法正确读取文件

c# - 在 C# 和 Bouncy CaSTLe 中读取 RSA PrivateKey

javascript - Node.js 中的 PHP aes-256-cbc mcrypt_decrypt() 等价物