Web前端之路Web前端之路让前端飞

jsrsa前端加签实践

2017-04-28  本文已影响260人  掌雄

对于前端JavaScript加签方法有很多种,本文为大家分享一下调用jsrsasign-latest-all-min.js库实现jsrsa加签,以及如何把该js库迁移到微信小程序上运行。

在线生成一套RSA的公钥和私钥

RSA公私钥在线生成地址:
http://www.bm8.com.cn/webtool/rsa/

我们把私钥拷贝出来:
<pre>
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC4kyLXI9LPCdbLaDw1Wk7IJBx4vqa+d11HRiUskmJQmZroMF/v
7nBrlssb/To91Uro9syKiwUTr3WhRlHkWNqHG+sxeI0WoTzC/lDYtSnfO13Jwc4K
6GcWqjvSj+hP2AGnMdHcOvdUbtll4BXdAzHviMzo0LOy5A1zalhpmLZfLQIDAQAB
AoGBAIiNossUX9R47QbT+Sdnxr1fqgjS1D45xTMD/GC7dC05V1fM4k16VIXkrCPq
9vnkIWW1oaImM/1aZGaKxe9wpUrnvXb4ciAP2ZKOI3C/S+NTWF+xnurmw+PtbNxa
4wX8FPUGmStKTzOZKMkzBpsGu9xWjPE+72FA7yn8haj0p3ipAkEA99V9jVOGM/8/
6/0djlmNMY2Rxeluu9WS/G/vPsh5R66BNsltyiF8aeqH26zLfoqbP+FY7k5MbeoC
qVuso9OUUwJBAL6oC+9Q9j5zs9aJrRe7J8r2m8NXongpVrrKlGe8b0MxALpn/2sW
lgz02k0a0gag/4/SdmzqY4N+i4usRoxnzn8CQGZybwMDut81rWPM7vHQHOiV/+NS
+n5U6/zD/J70WgYCodFW9LZwnzBdTanGRRxbCZAfhBaGcVuiN1Vw2u2h4ZcCQAb5
4yXoknoKhcQN2ZWKtZQJnf1x0XIQISpIi1GYZYHR4zLu5zul4eurcelsV88CSRec
HdUyZl3DXZvIu/QbQEUCQHnLFxd6WnLMXdAQhOixYTIXx3im0/15jCBd0zaoqHpL
RoB7z/Ask5sQJwXNalVag+GC7DPTbloXWzywrNI2DYA=
-----END RSA PRIVATE KEY-----
</pre>

在用到RSA加签的页面引入jsrsasign-latest-all-min.js库文件

<pre>
<script type="text/javascript" src="jsrsasign-latest-all-min.js"></script>
</pre>

调用加签方法

KEYUTIL.getKey可以接受PKCS#8的私钥格式

<pre>
var signData = 'my sign data';
var privateKey = '-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQC4kyLXI9LPCdbLaDw1Wk7IJBx4vqa+d11HRiUskmJQmZroMF/v7nBrlssb/To91Uro9syKiwUTr3WhRlHkWNqHG+sxeI0WoTzC/lDYtSnfO13Jwc4K6GcWqjvSj+hP2AGnMdHcOvdUbtll4BXdAzHviMzo0LOy5A1zalhpmLZfLQIDAQABAoGBAIiNossUX9R47QbT+Sdnxr1fqgjS1D45xTMD/GC7dC05V1fM4k16VIXkrCPq9vnkIWW1oaImM/1aZGaKxe9wpUrnvXb4ciAP2ZKOI3C/S+NTWF+xnurmw+PtbNxa4wX8FPUGmStKTzOZKMkzBpsGu9xWjPE+72FA7yn8haj0p3ipAkEA99V9jVOGM/8/6/0djlmNMY2Rxeluu9WS/G/vPsh5R66BNsltyiF8aeqH26zLfoqbP+FY7k5MbeoCqVuso9OUUwJBAL6oC+9Q9j5zs9aJrRe7J8r2m8NXongpVrrKlGe8b0MxALpn/2sWlgz02k0a0gag/4/SdmzqY4N+i4usRoxnzn8CQGZybwMDut81rWPM7vHQHOiV/+NS +n5U6/zD/J70WgYCodFW9LZwnzBdTanGRRxbCZAfhBaGcVuiN1Vw2u2h4ZcCQAb54yXoknoKhcQN2ZWKtZQJnf1x0XIQISpIi1GYZYHR4zLu5zul4eurcelsV88CSRecHdUyZl3DXZvIu/QbQEUCQHnLFxd6WnLMXdAQhOixYTIXx3im0/15jCBd0zaoqHpLRoB7z/Ask5sQJwXNalVag+GC7DPTbloXWzywrNI2DYA=-----END RSA PRIVATE KEY-----';
function doSign() {
var rsa = new RSAKey(); // 新建RSA对象
rsa = KEYUTIL.getKey(privateKey); // 设置私钥
var hashAlg = 'sha1'; // 设置sha1
var hSig = rsa.signString(signData, hashAlg); // 加签
hSig = hex2b64(hSig); // hex 转 b64
return hSig;
}
</pre>

jsrsasign-latest-all-min.js库迁移到微信小程序上运行

jsrsasign-latest-all-min.js直接在微信小程序上运行,会报window、navigator的错误,我们只要把库文件中对应的浏览器内置对象逐一替换掉就可以了。

替换后的库文件:
https://github.com/zhangxiongwu/testjsRsaSign/blob/master/jsrsasign-latest-all(can%20run%20in%20wchat%20smallapp).js

例子完整代码:
https://github.com/zhangxiongwu/testjsRsaSign

参考资料
jsrsasign官方地址:
https://kjur.github.io/jsrsasign/
github地址:
https://github.com/kjur/jsrsasign

您的意见是我改善的东西,欢迎评论提建议,如果对您有帮助,请点个赞,谢谢~~
菲麦前端专题,汇聚前端好文,邀您关注!

上一篇下一篇

猜你喜欢

热点阅读