我有一个会话密钥,它随着程序的每次执行而变化。我必须使用该会话密钥(AES 256)加密一个字节[],所以如何做到这一点。
我正在生成我的密钥
Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(rand);
generator.init(256);
key = generator.generateKey();
并使用它来加密字节数组
public static byte[] Encrypt(byte[] a,Key skey) throws Exception {
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skey);
byte[] encrypted =cipher.doFinal(a);
cipher.init(Cipher.DECRYPT_MODE, skey);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
return encrypted;
}
但是每次我运行程序时它都会显示错误
Exception in thread "main" java.security.InvalidKeyException: Illegal
key size or default parameters
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1026)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at com.esign.verify.DocHash.AES.Encrypt(AES.java:52)
at com.esign.verify.DocHash.DocHash.main(DocHash.java:264)