我是否正确地进行了 AES 256 加密和解密 Node.js?

Am I doing AES 256 encryption and decryption Node.js correctly?

我需要加密将存储在数据库中的聊天消息。数据是一串不同长度的字符。我想使用本机 node.js 加密库并使用 AES 256 等对称加密协议。我担心以下问题:

  1. 对于存储在 MySQL 中的 TEXT 字段中的此类字段,CBC 是否是此用例的正确 AES 模式?
  2. 密钥看起来是否正确生成?
  3. 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;

Is CBC the correct AES mode for this use case for this type of field stored in a TEXT field in MySQL?

好吧,这在一定程度上取决于您的文字。但可能是。

Does the key look like it is generated correctly?

是的,我觉得不错。它应该看起来是随机的,它看起来是随机的。不知道你关心的是什么。

Is the IV correct? Is prepending the IV to the encrypted text a proper way to do it or should it be a separate field?

IV 看起来不错。我看不出为什么不应该这样做的原因有很多,除了一个:它的存储效率不高。将数据存储为二进制数据而不是十六进制数据会更有效率!然后你不能只用冒号来分隔数据。所以要么你知道它的第一个 n 字节,要么你做一个单独的字段。两者都有优点和缺点,但两者都可以。主要是关于风格的问题。