在nodejs中使用aes-128-ecb加密数据

Ans*_*Rai 2 encryption aes node.js cryptojs

我必须在 nodejs 中使用 aes-128-ecb 加密数据,我的代码是

我正在使用 Crypto 来加密数据

const crypto = require('crypto');

const secret = '1000060000000000';

const cipher = crypto.createCipher('aes-128-ecb', secret);

const ciphertext = cipher.update('9', 'utf8', 'base64')+cipher.final('base64');

console.log("Cipher text is: " + ciphertext);
Run Code Online (Sandbox Code Playgroud)

输出应该是,EtgITaHs6lEvEHBipj08Kg== 但输出是nNzqejauQBnfiDqznGhZ0Q==

Ter*_*nox 5

这里的问题是crypto.createCipher的使用,它不直接使用密钥,而是使用摘要。

引用文档:

crypto.createCipher() 的实现使用 OpenSSL 函数 EVP_BytesToKey 派生密钥,摘要算法设置为 MD5、一次迭代且无盐。

另一方面,如果我们使用cipher.createCipheriv ,我们可以直接指定密钥,它将给我们预期的输出。

这是一个例子:

const crypto = require("crypto");

function encrypt(plainText, key, outputEncoding = "base64") {
    const cipher = crypto.createCipheriv("aes-128-ecb", key, null);
    return Buffer.concat([cipher.update(plainText), cipher.final()]).toString(outputEncoding);
}

function decrypt(cipherText, key, outputEncoding = "utf8") {
    const cipher = crypto.createDecipheriv("aes-128-ecb", key, null);
    return Buffer.concat([cipher.update(cipherText), cipher.final()]).toString(outputEncoding);
}

const key = "1000060000000000";
const plainText = "9";
const encrypted = encrypt(plainText, key, "base64");
console.log("Encrypted string (base64):", encrypted);
const decrypted = decrypt(Buffer.from(encrypted, "base64"), key, "utf8")
console.log("Decrypted string:", decrypted);
Run Code Online (Sandbox Code Playgroud)

输出将是

EtgITaHs6lEvEHBipj08Kg==
Run Code Online (Sandbox Code Playgroud)