NodeJS DES ECB шифрование шестнадцатеричных данных с помощью модуля «crypto» - PullRequest
0 голосов
/ 08 июля 2019

Я пытаюсь шифровать / дешифровать шестнадцатеричные данные , используя узел js, модуль 'crypto' с алгоритмом DES-ECB . В официальной крипто-документации они приводят пример шифрования aes-192 в режиме CBC (см. Прилагаемый код), но в режиме ECB не требуется iv (вектор инициализации) . Я не знаю, как адаптировать этот код для шифрования в режиме ECB с помощью алгоритма DES.

Вот код JavaScript, приведенный в официальной документации модуля js 'crypto' (https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_class_cipher):

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();

В моем случае я должен изменить поле «алгоритм» на:

const algorithm = 'des-ecb'

Но тогда я также должен адаптировать части, относящиеся к iv (так как для алгоритма DES-ECB не требуется iv), и я не знаю, как это сделать ...

Большое спасибо!

1 Ответ

0 голосов
/ 09 июля 2019

Вы можете попробовать этот подход, это должно делать то, что вы хотите:

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);
...