SM2是非对称加密算法,网上很难找到正常使用的前后端对应版本,这里为了方便大家不用C币去下载,我这里就直接贴出来需要的代码和工具类了哈
js端
前端的加密会默认把加密内容转base64,所以Java后端解密的时候不转码就会无法还原,sm2Decrypt1()是前端解密的和sm2Encrypt可以配套使用,
function sm2Encrypt(data, publickey, cipherMode) {
cipherMode = cipherMode == 0 ? cipherMode : 1;
// msg = SM2.utf8tob64(msg);
var msgData = CryptoJS.enc.Utf8.parse(data);
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;
}
function sm2Decrypt1(data, privatekey, cipherMode) {
cipherMode = cipherMode == 0 ? cipherMode : 1;
// msg = SM2.utf8tob64(msg);
data = data.substr(2);
var pk = SM2.tool(privatekey)
var cipher = new SM2Cipher(cipherMode);
var decryptData = cipher.Decrypt(pk,data);
decryptData = CryptoJS.enc.Base64.parse(decryptData)
decryptData = CryptoJS.enc.Utf8.stringify(decryptData);
return decryptData;
}
function sm2Decrypt(data, privatekey, cipherMode) {
cipherMode = cipherMode == 0 ? cipherMode : 1;
// msg = SM2.utf8tob64(msg);
data = data.substr(2);
var pk = SM2.tool(privatekey)
var cipher = new SM2