前端(CryptoJS引用请自行百度):
var DES3 = {
iv: function() {
return $.WebSite.formatDate(new Date(), "yyyyMMdd")
},
encrypt: function(b, c, a) {
if (c) {
return (CryptoJS.TripleDES.encrypt(b, CryptoJS.enc.Utf8.parse(c), {
iv: CryptoJS.enc.Utf8.parse(a || DES3.iv()),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})).toString()
}
return ""
},
decrypt: function(b, c, a) {
if (c) {
return CryptoJS.enc.Utf8.stringify(CryptoJS.TripleDES.decrypt(b, CryptoJS.enc.Utf8.parse(c), {
iv: CryptoJS.enc.Utf8.parse(a || DES3.iv()),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})).toString()
}
return ""
}
};
var data = {
"secretKey": "zYYlOfutVxVTEr8gGhDvCQlc",
"result": "dEbXpRZOSVpvUYeNsTTXmAv6XcC+Gknoel6prVrhBl/caPo7rN81BCxLxWcB9WGhp8DOXq27iSmrylZn3mF90g==",
};
console.log(DES3.iv());
var decryptStr = DES3.decrypt(data.result, data.secretKey);
console.log(decryptStr);
var encryptStr = DES3.encrypt(decryptStr, data.secretKey);
console.log(encryptStr);
前端执行结果:
后端:
package com.utils.des;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TripleDES {
private static final String KEY_ALGORITHM = "DESede";
private static final String CIPHER_ALGORITHM = "DESede/CBC/PKCS5Padding";
private static final String keyHex = "zYYlOfutVxVTEr8gGhDvCQlc";
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dataStr = "{\"sampleId\":\"12345\",\"sampleData\":\"这是一条测试数据\"}";
String ivHex = sdf.format(new Date());
System.out.println(ivHex);
String encryptStr = new TripleDES().encrypt(dataStr, ivHex);
System.out.println(encryptStr);
String decryptStr = new TripleDES().decrypt(encryptStr, ivHex);
System.out.println(decryptStr);
}
public String encrypt(String message, String ivHex) throws Exception {
final SecretKey key = new SecretKeySpec(keyHex.getBytes("utf-8"), KEY_ALGORITHM);
final IvParameterSpec iv = new IvParameterSpec(ivHex.getBytes("utf-8"));
final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return new sun.misc.BASE64Encoder().encode(cipherText);
}
public String decrypt(String message, String ivHex) throws Exception {
final SecretKey key = new SecretKeySpec(keyHex.getBytes("utf-8"), KEY_ALGORITHM);
final IvParameterSpec iv = new IvParameterSpec(ivHex.getBytes("utf-8"));
final Cipher decipher = Cipher.getInstance(CIPHER_ALGORITHM);
decipher.init(Cipher.DECRYPT_MODE, key, iv);
final byte[] plainText = decipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(message));
return new String(plainText, "UTF-8");
}
}
后端执行结果: