public class DesUtils {
//DES加密和解密过程中,密钥长度都必须是8的倍数
private static final String PASSWORD = "abcdefghijklmnopqrstuvwx";
private static final String CHARSET = "UTF-8";
/**
*
* <pre>功能描述: 加密
*/
private static byte[] encrypt(byte[] datasource) throws Exception {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(PASSWORD.getBytes());
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
//Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//现在,获取数据并加密
return cipher.doFinal(datasource);
}
/**
*
* <pre>功能描述: 解密
*/
private static byte[] decrypt(byte[] src) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
// 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(PASSWORD.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
return cipher.doFinal(src);
}
/**
*
* <pre>功能描述: 数据加密
*/
public static String encrypt(String srcStr) throws Exception {
byte[] src = srcStr.getBytes(Charset.forName(CHARSET));
byte[] buf = encrypt(src);
return DesUtils.parseByte2HexStr(buf);
}
/**
*
* <pre>功能描述: 数据解密
*/
public static String decrypt(String hexStr) throws Exception {
byte[] src = DesUtils.parseHexStr2Byte(hexStr);
byte[] buf = decrypt(src);
return new String(buf, Charset.forName(CHARSET));
}
/**
*
* <pre>功能描述: 将二进制转换成16进制
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
*
* <pre>功能描述: 将16进制转换为二进制
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}