You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
SOP/sop-sdk/sdk-nodejs/common/SignUtil.js

90 lines
2.7 KiB

const {KJUR, hextob64} = require('jsrsasign');
4 years ago
const HashMap = {
SHA256withRSA: 'SHA256withRSA',
SHA1withRSA: 'SHA1withRSA'
};
4 years ago
const PEM_BEGIN = '-----BEGIN PRIVATE KEY-----\n';
const PEM_END = '\n-----END PRIVATE KEY-----';
4 years ago
/**
* rsa签名参考https://www.jianshu.com/p/145eab95322c
*/
exports.SignUtil = {
/**
* 创建签名
* @param params 请求参数
* @param privateKey 私钥PKCS8
* @param signType 签名类型RSA,RSA2
* @returns 返回签名内容
*/
createSign(params, privateKey, signType) {
const content = this.getSignContent(params);
return this.sign(content, privateKey, signType);
4 years ago
},
sign: function (content, privateKey, signType) {
if (signType.toUpperCase() === 'RSA') {
return this.rsaSign(content, privateKey, HashMap.SHA1withRSA);
4 years ago
} else if (signType.toUpperCase() === 'RSA2') {
return this.rsaSign(content, privateKey, HashMap.SHA256withRSA);
4 years ago
} else {
throw 'signType错误';
4 years ago
}
},
/**
* rsa签名
* @param content 签名内容
* @param privateKey 私钥
* @param hash hash算法SHA256withRSASHA1withRSA
* @returns 返回签名字符串base64
*/
rsaSign: function (content, privateKey, hash) {
privateKey = this._formatKey(privateKey);
4 years ago
// 创建 Signature 对象
const signature = new KJUR.crypto.Signature({
alg: hash,
//!这里指定 私钥 pem!
prvkeypem: privateKey
});
signature.updateString(content);
const signData = signature.sign();
4 years ago
// 将内容转成base64
return hextob64(signData);
4 years ago
},
_formatKey: function (key) {
if (!key.startsWith(PEM_BEGIN)) {
key = PEM_BEGIN + key;
4 years ago
}
if (!key.endsWith(PEM_END)) {
key = key + PEM_END;
4 years ago
}
return key;
4 years ago
},
/**
* 获取签名内容
* @param params 请求参数
* @returns {string}
*/
getSignContent: function (params) {
const paramNames = [];
// 获取对象中的Key
paramNames.push(...Object.keys(params || {})
// 过滤无效的KeyValue
.filter(paramName => {
// 参数名不为undefined且参数值不为undefined
return !(typeof paramName === undefined || typeof params[paramName] === undefined);
}));
4 years ago
paramNames.sort();
4 years ago
// 合成签名字符串
const paramNameValue = paramNames.map(paramName => {
4 years ago
const val = params[paramName];
return `${paramName}=${val}`;
});
return paramNameValue.join('&');
4 years ago
}
};