算法实现
public class DESUtil{
privatefinal static String DES = "DES";
privatefinal static String CDES = "DES/CBC/PKCS5Padding";
/**
*Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
publicstatic String encrypt(String data, String key, String iv)
throwsException {
byte[]bt = encrypt(data.getBytes("UTF-8"),key.getBytes("UTF-8"),iv.getBytes("UTF-8"));
//加密后进行64位编码处理
returnnew BASE64Encoder().encode(bt);
}
/**
*Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws IOException
* @throws Exception
*/
publicstatic String decrypt(String data, String key,String iv) throws IOException,
Exception{
if(data == null)
{
returnnull;
}
//解密前进行64位编码解析
byte[]buf = new BASE64Decoder().decodeBuffer(data);
byte[]bt = decrypt(buf,key.getBytes("UTF-8"),iv.getBytes("UTF-8"));
returnnew String(bt);
}
/**
*Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
privatestatic byte[] encrypt(byte[] data, byte[] key,byte[] iv) throws Exception {
//iv
IvParameterSpec ivps = newIvParameterSpec(iv);
// 从原始密钥数据创建DESKeySpec对象
DESKeySpecdks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactorykeyFactory = SecretKeyFactory.getInstance(DES);
SecretKeysecurekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Ciphercipher = Cipher.getInstance(CDES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE,securekey, ivps);
returncipher.doFinal(data);
}
/**
*Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
privatestatic byte[] decrypt(byte[] data, byte[] key,byte[] iv) throws Exception {
//iv
IvParameterSpec ivps = newIvParameterSpec(iv);
// 从原始密钥数据创建DESKeySpec对象
DESKeySpecdks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactorykeyFactory = SecretKeyFactory.getInstance(DES);
SecretKeysecurekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Ciphercipher = Cipher.getInstance(CDES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE,securekey, ivps);
returncipher.doFinal(data);
}
}
调用测试
Stringkey = "1qaz!@#$";
Stringiv = "!QAZ1234";
Stringdata = "sys";
Strings="";
try{
s=DESUtil.encrypt(data,key, iv);
s=DESUtil.decrypt(s,key, iv);
}catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);