如何生成256位AES密钥

时间:2016-10-04 13:27:18

标签: java encryption aes

为了生成256位的AES密钥,我编写了以下代码:

KeyGenerator keyGen;

try {
  keyGen = KeyGenerator.getInstance("AES");
  keyGen.init(256);
  SecretKey secretKey = keyGen.generateKey();
  return secretKey;    
}
catch (Exception e) {
  e.printStackTrace();
  return null;
}

我的加密方法是:

  private byte[] aes256Encode(SecretKey key, IvParameterSpec iv, String message) throws InvalidKeyException,
      InvalidAlgorithmParameterException,
      NoSuchAlgorithmException, NoSuchPaddingException,
      IllegalBlockSizeException, BadPaddingException 
  {
    Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] encrypted = cipher.doFinal(message.getBytes());
    return encrypted;
  }

和IV生成方法是:

  private IvParameterSpec generateAESIV() {
    // build the initialization vector (randomly).
    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[16];//generate random 16 byte long
    random.nextBytes(iv);
    IvParameterSpec ivspec = new IvParameterSpec(iv);
    return ivspec;
  }

但是在加密时,它会抛出以下错误:

Exception in thread "main" java.security.InvalidKeyException: Illegal key size
    at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
    at javax.crypto.Cipher.implInit(Cipher.java:805)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1396)
    at javax.crypto.Cipher.init(Cipher.java:1327)

有人能指出我在这里犯的错误吗?

2 个答案:

答案 0 :(得分:1)

您是否更新了JCE罐?。

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

Java出货时默认为128位。看看,让我知道

答案 1 :(得分:1)

更改此行

keyGen.init(256);

keyGen.init(128);

默认情况下,Java仅支持128位加密。

修改: 如果您需要使用大于128位的密钥加密内容,则必须使用Java Cryptography Extension (JCE)