我想在客户端加密文件并将其发送到服务器端,然后 解密
但是,当我使用内置crypto的节点js时,却出现了错误
client.js
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
const encInput = fs.createReadStream("abc.txt");
const encOutput = fs.createWriteStream("abc.txt.enc");
encInput.pipe(cipher).pipe(encOutput).on('close', function() {
// DATA SENT TO SERVER SIDE
//USING PIPELINE TO SEND DATA TO SERVER
});
这部分做得很好,它在客户端创建了一个加密文件并将其发送到服务器端
Server.js
//receive Data
//AFTER RECEIVING FILE ON this side I run decrypt script
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
const decInput = fs.createReadStream("abc.txt.enc");
const decOutput = fs.createWriteStream("abc.txt");
decInput.pipe(decipher).pipe(decOutput);
这会导致错误
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipher._flush (internal/crypto/cipher.js:141:28)
at Decipher.prefinish (_stream_transform.js:141:10)
at Decipher.emit (events.js:182:13)
at prefinish (_stream_writable.js:630:14)
at finishMaybe (_stream_writable.js:638:5)
at afterWrite (_stream_writable.js:481:3)
at onwrite (_stream_writable.js:471:7)
at Decipher.afterTransform (_stream_transform.js:94:3)
at Decipher._transform (internal/crypto/cipher.js:136:3)
at Decipher.Transform._read (_stream_transform.js:190:10)
Emitted 'error' event at:
at Decipher.onerror (_stream_readable.js:687:12)
at Decipher.emit (events.js:182:13)
at done (_stream_transform.js:208:19)
at _flush (_stream_transform.js:142:7)
at Decipher._flush (internal/crypto/cipher.js:143:5)
at Decipher.prefinish (_stream_transform.js:141:10)
[... lines matching original stack trace ...]
at afterWrite (_stream_writable.js:481:3)
我知道客户端没有问题,它可以很好地使用管道套接字发送数据
**在服务器端接收数据也没有问题,只是解密造成了问题,idk为什么会这样**
您想了解我的代码的其他信息,请告诉我们
使用Node v10.6.0
答案 0 :(得分:0)
尝试使用初始化向量和base64
文件存储格式:
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const base64 = require('base64-stream');
const iv = new Buffer('1065faf25ac8560968c58ce6dc0ae36f', 'hex'); // 16 byte iv
const kk = new Buffer('84521db468d282c4ce21cdde65e508ce3d1924d1be5c4754', 'hex'); // 24 byte key (192 bits)
const cipher = crypto.createCipheriv('aes192', kk, iv, { encoding: 'base64' });
const encInput = fs.createReadStream(path.join(__dirname, "abc.txt"));
const encOutput = fs.createWriteStream(path.join(__dirname, "abc.txt.enc"));
encInput.pipe(cipher).pipe(encOutput).on('close', function () {
const decipher = crypto.createDecipheriv('aes192', kk, iv);
const decInput = fs.createReadStream(path.join(__dirname, "abc.txt.enc"));
const decOutput = fs.createWriteStream(path.join(__dirname, "abc.txt.dec"));
decInput.pipe(base64.decode()).pipe(decipher).pipe(decOutput);
});