简体   繁体   中英

How to switch between AES-128, AES-192 and AES-256

How can I switch between AES-128 , AES-192 and AES-256 . My present implementation uses only AES-128

Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
IvParameterSpec ivspec = new IvParameterSpec(initialztnVector);
cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
byte[] enc = cipher.doFinal(toEncrypt);

Changing to Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Will it make AES-256 possible ? What should I do to have AES-192

The library decides on the AES key length based on the length of the supplied key. Sloppy, explicitly specifying would be more clear. Do make sure the supplied key is exactly the correct length, do not rely on key padding.

The padding has no relationship to the key size. Padding is necessary if the plain text input data length is not always (or a priori) an exact multiple of the block size (16-bytes for AES).

Note the comment by @KevinO about using the correct .jar file.

As already mentioned by @zaph, just provide a 256bit key as input and it works (regardless of the mode (eg CBC) or Padding used).

Also, as referred by @KevinO, you may have to install the Unlimited Strength Policy Files ( here for Java 8) to support 256 bits of AES security.

Sometimes however, especially if you need to distribute your software, it is not always possible to change the Policy Files on your client's machine. Although not recommended as you may violate the Java License Agreement , you can use reflection to bypass the restrictions without changing the default Policy Files. Ported from this link , just use this snippet that will run during class loading. Then, you can use any supported key size.

static {
    try {
        Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
        field.setAccessible(true);
        field.set(null, java.lang.Boolean.FALSE);
    } catch (Exception ex) {
    //Report the exception
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM