package com.hhhh;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DES3 {
/**
* content: 加密内容
* slatKey: 加密的盐,16位字符串
* vectorKey: 加密的向量,16位字符串
*/
public static String encrypt(String content, String slatKey, String vectorKey) throws Exception {
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "DESede");
IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return Base64.encode(encrypted);
}
/**
* content: 解密内容(base64编码格式)
* slatKey: 加密时使用的盐,16位字符串
* vectorKey: 加密时使用的向量,16位字符串
*/
public static String decrypt(String base64Content, String slatKey, String vectorKey) throws Exception {
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "DESede");
IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] content = Base64.decode(base64Content);
byte[] encrypted = cipher.doFinal(content);
return new String(encrypted);
}
//IV和key换成自己的
public static void main(String args[]){
String IV = "xxx";
final String key = "xxx";
// 加密流程
String telePhone = "15629551180";
try {
System.out.println("==========3des加密前============"+telePhone);
String encryptStr = encrypt(telePhone,key,IV);
System.out.println("==========3des加密后============"+encryptStr);
System.out.println("==========3des解密后============"+decrypt(encryptStr,key,IV));
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于 这里用到的加密模式是CBC ,填充是PKCS5Padding
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); 选的是加密模式和填充,至于如何写, 参考https://blog.csdn.net/BingHongChaZuoAn/article/details/101052613