Java 无法解密AES-256密码文本
我得到这个错误: 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)Java 无法解密AES-256密码文本,java,encryption,bouncycastle,Java,Encryption,Bouncycastle,我得到这个错误: 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) 输
输出通常是填充的,并且比输入长。您不应该截断输出。我已经删除了用于截断的代码,但仍然得到了相同的异常。我发现的另一个问题是,我在doFinal(output,outputfoffset)上遇到了这个异常;这条线。我的解密在使用相同代码的16个字符以下工作正常,但不能使用超过16个字符。Q没有指定模式,但因为它明显使用pkcs7填充,密文比明文长,而解密时,密文是输入,明文是输出,因此输出较短,根据
processBytes
和doFinal
的返回值计算的outputLength
是正确的长度(如果调用成功)。虽然原则上填充错误可能是由发送方中的错误引起的,但99.99%的时间是因为您的密钥、IV和/或密文错误或被修改,或者您使用了错误的模式或填充。你没有说或展示任何关于如何处理这些问题的信息,因此不可能给出任何有用的建议。FYIjava.util.Arrays.copyOf(byte[],int)
是最简单的2-3个语句的替代品。公共字节[]decryptAES256(byte[]输入,byte[]密钥)抛出InvalidCipherTextException{assert key.length==32;//32字节==256位密码参数密码参数=新的密钥参数(密钥);BlockCipher BlockCipher=new AESEngine();blockcipherpading blockcipherpading=new PKCS7Padding();BufferedBlockCipher BufferedBlockCipher=new paddedbufferedbufferedblockcipher(BlockCipher,blockcipherpading);return decrypt(输入,BufferedBlockCipher,cipher参数);}这是否澄清了问题?我正在使用PKCS7Padding进行加密和解密。请不要在注释中添加代码,它不可读。请不要把你的问题放在评论中,堆栈策略是把问题放在问题中。
public byte[] process(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters, boolean forEncryption) throws InvalidCipherTextException {
bufferedBlockCipher.init(forEncryption, cipherParameters);
int inputOffset = 0;
int inputLength = input.length;
int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength);
byte[] output = new byte[maximumOutputLength];
int outputOffset = 0;
int outputLength = 0;
int bytesProcessed;
bytesProcessed = bufferedBlockCipher.processBytes(
input, inputOffset, inputLength,
output, outputOffset
);
outputOffset += bytesProcessed;
outputLength += bytesProcessed;
bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset);
outputOffset += bytesProcessed;
outputLength += bytesProcessed;
if (outputLength == output.length) {
return output;
} else {
byte[] truncatedOutput = new byte[outputLength];
System.arraycopy(
output, 0,
truncatedOutput, 0,
outputLength
);
return truncatedOutput;
}
}