-1

我正在尝试使用 Java 中的 JCA 和 JCE 编写一个简单的应用程序来加密和解密一段文本。

到目前为止,加密部分有效,但在解密时它给了我以下异常:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

这是我初始化两个密码 encCipher 和 decCipher 的部分。

PBEKeySpec pbeKeySpec;
PBEParameterSpec paramSpec;
SecretKeyFactory keyFac;
byte[] salt = {(byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
               (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99};
int count = 20;
paramSpec = new PBEParameterSpec(salt, count);

try {
    pbeKeySpec = new PBEKeySpec("my_password".toCharArray(), salt, count);
    SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(pbeKeySpec);

    encCipher = Cipher.getInstance(secretKey.getAlgorithm());
    encCipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
    decCipher = Cipher.getInstance(secretKey.getAlgorithm());
    decCipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);

} catch (Exception ex) {
    ex.printStackTrace();
 }

我没有使用 Java Cryptography Architecture 的经验,我想知道如何修复该错误。

异常发生在 loadClients 的 decCipher.doFinal 行。

private void saveClients() {
   String plainText = "";
   String encText = "";
   Set<String> clients = my_clients.keySet();
        try {
            PrintWriter out = new PrintWriter(new File(output_file));
            for (String client : clients) {
                long client_time = my_clients.get(client);
                plainText = client + " " + client_time;

                encText = new String(encCipher.doFinal(plainText.getBytes()));
                out.println(encText);
            }
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void loadClients() {
        BufferedReader in;
        String line;
        try {
            in = new BufferedReader(new FileReader(output_file));
            while ((line = in.readLine()) != null) {
                byte[] decBytes = decCipher.doFinal(line.getBytes());
                String decText = new String(decBytes);
                String[] client_data = decText.split("[ ]");
                my_clients.put(client_data[0], Long.parseLong(client_data[1]));
            }
            in.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
     }
4

1 回答 1

1

问题来自您将字节转换为字符串的事实。假设您的默认平台编码是 ASCII。这意味着加密文本中包含的一半字节(字节 128 及以上)不代表有效字符。此外,您为每个加密文本写一行。所以,如果你的加密字节数组恰好包含一个换行符,你实际上会向 writer 写入两行,并尝试逐行解密,这将导致异常。

要么使用字节来存储和传输您的加密数据,要么使用无损算法将它们转换为字符串,例如 Base64(这将确保所有内容都将转换为可打印的字符)。Apache commons-codec 有一个 Base64 实现。

于 2011-12-26T15:35:34.433 回答