题目是私钥加密,为啥要写,就是因为目前网络能搜到的库,都没有这个算法。不管是jsencrypt.js,还是js-rsa-security.js,还是kjur-jsrsasign-d282c71,加密算法其实都一样的函数,不知道为啥取了不同的名字。
代码是直接在kjur-jsrsasign-d282c71库里面的jsrsasign-all-min.js添加的。所以要了解具体情况需要先下载该库。
RSAKey.prototype.privEncrypt = function(d) {
var a = pkcs1pad1(d, (this.n.bitLength() + 7) >> 3);
if (a == null) {
return null
var e = this.doPrivate(a);
if (e == null) {
return null
var b = e.toString(16);
if ((b.length & 1) == 0) {
return b
} else {
return "0" + b
RSA加密参照网页链接:
RSA公钥私钥加密
PKCS1Padding分析
去PKCS1Padding分析页面,看看具体原理
function pkcs1pad1(e, h) {
if (h < e.length + 11) {
throw "Message too long for RSA";
return null
var g = new Array();
var d = e.length - 1;
while (d >= 0 && h > 0) {
var f = e.charCodeAt(d--);
g[--h] = f;
g[--h] = 0;
while (h > 2) {
g[--h] = 255;
g[--h] = 1;
g[--h] = 0;
return new BigInteger(g)
let priHex = "";
let rsa = new RSAKey();
rsa.readPKCS8PrvKeyHex(priHex);
let hSig = rsa.privEncrypt(content);
let hipherText = hex2b64(hSig);
如果是PKCS#1的pem格式的Base64私钥可以用下面的接口读入
let prvKey = "";
let rsa = new RSAKey();
rsa.readPrivateKeyFromPEMString(prvKey);
let hSig = rsa.privEncrypt(content);
let hipherText = hex2b64(hSig);
//公钥(注意包括头(-----BEGIN PUBLIC KEY-----)尾(-----END PUBLIC KEY-----)标志)
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbdq5NjtUEkAQ6wucPuhC0aRvSMsaX3GrhkwsLLdWZnVNVpkJRw
yPFq9HJNuntRw7P9Sb3Tk.
$privateKeyFilePath = '-----BEGIN RSA PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJDArkki2k3+xhze
v5emztqFtUhOzVlSveQ5dOLC4nNlLg8r81I9xBaXB7m4rb6lVjLgUuAXKUJ8y7yH
eE02s695cR/ZD0fierrMKMkmTFZIqOVYchn15N8E
var encrypt = new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
var encrypted = encrypt.encryptLong("results");
console.log('加密后数据:%o', encrypted);
var decrypt = new JSEncrypt();
decrypt.setPrivateKey(PRIVATE_KEY);
let un = decrypt.decryptLong(encrypted);
console.log('解密后数据:%o', un);