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

89 lines
2.5 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
*/
4 years ago
module.exports = {
4 years ago
/**
* 创建签名
* @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 = [];
4 years ago
for (const key in params) {
paramNames.push(key);
}
4 years ago
paramNames.sort();
4 years ago
4 years ago
const paramNameValue = [];
4 years ago
for (let i = 0, len = paramNames.length; i < len; i++) {
const paramName = paramNames[i];
const val = params[paramName];
if (paramName && val) {
paramNameValue.push(`${paramName}=${val}`);
}
}
return paramNameValue.join('&');
4 years ago
}
};