jpo*_*s18 7 javascript encryption encryption-symmetric node.js
我需要加密将存储在数据库中的聊天消息。数据是一串不同长度的字符。我想使用本机 node.js 加密库并使用对称加密协议,例如 AES 256。我担心以下问题:
TEXT?// 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;
Run Code Online (Sandbox Code Playgroud)
对于存储在 MySQL 中 TEXT 字段中的此类字段,CBC 是否是此用例的正确 AES 模式?
嗯,这有点取决于你的文字。但可能是的。
密钥看起来是否正确生成?
是的,我觉得不错。它应该看起来是随机的,而且看起来也是随机的。不确定您在这里担心什么。
IV 正确吗?在加密文本前添加 IV 是正确的方法还是应该将其作为一个单独的字段?
IV 对我来说看起来不错。我看不出有什么理由不应该这样做,除了一个:它的存储效率不是很高。将数据存储为二进制数据而不是十六进制字符串会更有效!然后你不能只使用冒号来分隔数据。所以要么你知道它是第一个n字节,要么你做一个单独的字段。两者都有优点和缺点,但都还可以。这是关于风格的主要问题。
| 归档时间: |
|
| 查看次数: |
11997 次 |
| 最近记录: |