【发布时间】:2014-05-11 21:12:54
【问题描述】:
以下代码完美实现了AES-128加密/解密。
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");
}
当我想使用 AES-256 时,我认为可以通过修改 keygen.init(256); 和 byte[] iv = new byte[32]; 来完成,但这会变成错误(线程“main”中的异常 java.security.InvalidKeyException:非法密钥大小) !有人可以解释为什么在我进行这两个修改时会发生错误以及我应该怎么做。谢谢各位:)
【问题讨论】:
-
你得到什么错误?
-
线程“主”java.security.InvalidKeyException 中的异常:非法密钥大小
-
InvalidKeyException: Illegal key size表示您没有安装无限的策略文件或将它们放入错误的目录。您可以使用Cipher.getMaxAllowedKeyLength( "AES/CBC/PKCS5Padding" )来检查您是否正确安装它们:如果输出为128,那么加密仍然是有限的。 -
AES 192 和 AES 256 的 IV 大小是相同的 16 字节 - 无论密钥大小如何,AES 块大小始终为 128 位。
标签: java encryption cryptography aes