Java DES3加密,包含密钥,日期偏移量,明文
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class DESUtil {
private static String encoding = "gb2312";
private static String data = "{\"parkCode\":\"1\",\"plateNo\":\"京A11113\"}";
/**
获取当前日期:yyyyMMdd
*/
public static String getNowDateYMD() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(date);
}
/**加密*/
public static String encrypt(String key, String iv, String data) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "desede");
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ips);
byte[] encryptData = cipher.doFinal(data.getBytes(encoding));
return Base64.getEncoder().encodeToString(encryptData);
}
/**解密*/
public static String decrypt(String key, String iv, String data) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "desede");
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKey, ips);
byte[] decryptData = cipher.doFinal(Base64.getDecoder().decode(data.getBytes(encoding)));
return new String(decryptData, "GB2312");
}
/**测试*/
public static void main(String[] args) throws Exception {
String key = "693207DB8148FBC9D8410179";
String iv = "20190225";
String encryption = encrypt(key, iv, data);
System.out.println(encryption);
String decryption = decrypt(key, iv, encryption);
System.out.println(decryption);
}
}