gpt4 book ai didi

java - 如何生成 256 位 AES key

转载 作者:行者123 更新时间:2023-11-30 02:47:11 34 4
gpt4 key购买 nike

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

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)

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

最佳答案

您更新了 JCE jar 吗?

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

Java 出厂时默认为 128 位。看一下然后告诉我

关于java - 如何生成 256 位 AES key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39853625/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com