【问题标题】:NodeJS, after sending the buffer through socket console says it's not a bufferNodeJS,通过套接字控制台发送缓冲区后说它不是缓冲区
【发布时间】:2016-03-30 22:00:23
【问题描述】:

我正在尝试在 ECB 模式下实现 AES 加密。有代码。

function encrypt (key, iv, plaintext) {
    if(algorithm == 'aes-128-ecb') iv = new Buffer('');
    var cipher = crypto.createCipheriv(algorithm, key, iv);    
    cipher.setAutoPadding(true);
    var ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);        
    return ciphertext; }

function decrypt (key, iv, ciphertext) {
    if(algorithm == 'aes-128-ecb') iv = new Buffer('');
    var decipher = crypto.createDecipheriv(algorithm, key, iv);    
    decipher.setAutoPadding(true); 
    var plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
    return plaintext; }

当我加密缓冲区时,我通过这样的套接字发送它:

content = AES.encrypt(clients.getKeyOf(clientID), '', _msg);

            _msg = {clientID: clientID,
                    username: username,
                    timestamp: date.getHours() + ":" + ('0' + date.getMinutes()).slice(-2),
                    isEncrypted: isEncrypted,
                    content: content};

clientSocket.write( JSON.stringify(_msg));

然后我收到它并尝试像这样解密它。

var _msg = JSON.parse(msg);
_msg.content = AES.decrypt(clients.getKeyOf(_msg.clientID), '', _msg.content);

收到的数据是 JSON 解析为 JavaScript 对象,如果我尝试 console.log 它,它说它是一个缓冲区。当我尝试解密它时,错误提示“对象既不是字符串也不是缓冲区。”

【问题讨论】:

  • 缓冲区不是 JSON 可序列化的,是吗?
  • 当我将它字符串化时,我得到 {"Type":"Buffer","Data":"xxxxxx"}。我没有收到解析错误,也没有任何警告。发送缓冲区的最佳方式是什么? @Artjom B.

标签: javascript json node.js sockets encryption


【解决方案1】:

我现在很清楚,缓冲区不可序列化,即使接收和解析的 JSON 表明它是一个无法识别为缓冲区的缓冲区。

我通过从接收到的数据创建一个新的缓冲区来实现这一点,如下所示:

var buff = new Buffer(_msg.content);
_msg.content = AES.decrypt(clients.getKeyOf(_msg.clientID), '', buff).toString('utf8');

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 2014-08-19
    • 1970-01-01
    • 2018-11-08
    • 2017-08-26
    • 2023-03-31
    • 2014-05-10
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多