【发布时间】:2018-09-06 21:33:19
【问题描述】:
我需要加密将存储在数据库中的聊天消息。数据是一串不同长度的字符。我想使用本机 node.js 加密库并使用对称加密协议,例如 AES 256。我有以下担忧:
- 对于存储在 MySQL 中
TEXT字段中的此类字段,对于此用例,CBC 是否是正确的 AES 模式? - 密钥看起来是否正确生成?
- IV 是否正确?将 IV 添加到加密文本之前是一种正确的方法还是应该是一个单独的字段?
// AES RFC - https://tools.ietf.org/html/rfc3602
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
// generate key with crypto.randomBytes(256/8).toString('hex')
const key = '6d858102402dbbeb0f9bb711e3d13a1229684792db4940db0d0e71c08ca602e1';
const IV_LENGTH = 16;
const encrypt = (text) => {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key, 'hex'), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
};
const decrypt = (text) => {
const [iv, encryptedText] = text.split(':').map(part => Buffer.from(part, 'hex'));
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key, 'hex'), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
};
exports.encrypt = encrypt;
exports.decrypt = decrypt;
【问题讨论】:
-
@MattClark 我相信这不是重复的,因为它提供了一个使用 IV 并演示解密的示例。
-
@MattClark 这看起来更好吗?这真的是我的担忧。还说某人有一个“可怕的问题”并表现出“不努力”似乎与 StackExchange 行为准则不符。 meta.stackexchange.com/conduct
-
您有什么顾虑?乍一看,这对我来说很好。
-
这段代码对你有用吗?
标签: javascript node.js encryption encryption-symmetric