主要步骤如下:
1.利用SecretKeyFactory.getInstance("加密算法")创建密钥工厂,加密算法如"DES","AES"等
2.用new DESKeySpec(原始密钥)产生密钥对象,原始密钥是byte[]类型的
3.用密钥工厂的generateSecret(密钥对象)方法把密钥对象转换成规范的密钥对象
4.用new SecureRandom()或者用new IvParameterSpec(向量)生成一个可信任的随机数源
5.用Cipher.getInstance(“加密算法/加密模式/填充模式”)产生加密解密对象
6.用cipher.init(加密解密模型,规范密钥,随机数)初始化加密解密对象
7.用cipher.doFinal(数据)执行加密解密操作
代码如下:
//加密
private byte[] desEncrypt(byte[] data, byte[] key) throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(1, securekey, sr);
return cipher.doFinal(data);
}
//解密
private byte[] desDecrypt(byte[] data, byte[] key) throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(2, securekey, sr);
return cipher.doFinal(data);
}
因为加密完数据时byte[]类型的,因此使用sun.misc包下的BASE64Encoder类将二进制类型编码转换成String,如:
String str = (new BASE64Encoder()).encode(bt);