package com.topnet.utils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
public class TripleDESNew {
//支持PKCS7Padding、默认只支持PKCS5Padding
static {
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
} else {
Security.removeProvider("BC");
Security.addProvider(new BouncyCastleProvider());
}
}
// 加密
public static String Encrypt(String sSrc, String sKey) throws Exception {
byte[] key = sKey.getBytes();//秘钥必须是24位
byte[] plainText = sSrc.getBytes("utf-8");
SecretKey secretKey = new SecretKeySpec(key, "DESede");
//encrypt
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(plainText);
System.out.println("encrypt_3des_ecb: " + Hex.encodeHexString(encryptedData));//字节数组(byte[])转为十六进制(Hex)字符串
return Hex.encodeHexString(encryptedData);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
// 解密
public static String Decrypt(String sSrc, String sKey) throws Exception {
byte[] key = sKey.getBytes();//秘钥必须是24位
byte[] plainText = Hex.decodeHex(sSrc.toCharArray());
SecretKey secretKey = new SecretKeySpec(key, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptPlainText = cipher.doFinal(plainText);
System.out.println("encrypt_3des_ecbjiemi: " + new String(decryptPlainText,"utf-8"));
return new String(decryptPlainText,"utf-8");//字节数组(byte[])转为十六进制(Hex)字符串
}
}
前端
var assert = require('assert');
var crypto = require('crypto');
//3DES加密
function Encrypt(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0)
var plaintext = param.plaintext
var alg = param.alg
var autoPad = param.autoPad
//encrypt
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad) //default true
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');
return ciph;
}
//3DES解密
function Decrypt(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0)
var plaintext = param.plaintext
var alg = param.alg
var autoPad = param.autoPad
//decrypt
var decipher = crypto.createDecipheriv(alg, key, iv);
decipher.setAutoPadding(autoPad)
var txt = decipher.update(plaintext, 'hex', 'utf8');
txt += decipher.final('utf8');
return txt;
}
版权声明:本文为weixin_41542329原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。