使用模块 'crypto' 对十六进制数据进行 NodeJS DES ECB 加密

NodeJS DES ECB encryption of hex data with module 'crypto'

我正在尝试 encrypt/decrypt 十六进制数据 使用 node js 模块 'crypto'DES-ECB算法。在官方 'crypto' 文档中,他们给出了 CBC 模式下的 aes-192 加密示例(参见附加代码),但是 ECB 模式不需要 iv(初始化向量) .我不知道如何修改此代码以使用 DES 算法在 ECB 模式下加密。

这里是node js'crypto'模块(https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_class_cipher)官方文档中给出的JavaScript代码:

const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const cipher = crypto.createCipheriv(algorithm, key, iv);

let encrypted = '';
cipher.on('readable', () => {
  let chunk;
  while (null !== (chunk = cipher.read())) {
    encrypted += chunk.toString('hex');
  }
});
cipher.on('end', () => {
  console.log(encrypted);
  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
});

cipher.write('some clear text data');
cipher.end();

在我的例子中,我必须将 "algorithm" 字段更改为:

const algorithm = 'des-ecb'

但是我还必须调整处理 iv 的部分(因为 DES-ECB 算法不需要 iv),我不知道该怎么做...

非常感谢!

您可以尝试这种方法,这应该可以满足您的要求:

const crypto = require('crypto');
const algorithm = 'des-ecb';
const password = 'some password';
// use a hex key here
const key = Buffer.from("d0e276d0144890d3", "hex");

const cipher = crypto.createCipheriv(algorithm, key, null);
let encrypted = cipher.update("Those are my principles, and if you don't like them... well, I have others.", 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log("Encrypted: ", encrypted);

const decipher = crypto.createDecipheriv(algorithm, key, null);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log("Decrypted: ", decrypted);