[英]AES 256 Encryption Issue
以下代码完美实现了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);
来完成keygen.init(256);
和byte[] iv = new byte[32];
,但是这将成为错误(线程“ main”中的异常java.security.InvalidKeyException:密钥大小非法)! 有人可以解释为什么我进行这两个修改时会发生错误,并且该怎么办。 感谢大伙们 :)
如果要使用AES 256加密,则必须安装无限强度辖区策略文件:
http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
这样可以实现更高的加密级别,例如AES 256和RSA 2048。
将zip中的文件替换为<java-home>\\lib\\security
的当前文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.