How to decrypt aes-256-cbc in Java

ぐ巨炮叔叔 提交于 2019-12-06 07:37:35

Below is the encryption and decryption process for a string using AES algorithm.

 private static final String key = "aesEncryptionKey";
    private static final String initVector = "encryptionIntVec";

    public static String encrypt(String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

public static String decrypt(String encrypted) {
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

In case init vector is not known, try using below code segment.

public byte[] decrypt(String encryptedString) throws DataLengthException, InvalidCipherTextException {

        byte[] input = encryptedString.getBytes("UTF-8");
        CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
        SecureRandom random = new SecureRandom();;
        KeyParameter key = new KeyParameter("$secretHash".getBytes());// your key string
        BlockCipherPadding blockCipherPadding = new PKCS7Padding();;
        PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, blockCipherPadding);

        int blockSize = cbcBlockCipher.getBlockSize(); // Make sure this block size is same as that used while encrypting the string.
        int inputOffset = 0;
        int inputLength = input.length;
        int outputOffset = 0;

        byte[] initializationVector = new byte[blockSize];

        System.arraycopy(input, 0, initializationVector, 0, blockSize);
        inputOffset += blockSize;
        inputLength -= blockSize;

        pbbc.init(encrypt, new ParametersWithIV(key, initializationVector));
        byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];

        int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);

        outputLength += pbbc.doFinal(output, outputLength);

        return Arrays.copyOf(output, outputLength);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!