- 论坛徽章:
- 0
|
1. 首先下载jce的jar包,这个包里含有加密的工具类,使用方便,下载地址是:
http://java.sun.com/products/archive/jce/
2. 解压缩后可以看到lib下的jar包,将它们拷入到%JAVA_HOME%\lib\ext目录下,然后在CLASSPATH中添加这个路径。也可以在需要时添加到项目的类路径里。
3. 加密方法:
//使用指定的密钥对信息加密
public static String encyptInfo(String info,String secretKey) throws Exception{
//从密钥中读取SecretKey对象
byte a[] = hex2byte(secretKey);
java.io.ByteArrayInputStream byteIn = new java.io.ByteArrayInputStream(a);
java.io.ObjectInputStream in2 = new java.io.ObjectInputStream(byteIn);
SecretKey deskey = (SecretKey) in2.readObject();
//获得加密类的实例,algorithm可取DES,DESeda等
Cipher c1 = Cipher.getInstance(algorithm);
//初始化方式为加密
c1.init(Cipher.ENCRYPT_MODE, deskey);
//执行加密,得到加密后的字节
byte[] cipherByte = c1.doFinal(info.getBytes());
return byte2hex(cipherByte);
}
4. 解密方法:
//使用指定的密钥对信息解密
public static String decyptInfo(String clipher,String secretKey) throws Exception{
//从密钥中读取SecretKey对象
byte a[] = hex2byte(secretKey);
java.io.ByteArrayInputStream byteIn = new java.io.ByteArrayInputStream(a);
java.io.ObjectInputStream in2 = new java.io.ObjectInputStream(byteIn);
SecretKey deskey = (SecretKey) in2.readObject();
//获得解密类的实例,algorithm可取DES,DESeda等
Cipher c1 = Cipher.getInstance(algorithm);
//初始化方式为解密
c1.init(Cipher.DECRYPT_MODE, deskey);
//执行解密,得到解密后的字节
byte[] infoByte = c1.doFinal(hex2byte(clipher));
return new String(infoByte);
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/20181/showart_1888963.html |
|