直接上前端代码
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 test(){
const msg="hello acheng";
// 公钥,由后端生成
const pubkeyHex="XXXX"
const encryptData = sm2Encrypt(msg, pubkeyHex);
console.log("encryptData " ,encryptData)
}
前端参考地址:https://github.com/lifesreason/SM2
后端参考地址:https://github.com/hwyqb/SM2_SM3_SM4Encrypt
整合了下 SM2, SM3, SM4,前端js加密,后端解密,均已自测通过
下载地址https://download.csdn.net/download/HBliucheng/13195667