我想加密输入流并通过 TCP 将其发送到另一台服务器。到目前为止,一切都很好。一切顺利,直到连接关闭。几乎在任何情况下都没有满足所需的 192 位 block 大小,并且脚本因 wrong final block length
而崩溃,尽管我打开了自动填充。
似乎自动填充仅在使用旧版界面时才有效。我在这里做错了吗?
var net = require("net")
, crypto = require("crypto");
var credentials = { algorithm: "aes192", password: "password" }
, decipher = crypto.createDecipher(credentials.algorithm, credentials.password)
, cipher = crypto.createCipher(credentials.algorithm, credentials.password);
decipher.setAutoPadding(true);
cipher.setAutoPadding(true);
net.createServer(function(socket) {
socket.pipe(socket);
}).listen(2000);
var socket = net.connect(2000);
socket.pipe(decipher).pipe(process.stdout);
process.stdin.pipe(cipher).pipe(socket);
socket.write("Too short.");
socket.end();
在我理想的 Node.js 世界中,(De-)Cipher Stream 会在源流关闭时自动填充最后一个 block 。我认为这是一个设计缺陷。
除了opening an issue ,我该如何规避这种行为?我必须在 Socket 和 (De-)Cipher Streams 之间放置一个字节计数器吗?
最佳答案
你已经这样设置你的管道了:
stdin | cipher | socket (loopback) | decipher | stdout
但是你通过直接写入套接字来绕过加密,像这样使用它们:
socket (loopback) | decipher | stdout
试试这个代码:
var net = require("net")
, crypto = require("crypto");
var credentials = { algorithm: "aes192", password: "password" }
, decipher = crypto.createDecipher(credentials.algorithm, credentials.password)
, cipher = crypto.createCipher(credentials.algorithm, credentials.password);
decipher.setAutoPadding(false); //set to false to keep the padding
cipher.setAutoPadding(true);
//Loopback
server = net.createServer(function(socket) {
socket.pipe(socket);
})
server.listen(2000);
var socket = net.connect(2000);
//cipher to the loopback socket, to decipher and stdout
cipher.pipe(socket).pipe(decipher).pipe(process.stdout);
//write some data
cipher.write("Too short.");
//Clean exit
cipher.end();
server.unref();
出于演示的目的,我从 Decryptor
对象中删除了自动填充,以便您可以看到剩余的填充。在 xxd 中管道程序(在命令行,而不是在 Node 中)给了我这个输出:
$ nodejs so.js | xxd
0000000: 546f 6f20 7368 6f72 742e 0606 0606 0606 Too short.......
0x06
重复 6 次。
关于javascript - 如何处理 Node.js 加密流中的 block 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16775219/