//DES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
private final static String TRANSFORMATION = "DES/CBC/PKCS5Padding";
//初始化向量参数,AES 为16bytes. DES 为8bytes.
private final static byte[] IVPARAMETERSPEC = {0,0,0,0,0,0,0,0};
//DES是加密方式
private final static String ALGORITHM = "DES";
/**
* DES算法,加密
*
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
*/
public static String encode(String key, byte[] data) {
try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC);
cipher.init(Cipher.ENCRYPT_MODE, getRawKey(key), iv);
byte[] bytes = cipher.doFinal(data);
return bytes2HexString(bytes);
} catch (Exception e) {
return null;
}
}
/**
* 字节数组转16进制字符串;
* @param array 数组
* @return string
*/
private static String bytes2HexString(byte[] array) {
StringBuilder builder = new StringBuilder();
for (byte b : array) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
builder.append(hex);
}
return builder.toString().toUpperCase();
}
// 对密钥进行处理
private static Key getRawKey(String key) throws Exception {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
return keyFactory.generateSecret(dks);
}
/**
* 解密
*
*/
public static byte[] decrypt(byte[] src, String password) 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);
}
网友评论