如何使用带有公共和私有密钥的node-rsa解密文件?

时间:2019-05-09 05:28:46

标签: javascript node.js file encryption

我正在关注medium上的本教程。但是,本教程没有说明如何解密加密文件。也没有解释如何使用公钥/私钥。

仅运行解密不适用于以下错误。

enter image description here

相关文档似乎在npmjs.com上。

实际代码

// node modules
const fs = require('fs');

// npm modules
const parseArgs = require('minimist');
const NodeRSA = require('node-rsa');

// get command line arguments
const argv = parseArgs(process.argv.slice(2));
// console.dir(argv);

// read a file
const file = fs.readFileSync('' + argv.file, 'utf8');

// generate keys
const key = new NodeRSA().generateKeyPair();
const publicKey = key.exportKey('pkcs8-public-pem');
const privateKey = key.exportKey('pkcs1-pem');

// write public key
fs.openSync('keys/public.pem', 'w');
fs.writeFileSync('keys/public.pem', publicKey, 'utf8');

// write private key
fs.openSync('keys/private.pem', 'w');
fs.writeFileSync('keys/private.pem', privateKey, 'utf8');

// write encrypted file
const encrypted = key.encrypt(file, 'base64');
fs.openSync('encrypted.txt', 'w');
fs.writeFileSync('encrypted.txt', encrypted, 'utf8');

// read encrypted file
const fileEncrypted = fs.readFileSync('encrypted.txt', 'utf8');
const decrypted = key.decrypt(fileEncrypted, 'base64'); // error here
// has to do with key generation?

default.txt

测试

encrypted.txt

  

qLs0dUez + LzhlNBGnvEzLRdYF0HUHoRignMxT2MZO7Qs8tMvkmWbiA1oxJbT7ZC5bPS + dHvFgbiWbdje / 3 / Y17JT8JxflryJU6394UPfsTDLmtZZroemTtTzJxVnGZlw0IyQtfn79eysQaEoKMQ9hKjDySxO1gLwJJZ1DoxW7CNu0BqfcGUMcREQ + ozrhKpMRK0piWUWqHYwX0EIxQT8 / rh5ER + tCdh4lR7N5 + FPA4VOde3z / 36DvQ9KOMChS7m91aH0QXUqhMaHtjslvcoj4i1Rwzd0qn1imHPc8LncZz6hv2deRqU65rS + M6UeC9LWJjblVf2er25x8B1yszaV + A ==

3 个答案:

答案 0 :(得分:2)

只需将您的解密更改为使用utf8

const decrypted = key.decrypt(fileEncrypted, 'utf8');

答案 1 :(得分:0)

您正在尝试解密明文文件。 尝试解密加密的文件。

答案 2 :(得分:0)

您没有正确解密数据,encoding的{​​{1}}参数是所需的结果编码,而不是输入编码。

尽管据说delete方法通过JSDoc占用一个缓冲区:

NodeRSA.prototype.decrypt(buffer, encoding)

您可以跟踪代码以查看如果/** * Decrypting data method with private key * * @param buffer {Buffer} - buffer for decrypting * @param encoding - encoding for result string, can also take 'json' or 'buffer' for the automatic conversion of this type * @returns {Buffer|object|string} */ 是字符串,则假定它采用buffer编码:

base64

我们可以通过忽略文件系统的交互来了解往返的工作方式,从而简化您的问题:

buffer = _.isString(buffer) ? Buffer.from(buffer, 'base64') : buffer;

或者,您可以分别将输入和输出分别显式地转换为缓冲区和从缓冲区显式转换,这可以帮助您了解实际情况:

const key = new NodeRSA().generateKeyPair();

// Encrypt the utf8 encoded input string and output a base64 encoded string
const encrypted = key.encrypt('test', 'base64');
console.log(encrypted);

// Decrypt the base64 encoded input string and output a utf8 encoded string
const decrypted = key.decrypt(encrypted, 'utf8');
console.log(decrypted);