使用Node.js加密流加密和解密文件

时间:2018-04-13 04:34:47

标签: node.js encryption electron filestream

我正在使用Electron和react.js创建一个桌面应用程序,我必须使用Crypto库加密和解密文件(.txt,.pdf,.jpg,.png)。 我正在使用流来做到这一点。 所以我只是从FileAPI获取文件并传递文件路径以创建readStream。

export function encrypt (passphrase) {
 const crypto = require('crypto');
 const fs = require('fs');
 const cipher = crypto.createCipher('aes192', passphrase);
 const input = fs.createReadStream(file_path);
 const output = fs.createWriteStream('test.enc');
 input.pipe(cipher).pipe(output);}

export function decrypt (passphrase) {
 const crypto = require('crypto');
 const fs = require('fs');
 const cipher = crypto.createDecipher('aes192', passphrase);
 const input = fs.createReadStream(file_path);
 const output = fs.createWriteStream('test.pdf');}
 input.pipe(cipher).pipe(output);  

此代码仅适用于.txt文件。

是否有任何帮助使其适用于其他文件格式?

1 个答案:

答案 0 :(得分:0)

所以这是一个起作用的函数..只需使用“数据”以您需要的任何格式调用该函数..似乎最好使用字符串或缓冲区。

function Encrypt_AES(data, pubkey) {

const algorithm = 'aes-192-cbc';
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(pubkey, 'salt', 24);
// Use `crypto.randomBytes` to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const cipher = crypto.createCipheriv(algorithm, key, iv);

let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');

return encrypted;

}

function Decrypt_AES(data, pubkey) {
const algorithm = 'aes-192-cbc';
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(pubkey, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Encrypted using same algorithm, key and iv.

let decrypted = decipher.update(data, 'hex', 'utf8');
decrypted += decipher.final('utf8');


return decrypted;
}