当前位置: 首页 > 知识库问答 >
问题:

Nodejs createCipheriv like openssl

卫俊誉
2023-03-14

Mariadb的rest加密依赖于OpenSSL对keys.txt文件的sha1加密(https://mariadb.com/kb/en/library/encryption-key-management/#encrypting-the-key-file)。我需要使用node.js启动一个MariaDB实例。因此,我需要使用Node.js以类似的方式加密这个文件。到目前为止,使用https://html" target="_blank">github.com/beeven/gulp-openssl-encrypt作为指南,我已经能够复制OpenSSL版本的-MD MD5。但那不是Mariadb要求的sha1文摘。

function md5(data) {
  let hash = crypto.createHash('md5');
  hash.update(data);
  return hash.digest();
}
const buffer = Buffer.from(stringToEncrypt);
const salt = crypto.randomBytes(8);
const password = Buffer.from(encryptionKey);
const hash1 = md5(Buffer.concat([password, salt]));
const hash2 = md5(Buffer.concat([hash1, password, salt]));
const key = Buffer.concat([hash1, hash2]);
const iv = md5(Buffer.concat([hash2, password, salt]));
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
const chunks = [Buffer.from('Salted__'),salt];
chunks.push(cipher.update(buffer));
chunks.push(cipher.final());
let encryptedStuff = Buffer.concat(chunks);

(编辑:澄清)我想要的是这样的东西:

function sha1(data) {
  let hash = crypto.createHash('sha1');
  hash.update(data);
  return hash.digest();
}
const buffer = Buffer.from(stringToEncrypt);
const salt = crypto.randomBytes(8);
const password = Buffer.from(encryptionKey);
const hash1 = sha1(Buffer.concat([password, salt]));
const hash2 = sha1(Buffer.concat([hash1, password, salt]));
const key = Buffer.concat([hash1, hash2]);
const iv = sha1(Buffer.concat([hash2, password, salt]));
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
const chunks = [Buffer.from('Salted__'),salt];
chunks.push(cipher.update(buffer));
chunks.push(cipher.final());
let encryptedStuff = Buffer.concat(chunks);

但是当我尝试时,密钥和iv变得太长,它错误为“无效的密钥长度”。因此,当我试图按照https://github.com/nodejs/node/issues/6696的建议对它进行切片时,它确实对它进行了加密,但openssl不能对其进行解密。

共有1个答案

卢嘉誉
2023-03-14

有关用于encevp_bytestokey的基于OpenSSL密码的加密方案的详细信息,请参阅https://crypto.stackexchange.com/questions/3298/is-there-a-standard-for-openssl-interoperable-aes-encryption

CBC模式下的AES-256键+IV需要48个八位字节,而SHA1输出为20个八位字节,因此必须:

// do three hashes, much as you already have
hash1 = sha1(Buffer.concat([password, salt]));
hash2 = sha1(Buffer.concat([hash1, password, salt]));
hash3 = sha1(Buffer.concat([hash2, password, salt]));

// then concatenate them and split _that_ to key and IV 
total = Buffer.concat([hash1,hash2,hash3]);
key = total.slice(0,32);
iv = total.slice(32,48);

对于md5,将它们分开处理是有效的,因为16个八位字节的md5输出正好是密钥大小的一半,也正好是IV大小。

 类似资料:

相关问答

相关文章

相关阅读