sm2前端加密
function sm2Encrypt(data, publickey, cipherMode) {
cipherMode = cipherMode == 0 ? cipherMode : 1;
// msg = SM2.utf8tob64(msg);
var msgData = CryptoJS.enc.Utf8.parse(data);
// 有的js不会注释下面装换过程,我尝试下了下,不注释掉后端解码会出问题
// msgData = CryptoJS.enc.Base64.stringify(msgData);
// //在转utf-8
// msgData = CryptoJS.enc.Utf8.parse(msgData);
var pubkeyHex = publickey;
if (pubkeyHex.length > 64 * 2) {
pubkeyHex = pubkeyHex.substr(pubkeyHex.length - 64 * 2);
}
var xHex = pubkeyHex.substr(0, 64);
var yHex = pubkeyHex.substr(64);
var cipher = new SM2Cipher(cipherMode);
var userKey = cipher.CreatePoint(xHex, yHex);
msgData = cipher.GetWords(msgData.toString());
var encryptData = cipher.Encrypt(userKey, msgData);
return '04' + encryptData;
}
// html调用
function encryption(){
const msg="test";
// 公钥,由后端生成
const pubkey="XXXX"
const cipherMode = 0; // 1 - C1C3C2,0 - C1C2C3,默认为1
const encryptData = sm2Encrypt(msg, pubkey,cipherMode);
console.log("encryptData" ,encryptData)
}
SM2,、SM3,、SM4前端js加密,后端解密以及SM2,、SM3,、SM4 js下载https://download.csdn.net/download/weixin_44037153/20097454