1. 导入依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
2. 编写工具类
密钥可以自己随意定义
public class SecretUtils {
private static Logger logger = LoggerFactory.getLogger(SecretUtils.class);
/**
* 转换成十六进制字符串
*
* @param
* @return
*/
public static byte[] hex(String key) {
String f = DigestUtils.md5Hex(key);
byte[] bkeys = f.getBytes();
byte[] enk = new byte[24];
for (int i = 0; i < 24; i++) {
enk[i] = bkeys[i];
}
return enk;
}
/**
* 3DES加密
*
* @param key 密钥,24位
* @param srcStr 将加密的字符串
* @return
*/
public static String encode3Des(String key, String srcStr) {
try {
byte[] keybyte = hex(key);
byte[] src = srcStr.getBytes();
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
//加密
Cipher c1 = Cipher.getInstance("DESede");
c1.init(Cipher.ENCRYPT_MODE, deskey);
String pwd = Base64.getUrlEncoder().encodeToString(c1.doFinal(src));
return pwd;
} catch (Exception e) {
logger.error("func[encode3Des]" + srcStr + "异常信息:", e);
}
return null;
}
/**
* 3DES解密
*
* @param key 加密密钥,长度为24字节
* @param desStr 解密后的字符串
* @return lee on 2017-08-09 10:52:54
*/
public static String decode3Des(String key, String desStr) {
try {
byte[] keybyte = hex(key);
byte[] src = Base64.getUrlDecoder().decode(desStr);
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
//解密
Cipher c1 = Cipher.getInstance("DESede");
c1.init(Cipher.DECRYPT_MODE, deskey);
String pwd = new String(c1.doFinal(src));
return pwd;
} catch (Exception e) {
logger.error("func[decode3Des]" + desStr + "异常信息:", e);
}
return null;
}
}