java 8 解密文件 AES/CBC/NoPadding 为什么生成另一个加密文件?

问题描述 投票:0回答:1

我有这个aes-128-cbc加密算法来解密加密文件,根据这个Cipher链接,正确的Cipher实例是:AES/CBC/NoPadding,我有这个方法。

private static void decrypt() {
        String key = "12345678";
        String inputFile = "src/main/resources/config/data.encrypted";
        String outputFile = "src/main/resources/config/data";

        try {
            // Read the encrypted file
            FileInputStream fis = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) fis.available()];
            fis.read(inputBytes);

            // Set up the decryption cipher
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            // Decrypt the file
            byte[] decryptedBytes = cipher.doFinal(inputBytes);

            // Write the decrypted file
            FileOutputStream fos = new FileOutputStream(outputFile);
            OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            osw.write(new String(decryptedBytes, StandardCharsets.UTF_8));

            fis.close();
            osw.close();

            System.out.println("File decrypted successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

但我已经知道,生成的文件是加密的。您能给我一些解决办法吗?

java encryption java-8 aes
1个回答
0
投票

我们无法指出解密失败的原因。没有取消填充的 CBC(这意味着

"NoPadding"
只要输入数据是块大小的倍数,就总是成功。 解密算法将正常运行而不会抛出任何异常。

错误可能包括:

    密文的任何改变;
  1. IV 错误;
  2. 加密时使用不同的密码或密码模式;
  3. 键值不正确。
现在对密文 (1) 的更改可能会保持所得明文的某些部分完好无损。 CBC 模式 (2) 的错误 IV 只会随机化所得明文的第一部分。不同模式 (3) 的错误可能会产生任何奇怪的结果,并且使用错误的密钥 (4) 将创建全新的加密级别(除非使用不同模式时会产生异常)。对于许多操作模式,解密与加密非常相似甚至相同。

您已表示“生成的文件已加密”,但这并不确定,因为上面列出的任何错误至少会导致解密的密文的

一些被随机化。对称密码旨在创建与随机数据无法区分的密文。如果数据的任何部分未随机化,则最有可能出现问题 1 或 2。

© www.soinside.com 2019 - 2024. All rights reserved.