/**
* 默认值:DESede/CBC/PKCS5Padding
* 经验证使用initKeyWithPadding方式生产密钥时,和网站:http://tool.chacuo.net/crypt3des,结果相同
*
* @version 1.0
* @since 1.0
*/
public abstract class DESCoder {
public static final String VI = "01234567";
/**
* 转换密钥
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(String key) throws Exception {
// DESKeySpec dks = new DESKeySpec(key.getBytes());
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
// SecretKey secretKey = keyFactory.generateSecret(dks);
// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DESede");
return secretKey;
}
/**
* 解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
Key k = toKey(key);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(VI.getBytes());
cipher.init(Cipher.DECRYPT_MODE, k, ips);
return cipher.doFinal(data);
}
/**
* 生成密钥
*
* @return
* @throws Exception
*/
public static String initKey(String password) throws Exception {
return initKeyWithPadding(password);
}
/**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
Key k = toKey(key);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(VI.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, k, ips);
return cipher.doFinal(data);
}
/**
* 通过MD5的方式,生成密钥
*
* @param password
* @return
* @throws Exception
*/
public static String initKeyWithMd5(String password) throws Exception {
return Md5Utils.hash(password).substring(0, 24);
}
/**
* 不足24位时,通过填充的方式生产密钥
* @param password
* @return
* @throws Exception
*/
public static String initKeyWithPadding(String password) throws Exception {
if (password.length() >= 24) {
return password;
} else {
byte[] bytes = password.getBytes();
byte[] result = new byte[24];
System.arraycopy(bytes,0,result,0,bytes.length);
return new String(result);
}
}
public static void main(String[] args) throws Exception {
String str = "ilkYC37ksDM=";
byte[] hh = Coder.decryptBASE64(str);
byte[] rr = DESCoder.decrypt(hh, DESCoder.initKey("123456"));
System.out.println(new String(rr));
byte[] uu = DESCoder.encrypt("hello".getBytes("UTF-8"), DESCoder.initKey("123456"));
System.out.println(Coder.encryptBASE64(uu));
}
}