gpt4 book ai didi

java - 加密/解密,获取 IllegalBlockSizeException

转载 作者:行者123 更新时间:2023-12-01 18:51:08 26 4
gpt4 key购买 nike

我正在使用 Java 的加密库并收到 IllegalBlockSizeException。

我目前正在尝试以 XML 文件格式提取数据库内容。在数据转储期间,我正在创建一个 list 文件,其中包含一个字符串,该字符串使用数据库中定义的 key 进行解密。

稍后,当 XML 文件的内容加载到另一个数据库中时,它会从该数据库获取 key 并使用它来解密 list 。如果解密后的 list 与原始内容不匹配,则意味着源数据库和目标数据库中的加密 key 不匹配,并且用户会收到此通知。

以下是代码。 EncryptionEngine 对象是一个单例,它使用 Java 加密库抽象出许多加密细节。假设它工作正常,因为它是相当古老且成熟的代码。

这都是我制作的类(class)中的内容。首先,我们有这些数据成员:

private final String encryptedManifestContents;
private final static String DECRYPTED_MANIFEST_CONTENTS = "This file contains the encrypted string for validating data in the dump and load process";
final static String ENCRYPTED_MANIFEST_FILENAME = "manifest.bin";

首先是加密过程。该字符串的加密方式如下:

final EncryptionEngine encryptionEngine = EncryptionEngine.getInstance();
encryptedManifestContents = encryptionEngine.symmetricEncrypt(DECRYPTED_MANIFEST_CONTENTS); // The contents get converted to bytes via getBytes("UTF-8")

然后写入 list 文件(目标只是一个以字符串形式保存文件路径的变量):

EncryptedManifestUtil encryptedManifestUtil = new EncryptedManifestUtil(); // The class I've created.  The constructor is the code above, which just initialized the EncryptionEngine and encrypted the manifest string.
manifestOut = new FileOutputStream(destination + "/" + ENCRYPTED_MANIFEST_FILENAME);
manifestOut.write(encryptedManifestUtil.encryptedManifestContents.getBytes("UTF-8"));

至此,加密过程完成。我们获取了一个字符串,对其进行了加密,然后按顺序将内容写入到一个文件中。现在,当有人加载数据时,解密过程就会开始:

BufferedReader fileReader = new BufferedReader(new FileReader(filename)); // Filename is the manifest's file name and location
final EncryptionEngine encryptionEngine = EncryptionEngine.getInstance();
String decryptedManifest = encryptionEngine.decryptString(fileReader.readLine().getBytes("UTF-8")); // This is a symmetric decrypt

当解密发生时,它会抛出此异常:

Caused by: javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(DashoA13*..)

它似乎可以正确读取和写入文件,但内容对我来说是乱码。 fileReader.readLine() 的结果是:

9�Y�������䖷�߾��=Ă���    s7Cx�t�b��_-(�b��LFA���}�6�f����Ps�n�����ʢ�@��  �%��%�5P�p

感谢您的帮助。

编辑:所以我改变了写入文件的方式。

回想一下这一行:

encryptedManifestContents = encryptionEngine.symmetricEncrypt(DECRYPTED_MANIFEST_CONTENTS);

加密首先从输入的字符串中获取字节,然后解密,然后通过首先将其编码为基本 64 字节将字节更改回字符串。然后它将基本 64 字节数组转换回字符串。

考虑到这一点,我将文件编写器更改为 PrintWriter 而不是 FileOutputStream,并直接将字符串而不是字节写入文件。不幸的是我仍然收到错误。然而,读取行生成的字符串中的 � 似乎较少。

最佳答案

看起来问题出在你的 fileReader.readLine() 上 - 你正在将字节流写入文件,然后将其作为字符串读回。相反,您应该读取字节流,例如refer to this question ,或者使用Base64 Encoding要将字节数组转换为字符串,请将其写入文件,从文件中读取,然后将其转换回字节数组。

关于java - 加密/解密,获取 IllegalBlockSizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15886657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com