故事背景
还是传说中的PUK项目,不仅有一个独特的加密数据方法DESede/CBC/PKCS5Padding
,还加了一层RSA签名
(非对称加密),双重加密保障,安全系数5颗星!
普及一下非对称加密校验原理,简单说就是
甲方用自己的【私钥】对机密信息进行加密后发送给乙方,乙方再用甲方的【公钥】对甲方发送的数据进行验签。
Talk is cheap,show you the code !
核心代码
const crypto = require("crypto");
/**
* 创建签名(使用私钥和数据)
*
* @param data
* @param privateKey
* @returns {string}
*/
function createSign(data, privateKey) {
const sign = crypto.createSign('RSA-SHA1');
sign.update(data);
sign.end();
return sign.sign(privateKey).toString('base64')
}
/**
* 签名验证(使用公钥、数据、签名)
*
* @param data
* @param sign
* @param publicKey
* @returns {boolean}
*/
function verifySign(data, sign, publicKey) {
const verify = crypto.createVerify('RSA-SHA1');
verify.update(data);
verify.end();
return verify.verify(publicKey, Buffer.from(sign, 'base64'));
}
运行结果
注意,需要生成对应的公钥和私钥,可以使用openssl,也可以使用支付宝的开放工具
//使用公钥加密数据
const privateKey = `-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIzOypoBDOR0dLfR8gEdcHMuX97+Qms/KQ7tbsKzC/rbvJ0p3r9Dy5hTzSBR+BpFYDMJD9nnbDFZF7vg5hletPJoD7rN52DqBL3oMPLYN3u2qVRFIMnk0Oy2lBgAZ52VRcZNu5oYQlCvD+vztf7UCpcL2gP6A9zts4bj553N4gUVAgMBAAECgYAgvuKdCAuAgZi3OwrluXvyPWGsUUMO/+RDhXIRs2Pg1gM6JYeYwWJyrWJx1r41Fdc2ZzAZg9lEbKy5U6cPVVgNAwE8m4AHVNVlZJVvx0lGnvnh3XFlCrlKv/FseDQhi52vysVjIy1BDDWEUSnMcjfkwncjEBdzTLFqjbLiLinNwQJBAM9oTJM8j1K0N2qQfRsyRhUxJI+C4MDntK8CGqx0Qvf90dgXNM8FEVxsjDdN/nIMNeRYgXhrBSe+qlequSHtNeUCQQCtzAmNt3yANOymMaU19NWMf6WVeu5/GGBWgyarzffv/A9k16TrcHlMLcEC97ixmtNEB1ItkiJmJv7tzZmFpJ9xAkEAkwPFM6B7nw3rMfgVFc/+6UqaNbd5hIM5CcweCBuo1Ivv0JIydoOLGM5AXXtFXqXVFXS+4RJK5y85I0b6T1gLGQJARla51x1XyhuhW3HkR34bn41Z2rGyLMYU126lDAuEOSBuqoWMPa17qhUqdKUFnvvmXTYJUGBAg89shZocdDY4QQJBAME5svM/2FIuNDU2uqf4/yv32PHH11F9zez16nJFleagTYU6Lt1Hwcw39JyyxHUqOyKdXr/EncGv6zJgldPULbM=
-----END PRIVATE KEY-----`;
let json = `{"name":"chenqionghe","cn":"雪山飞猪","content":"no pain no gain, light weight baby"}`;
let sign = createSign(json, privateKey);
console.log(sign);
//使用公钥验证签名
const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMzsqaAQzkdHS30fIBHXBzLl/e/kJrPykO7W7Cswv627ydKd6/Q8uYU80gUfgaRWAzCQ/Z52wxWRe74OYZXrTyaA+6zedg6gS96DDy2Dd7tqlURSDJ5NDstpQYAGedlUXGTbuaGEJQrw/r87X+1AqXC9oD+gPc7bOG4+edzeIFFQIDAQAB
-----END PUBLIC KEY-----`;
console.log(verifySign(json, sign, publicKey));
运行输出
QPLXzRwQ8OFUn0S4c3+WaKO64uK6boQRTH1EAYS00Rh9br3so+ucX2KaIa3F0QZ5REkH96dEbCMWi/s0xAncCrnxKHjm43r2uybWE8qgBr8zVKOPTqwdIAEjIjPwSe8cRb4IAXJkPv6u7x+Qbw+tYrm0L3zvgitKeCl5PNdcEdo=
true
结果为true,验证通过