我遇到了RSA解密问题。
首先,我在openssl(OS X 10.14中为LibreSSL 2.6.4)中创建了一对公钥和私钥:
genrsa -out rsa_private_key.pem 1024
rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
然后,我编写了用于加密和解密的函数。代码如下:
//rsa.js
const crypto = require('crypto');
exports.encrypt = (data, key) => {
try {
let enc = crypto.publicEncrypt(key, Buffer.from(data));
return enc;
} catch (error) {
console.log('encrypt error:', error);
return null;
}
};
exports.decrypt = (encrypted, key) => {
try {
let dec = crypto.privateDecrypt({'key':key, 'padding': crypto.constants.RSA_PKCS1_OAEP_PADDING }, encrypted);
return dec;
} catch (error) {
console.log('decrypt error:', error);
return null;
}
};
然后我运行一个nodejs应用,该应用使用公共密钥加密字符串,然后使用 私钥:
//test.js
const rsa = require('./rsa');
const rsaKeys = require('./rsaKeys');
const plainText = '111111';
const crypted = rsa.encrypt(plainText, rsaKeys.pubKey);
const decrypted = rsa.decrypt(crypted, rsaKeys.privKey);
console.log('crypted:', crypted.toString('base64'));
console.log('decrypted:',decrypted.toString());
它运行得很好,因为解密的正是纯文本“ 111111”。然后我错误地更改了私钥的最后3位,例如:
exports.privKey = `-----BEGIN RSA PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxccc
-----END RSA PRIVATE KEY-----
`;
我继续运行test.js
,让我惊讶的是它显示了decrypted: 111111
。
后来我多次更改了最后3位,所有这些都能正确显示解密。当我更改私钥的前3位时,解密会在例外情况下运行。
我不明白为什么会出现我对cypher不太了解的结果广告。
请指出有关如何理解它的指南。
更新:添加密钥对。
exports.privKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCWVJtkMDXP1cM6wgOW4aMlHpCg+z0o+mSUTOQwCHJ4Em0x76jm
HsNcFV9svl2KsVZmAvb3CWkNGy/+ST4cKHALMRNZ5hKNcemRH7BSHgBPTNY896Zs
0FIHClsi9J0sWC5dNdVQ02JmU2WPz9XPlVhzaELml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