node加密rsa公钥和python解密私钥的问题

node和python默认的rsa加密方式是不一样,要调整一下。

node代码:


const fs = require('fs');
const NodeRSA = require('node-rsa');
const path = require('path').resolve();
 
const publicKey = fs.readFileSync(`${path}\\rsa_public_key.pem`, 'utf-8')
const privateKey = fs.readFileSync(`${path}\\rsa_private_key.pem`, 'utf-8')

const text = 'Hello RSA!';
 
// 公钥加密
const _publicKey = new NodeRSA();
_publicKey.setOptions({ encryptionScheme: 'pkcs1' }); // 务必要加这行代码
_publicKey.importKey(publicKey, "pkcs1-public");
const public_encrypted = _publicKey.encrypt(text);
console.log('public_encrypted: ', public_encrypted.toString('base64'));
 
//附赠私钥解密代码
const _privatKey = new NodeRSA(privateKey);
_privatKey.setOptions({ encryptionScheme: 'pkcs1' });
const private_decrypted = _privatKey.decrypt(public_encrypted);
console.log('private_decrypted: ', private_decrypted.toString('utf-8'));

python方面私钥解密代码代码:


from Crypto.Cipher import PKCS1_v1_5
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
import base64
 
ciphertext ='' // 这里把之前加密出来的base64字符串放这里
 
key = RSA.importKey(open('rsa_private_key.pem').read())
cipher = PKCS1_v1_5.new(key)
 
message = cipher.decrypt(base64.b64decode(ciphertext), None)
print(message) // 输出,完事
posted @ 2021-03-26 16:16  fengyujia  阅读(474)  评论(0编辑  收藏  举报