【发布时间】: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