主要步骤如下:
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(数据)执行加密解密操作
代码如下:
1 //加密 2 private byte[] desEncrypt(byte[] data, byte[] key) throws Exception { 3 SecureRandom sr = new SecureRandom(); 4 DESKeySpec dks = new DESKeySpec(key); 5 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 6 SecretKey securekey = keyFactory.generateSecret(dks); 7 Cipher cipher = Cipher.getInstance("DES"); 8 cipher.init(1, securekey, sr); 9 return cipher.doFinal(data); 10 } 11 //解密 12 private byte[] desDecrypt(byte[] data, byte[] key) throws Exception { 13 SecureRandom sr = new SecureRandom(); 14 DESKeySpec dks = new DESKeySpec(key); 15 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 16 SecretKey securekey = keyFactory.generateSecret(dks); 17 Cipher cipher = Cipher.getInstance("DES"); 18 cipher.init(2, securekey, sr); 19 return cipher.doFinal(data); 20 }
因为加密完数据时byte[]类型的,因此使用sun.misc包下的BASE64Encoder类将二进制类型编码转换成String,如:
String str = (new BASE64Encoder()).encode(bt);