JAVA AES 256 Decrypt [duplicate]

2020-06-27 12:08发布

问题:

I'm trying to decrypt with AES some data. I've been given a 256 bit key and 16 byte IV like these:

  String key = "Hh1s1f4T2mpN3yCh4ngeL8t3r\\.Thxpp";

  int[] v = {11, 1, 555, 222, 241, 21, 11, 33, 35, 91, 45, 6, 14, 30, 22, 234};

  String IV = Arrays.toString( v );

I've been told the padding should be PKCS7 but when I init the cipher with AES/CBC/PKCS7PADDING it says: Cannot find any provider supporting AES/CBC/PKCS7PADDING

If I use AES/CBC/PKCS5PADDING I get Illegal key size but I've checked that the key size is 32.

  public static String decrypt(String key, String initVector, String encrypted) {
    try {
        System.out.println( "Key size: " + key.getBytes("UTF-8").length ); 

        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;
 }

回答1:

If you are getting an IllegalKeySize exception with AES-256, check to ensure you have the JCE Unlimited Cryptographic Strength Policy files installed in your active JVM. They are required for any AES key length over 128 bits.

(PKCS #7 padding scheme is effectively equivalent to PKCS #5 in Java (the block size differs in the spec definitions), but Java never added the PKCS #7 name to its list, so using PKCS5Padding is correct.)



回答2:

First see the answer by @Andy.

If you are getting an "Illegal key size" error then the key size is incorrect, you need to figure out why by debugging. Create a variable for the UTF-8 key

byte[] keyBytes = key.getBytes("UTF-8")

and display it as hex, that way you can see exactly what it happening.

Inline conversions are essentially impossible to debug.

PKCS#5 padding is a subset of PKCS#7 padding and in every instance it is the same, PKCS#5 is just a name holdover from DES by lazy developers.

PKCS#7 padding:

PKCS#5 padding is identical to PKCS#7 padding, except that it has only been defined for block ciphers that use a 64-bit (8 byte) block size. In practice the two can be used interchangeably.



回答3:

You need to use bouncy castle as a provider for PKCS7PADDING.