加密Util
public class CryptUtil {
private static final String DES = "DES";
private static final String ISO = "ISO-8859-1";
private static final String GBK = "GBK";
private static final String MD5 = "MD5";
public static String encryptDES(String data, String key) throws Exception {
// 将字符串转换成byte类型数组,实质是各个字符的二进制形式
byte ptext[] = data.getBytes(GBK);
// 二进制串转换为一个大整数
BigInteger m = new BigInteger(ptext);
// m为密文的BigInteger类型
byte[] mt = m.toByteArray();
data = new String(mt, ISO);
// 给定的密钥内容需要8个字节
if (key.length() < 8) {
int len = 8 - key.length();
for (int i = 0; i < len; i++) {
key = key + " ";
}
}
// Key全部变小写
key = key.toLowerCase();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key.getBytes(ISO));
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey);
return new String(cipher.doFinal(data.getBytes(ISO)), ISO);
}
public static String decryptDES(String data, String key) throws Exception {
// 给定的密钥内容需要8个字节
if (key.length() < 8) {
int len = 8 - key.length();
for (int i = 0; i < len; i++) {
key = key + " ";
}
}
// Key全部变小写
key = key.toLowerCase();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key.getBytes(ISO));
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey);
// 将byte类型数组转换成字符串,实质是各个字符的二进制形式
String deMt = new String(cipher.doFinal(data.getBytes(ISO)), ISO);
String str = new String(deMt.getBytes(ISO), GBK);
return str;
}
public static String getMD5(String data) throws Exception {
// 用来将字节转换成 16 进制表示的字符
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
byte[] btInput = data.getBytes();
// MD5哈希化
MessageDigest mdInst = MessageDigest.getInstance(MD5);
mdInst.update(btInput);
byte[] md = mdInst.digest();
char str[] = new char[md.length * 2];
int k = 0;
// 每一个字节转换成 16 进制字符
for (int i = 0; i < md.length; i++) {
// 取第 i 个字节
byte byte0 = md[i];
// 取字节中高 4 位(左边四位)的数字转换,>>>为逻辑右移,右移后,高四位变成低四位,需要对低四位之外的值进行消零运算
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
// 取字节中低 4 位(右边四位)的数字转换,并且和0xf进行"逻辑与"运算,以消除高位的值,得到纯净的低四位值
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
}