gpt4 book ai didi

java - 如何使用 BouncyCaSTLe 轻量级 API 使用 PBE AES 加密/解密文件?

转载 作者:行者123 更新时间:2023-12-01 15:40:44 31 4
gpt4 key购买 nike

我正在尝试使用 AES 通过 PBE 加密/解密文件。我正在使用 Bouncy Casle 库(轻量级 API),因为我需要忽略 key 长度的限制。我找到了函数并更改了其中的一些代码。

public void decryptLW(InputStream in, OutputStream out, String password, byte[] salt, final int iterationCount) throws Exception {

PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest());
char[] passwordChars = password.toCharArray();
final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
pGen.init(pkcs12PasswordBytes, salt, iterationCount);
CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128);
aesCBC.init(false, aesCBCParams);
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding());

try {

// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {

byte[] plainTemp = new byte[aesCipher.getOutputSize(buf.length)];
int offset = aesCipher.processBytes(buf, 0, buf.length, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
final byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);

out.write(plain, 0, numRead);
}
out.close();
in.close();
} catch (java.io.IOException e) {
}

}

我有一个错误:

org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(Unknown Source)
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(Unknown Source)

我可以做什么来消除这个错误?我必须在此函数中更改什么才能获得加密文件的能力。

最佳答案

最后,我发现了问题,我没有初始化aesCipher。当我添加方法 aesCipher.init(true, aesCBCParams); 时它开始工作了。

我还更改了一些代码:

int numRead = 0;
while ((numRead = fin.read(buf)) >= 0) {
if (numRead == 1024) {
byte[] plainTemp = new byte[aesCipher.getUpdateOutputSize(numRead)];
int offset = aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);

final byte[] plain = new byte[offset];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
fout.write(plain, 0, plain.length);
} else {
byte[] plainTemp = new byte[aesCipher.getOutputSize(numRead)];
int offset = aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
final byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
fout.write(plain, 0, plain.length);
}
}

关于java - 如何使用 BouncyCaSTLe 轻量级 API 使用 PBE AES 加密/解密文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079058/

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