java中的AES 256算法遇到 Illegal key size or default parameters错的解决办法

报错堆栈如下:

Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
    at my.package.Something.decode(RC4Decoder.java:25) ~[my.package.jar:na]

Google到问题原因,链接地址如下:

http://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters

根据回答找到下载新jar包(JDK6)链接地址如下:

http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

JDK7 的地址如下:

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

把里面的两个jar包:local_policy.jar 和 US_export_policy.jar 替换掉原来安装目录C:\Program Files\Java\jre6\lib\security 下的两个jar包接可以了

然后就重新运行程序,不会报错了,测试代码如下:

public class Test {
	public static void main(String[] args) throws Exception {
		 KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		 keyGen.init(256);
		 SecretKey key = keyGen.generateKey();
		 ObjectOutputStream oop = new ObjectOutputStream(new
		 FileOutputStream("c:\\key.dat"));
		 oop.writeObject(key);
		 oop.close();
		
		String strTest = "Hello, Jason";
		byte[] strAfterAES = encryptData(strTest.getBytes());
		System.out.println(new String(strAfterAES));
		byte[] strOriContent = decryptData(strAfterAES);
		System.out.println(new String(strOriContent));
	}


	public static byte[] encryptData(byte[] input) throws Exception {
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("c:\\key.dat"));
		SecretKey aeskey = (SecretKey) in.readObject();
		Cipher c1 = Cipher.getInstance("AES");
		c1.init(Cipher.ENCRYPT_MODE, aeskey);
		byte[] cipherByte = c1.doFinal(input);
		return cipherByte;
	}


	public static byte[] decryptData(byte[] input) throws Exception {
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("c:\\key.dat"));
		SecretKey aeskey = (SecretKey) in.readObject();
		Cipher c1 = Cipher.getInstance("AES");
		c1.init(Cipher.DECRYPT_MODE, aeskey);
		byte[] clearByte = c1.doFinal(input);
		return clearByte;
	}
}


BTW:

 If ur JVM is IBM JVM pls refer to the below link to update the unlimited key size jars

http://pic.dhe.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=%2Fcom.ibm.websphere.nd.multiplatform.doc%2Finfo%2Fae%2Fae%2Ftwbs_tunev6wss.html




  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值