[笔记] javascript RSA 加密,解密,签名,验签
使用的库:
travist/jsencrypt: A Javascript library to perform OpenSSL RSA Encryption, Decryption, and Key Generation.
brix/crypto-js: JavaScript library of crypto standards.
测试地址:
Online RSA Key Generator
如果是在 HTML 中使用,引用的库:
// 具体地址,需要另行处理
<script src="./jsencrypt.min.js"></script>
<script src="./crypto-js.js"></script>
加密与解密
// Encrypt with the public key...
var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());
// Decrypt with the private key...
var decrypt = new JSEncrypt();
decrypt.setPrivateKey($('#privkey').val());
var uncrypted = decrypt.decrypt(encrypted);
签名与验签
这里的 hash 算法是 SHA256
// Sign with the private key...
var sign = new JSEncrypt();
sign.setPrivateKey($('#privkey').val());
var signature = sign.sign($('#input').val(), CryptoJS.SHA256, "sha256");
// Verify with the public key...
var verify = new JSEncrypt();
verify.setPublicKey($('#pubkey').val());
var verified = verify.verify($('#input').val(), signature, CryptoJS.SHA256);
END
作者:
J.晒太阳的猫
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。