由于工作需要,需要使用RSA算法对数据进行签名
1、使用支付宝的RSA工具,快速生成RSA私钥公钥,同时用于校验结果
2、选择密钥格式以及密钥长度
这里我们选择以密钥格式PKCS8(JAVA使用),密钥长度1024为例
3、使用node-rsa实现签名
npm install node-rsa
4、实现签名以及校验签名
-
生成密钥,使用RAS工具生成密钥
-
导入私钥,私钥来源于上图中“商户应用私钥”
const NodeRSA = require('node-rsa');
let userPrivateKey = `-----BEGIN PRIVATE KEY-----[你的私钥]-----END PRIVATE KEY-----`;
const key = new NodeRSA();
key.setOptions({b: 1024, signingScheme: "sha1"});//配置密钥长度,并设置签名方法
key.importKey(userPrivateKey, 'pkcs8-private');//导入密钥并设定格式
- 代码生成公钥
const publicDer = key.exportKey('pkcs8-public');
console.log(publicDer);
输出结果与RSA公钥结果对比
结果一致
- 使用RSA工具签名
请求示例参数
a=123&charset=UTF-8&method=alipay.mobile.public.menu.add&sign_type=RSA×tamp=2014-07-24 03:07:50&version=1.0
注意:参数中charset和sign_type对应工具中的字符集和签名方式
- 代码实现签名
let text = '[签名字符串]';
let buffer = Buffer.from(text);
let signature = key.sign(buffer).toString('base64');
console.log(signature);
- 签名结果对比
结果一致
完整代码
const NodeRSA = require('node-rsa');
let userPrivateKey = `-----BEGIN PRIVATE KEY-----MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKM4jTMTftwr3Vtk1LxCY8Nqlmk3WQa7FecvizcMIxgGjg2pQg4ZFOahKxv4VgrjUtgctgIsVebVDcCBxkyPEKYYjFyT20Ez6wcuYsI30lJCJOK7iTw/8QtvkJBrRZhVEYkiSSb9EBG+xuHA3H0nRn/XxRhZTMdNozki1nXNNl2pAgMBAAECgYAuCOEqKrF4/5YrFME7Z64ji4honIerclC3J52oJPAw8ohWKgrLVx+h/IrgFKaP45WWBmL/Men4dNawGOoI5cDX4zf+H7cOFAIVg+0SEqODAiHHYj6aQ+P6qTPJEshmA6DNcjpliuvEACFcg+m4w2NjRN3jeNTBAnhg11WbxKIUQQJBAO0jyJ0FUr7TONXVtjFZC3tSsjv8r3BUjfcuY1tOfusWQQpLMtENOeaY4mjoVkGynDHc/ZiZd8zHsQjB9P238BUCQQCwM8OOZEhiJOog5PAbq3IFTO7nuj9UCjNik+SetXCq3tjPXaGqBrxsWpW8I9diKyXYv0VC/xI+FQut2fVlGghFAkAbjs0BclzrUCCKuQszMOXkrveHgRXiN/FHiFyDf9u/9hYY3CRLpv3TjnDBQD7F47vDD6to0Gzbn1kza1bNJVMBAkEAoRxzrvsbBEJkofczZNl6xEX4HII77Yf2PCimXkfg4RwqelFOxLysBRc+2mybP/PcAzfBCOVZtNJhf3FP5EXNUQJBAMiXPbZ30X/EdAkIGk+cLjzlf2QiOTsKMNY46mzRZV93TziIK3yjtxQozSoZxu4+qKqDKtgpRqw/wCvhTYBBJx0=-----END PRIVATE KEY-----`;
const key = new NodeRSA();
key.setOptions({b: 1024, signingScheme: "sha1"});
key.importKey(userPrivateKey, 'pkcs8-private');//导入密钥并设定格式
const publicDer = key.exportKey('pkcs8-public');
console.log(publicDer);
let text = 'a=123&charset=UTF-8&method=alipay.mobile.public.menu.add&sign_type=RSA×tamp=2014-07-24 03:07:50&version=1.0';
let buffer = Buffer.from(text);
let signature = key.sign(buffer).toString('base64');
console.log(signature);