nodeJS rsasha加密
/** * Created by Administrator on 2017/4/19. */ var crypto = require('crypto'); //签名 function signer(algorithm, key, data) { key = get_key(key, 1); var sign = crypto.createSign(algorithm); sign.update(data); sig = sign.sign(key, 'base64'); return sig; } //验证签名 function verify(algorithm, pubkey, sig, data) { pubkey = get_key(pubkey, 0); var verify = crypto.createVerify(algorithm); verify.update(new Buffer(data, 'utf-8')); return verify.verify(pubkey, sig, 'base64'); } /** *获取PEM格式的秘钥(公钥,私钥) *key:待编码的key *keyType: 0 公钥 1 私钥 */ function get_key(key,keyType) { key = insert_str(key, '\n', 64); switch (keyType) { case 0: key = '-----BEGIN PUBLIC KEY-----\n' + key + '-----END PUBLIC KEY-----'; break; case 1: key = '-----BEGIN PRIVATE KEY-----\n' + key + '-----END PRIVATE KEY-----'; break; } return key; } /** * 在指定位置插入字符串 * @待插入字符串 str * @插入字符串 insert_str * @位置 sn * @returns {string} */ function insert_str(str, insert_str, sn) { var newstr = ""; for (var i = 0; i < str.length; i += sn) { var tmp = str.substring(i, i + sn); newstr += tmp + insert_str; } return newstr; } /** * RSA-SHA1验证签名 * @数据 {string} data * @公钥 {string} pubkey * @签名 {string} sig */ exports.rsasha1verify = function(data,pubkey,sig){ var algorithm = 'RSA-SHA1'; return verify(algorithm,pubkey,sig,data); } /** * RSA-SHA1签名 * @加密私钥 {string} key * @数据 {string} data */ exports.rsasha1sign = function (key,data) { var algorithm = 'RSA-SHA1'; return signer(algorithm, key, data); } /** * RSA-SHA256签名 * @加密私钥 {string} key * @数据 {string} data */ exports.rsasha256sign = function (key ,data) { var algorithm = 'RSA-SHA256'; return signer(algorithm, key, data); } /** * RSA-SHA256验证签名 * @数据 {string} data * @公钥 {string} pubkey * @签名 {string} sig */ exports.rsasha256verify = function (data, pubkey, sig) { var algorithm = 'RSA-SHA256'; return verify(algorithm, pubkey, sig, data); }
个人用 备份