Bouncy Castle AES-256解密失败

时间:2018-05-25 15:40:01

标签: java aes 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)

使用以下代码..

public byte[] encryptAES256(byte[] input, byte[] key) throws InvalidCipherTextException {
    assert key.length == 32;
    CipherParameters cipherParameters = new KeyParameter(key);
    BlockCipher blockCipher = new AESEngine();
    BlockCipherPadding blockCipherPadding = new PKCS7Padding();
    BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding);
    return encrypt(input, bufferedBlockCipher, cipherParameters);
}

public byte[] decryptAES256(byte[] input, byte[] key) throws InvalidCipherTextException {
    assert key.length == 32;
    CipherParameters cipherParameters = new KeyParameter(key);
    BlockCipher blockCipher = new AESEngine();
    BlockCipherPadding blockCipherPadding = new PKCS7Padding();
    BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding);
    return decrypt(input, bufferedBlockCipher, cipherParameters);
}

public byte[] process(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters, boolean forEncryption) throws InvalidCipherTextException {
    bufferedBlockCipher.init(forEncryption, cipherParameters);
    byte[] rv = new byte[bufferedBlockCipher.getOutputSize(input.length)];
    int tam = bufferedBlockCipher.processBytes(input, 0, input.length, rv, 0);
    try {
        bufferedBlockCipher.doFinal(rv, tam);
        return rv;
    } catch (Exception e) {
        e.printStackTrace();
    }
   return rv; 
}

public byte[] decrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, 
    CipherParameters cipherParameters) throws InvalidCipherTextException {
    boolean forEncryption = false;
    return process(input, bufferedBlockCipher, cipherParameters, forEncryption);
}

有人可以帮我弄清楚为什么我会得到这个例外吗?

1 个答案:

答案 0 :(得分:0)

无论何时忽略返回值,都应该暂停。您忽略了bufferedBlockCipher.doFinal(rv, tam)方法中process的返回值。我相信,在您的代码中,这只会在解密操作期间导致问题。请注意,bufferedBlockCipher.getOutputSize(input.length)将返回一个最小长度的值,不一定是精确的长度。换句话说,它可能有点太大了。 doFinal方法将在删除填充后为您提供最后一个块的实际大小。然后,您可以使用简单的java.util.Arrays.copyOf(...)之类的东西返回正确大小的数组,例如

int lastBlockLen = bufferedBlockCipher.doFinal(rv, tam);
return Arrays.copyOf(rv, tam + lastBlockLen);