参考:
http://blog.youkuaiyun.com/lvxiangan/article/details/72529221
和
https://www.jianshu.com/p/251a619864f3
直接上代码:
/**
* <pre>
* author : WangChaowei
* time : 2018/3/12.
* desc : 3DES 加解密
* 双倍长密钥:16位
* 三倍长密钥:24位
* 加密流程是:1、先用前8字节加密成TMP1,
* 2、再用中8字节解密TMP1成TMP2,
* 3、最后用后8字节加密TMP2。
* </pre>
*/
public class ThreeDESDemo {
private static final String Algorithm = "DESede";//定义加密算法(3DES)
private String keyString = "haha01234567899876543210";
private byte[] key = null; //密钥(16位/24位)
/**
* 加密
*
* @param data 加密数据
* @return
*/
public String encrypt3DES(String data) {
String result = null;
try {
//String转byte数组
this.key = keyString.getBytes("UTF-8");
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
//获取cipher对象
Cipher cipher = Cipher.getInstance(Algorithm);
//cipher初始化(加密)
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypt = cipher.doFinal(data.getBytes("UTF-8"));
//base64转码成String(不用base64转String,可能有异常)
result = new String(Base64.encode(encrypt, Base64.DEFAULT), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "密钥有误,byte数组16位/24位";
}
return result;
}
/**
* 解密
*
* @param data 解密数据
* @return
*/
public String decrypt3DES(String data) {
String result = null;
try {
SecretKey secretKey = new SecretKeySpec(this.key, Algorithm);
Cipher cipher = Cipher.getInstance(Algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes = Base64.decode(data.getBytes("UTF-8"), Base64.DEFAULT);
byte[] plain = cipher.doFinal(bytes);
result = new String(plain, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}