import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DesUtil {
private final static String DES = "DES";
public static final String CLUB_KEY = "47poksdfj2";
public static byte[] encrypt(byte[] data,byte[] key) throws Exception{
//生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
//从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
//创建一个密钥工厂,然后用他把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, sr);
byte[] arrB = cipher.doFinal(data);
int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString().getBytes();
}
/**
* 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
return new String(bt,"utf-8");
}
/**
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] arrB, byte[] key) throws Exception {
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
try {
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
} catch (Exception e) {
}
}
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把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, sr);
return cipher.doFinal(arrOut);
}
/**
* 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
public static String decrypt(String data, String key) throws Exception {
if (data == null) {
return null;
}
byte[] buf = data.getBytes("utf-8");
//byte[] buf = Base64Binrary.decodeBase64Binrary(data);
byte[] bt = decrypt(buf,key.getBytes());
return new String(bt,"utf-8");
}