How to use Bouncy Castle lightweight API with AES and PBE

前端 未结 4 967
清酒与你
清酒与你 2020-12-08 17:47

I have a block of ciphertext that was created using the JCE algorithim \"PBEWithSHA256And256BitAES-CBC-BC\". The provider is BouncyCastle. What I\'d like to do it decrypt th

4条回答
  •  自闭症患者
    2020-12-08 18:18

    There were a few problems with your decrypt method:

    private static byte[] decrypt(final byte[] bytes, final char[] password, final byte[] salt) throws DataLengthException, IllegalStateException, InvalidCipherTextException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    
        final PBEParametersGenerator keyGenerator = new PKCS12ParametersGenerator(new SHA256Digest());
        keyGenerator.init(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password), salt, 20);
        final CipherParameters keyParams = keyGenerator.generateDerivedParameters(256, 128);
    
        final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
        cipher.init(false, keyParams);
    
        final byte[] processed = new byte[cipher.getOutputSize(bytes.length)];
        int outputLength = cipher.processBytes(bytes, 0, bytes.length, processed, 0);
        outputLength += cipher.doFinal(processed, outputLength);
    
        final byte[] results = new byte[outputLength];
        System.arraycopy(processed, 0, results, 0, outputLength);
        return results;
    }
    

    The main problems were the way you were carrying out the decryption without using a block cipher and the missing IV size to the generateDerivedParameters method. I saw the first problem pretty quickly, the 2nd one was much less obvious. I only discovered that one through looking at a Bouncy Castle test called PBETest.

提交回复
热议问题