AES 256 Encryption Issue

半世苍凉 提交于 2019-12-03 20:33:23

问题


The following code perfectly implements AES-128 encryption/decryption.

public static void main(String[] args) throws Exception
{
    String input = JOptionPane.showInputDialog(null, "Enter your String");
    System.out.println("Plaintext: " + input + "\n");

    // Generate a key
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128); 
    byte[] key = keygen.generateKey().getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

    // Generate IV randomly
    SecureRandom random = new SecureRandom();
    byte[] iv = new byte[16];
    random.nextBytes(iv);
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    // Initialize Encryption Mode
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);

    // Encrypt the message
    byte[] encryption = cipher.doFinal(input.getBytes());
    System.out.println("Ciphertext: " + encryption + "\n"); //

    // Initialize the cipher for decryption
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);

    // Decrypt the message
    byte[] decryption = cipher.doFinal(encryption);
    System.out.println("Plaintext: " + new String(decryption) + "\n");
}

When I want to use AES-256, I thought that can be done by just modifying keygen.init(256); and byte[] iv = new byte[32];, however this becomes error (Exception in thread "main" java.security.InvalidKeyException: Illegal key size)! Can someone explain why error occurs when I made these two modification and what should I do. Thank you guys :)


回答1:


If you want to use AES 256 encryption you must install the Unlimited Strength Jurisdiction Policy Files:

http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

This enables the higher encryption levels like AES 256 and RSA 2048.

Replace the files from the zip with the current ones in <java-home>\lib\security.



来源:https://stackoverflow.com/questions/23597984/aes-256-encryption-issue

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