/**
* @Author yanjun.hou
*/
public class TripleDESUtil {
public static final String CIPHERMODE = "DESede/ECB/PKCS5Padding";
public static final String ENCODE = "utf-8";
public static final String TRIPLEDES_KEY="1234567890qwertas";
/**
* 初始化密钥
* @return
* @throws Exception
*/
public static String getKeyStr() throws Exception{
return Base64.encodeBase64String(TRIPLEDES_KEY.getBytes());
}
/**
* 加密
* @param src
* @return
*/
public static String encrypt(String src) {
if (StringUtils.isBlank(src)) {
return "";
}
try {
DESedeKeySpec dks = new DESedeKeySpec(getKeyStr().getBytes(ENCODE));
SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(CIPHERMODE);
cipher.init(Cipher.ENCRYPT_MODE, securekey);
byte[] b = cipher.doFinal(src.getBytes());
return Base64.encodeBase64String(b).replaceAll("\r", "").replaceAll("\n", "");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 解密
* @param src
* @return
*/
public static String decrypt(String src) {
if (StringUtils.isBlank(src)) {
return "";
}
try {
byte[] bytesrc = Base64.decodeBase64(src);
DESedeKeySpec dks = new DESedeKeySpec(getKeyStr().getBytes(ENCODE));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(CIPHERMODE);
cipher.init(Cipher.DECRYPT_MODE, securekey);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}