【发布时间】:2011-11-10 11:51:12
【问题描述】:
我正在尝试使用 AES 使用 PBE 加密/解密文件。我正在使用 Bouncy Casle 库(轻量级 API),因为我需要忽略对密钥长度的限制。我找到了函数并更改了其中的一些代码。
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:垫块损坏
在 org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(未知来源)
在 org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(未知来源)
我可以做些什么来消除这个错误?以及我必须在此功能中进行哪些更改才能获得加密文件的能力。
【问题讨论】:
-
您考虑过使用
CipherInputStream和CipherOutputStream类吗?让你的代码更简单。
标签: java encryption cryptography aes bouncycastle