Как заменить устаревший crypto.createCipher в nodejs? - PullRequest
3 голосов
/ 24 февраля 2020

Я использую следующие функции для шифрования / дешифрования строк в nodejs:

var crypto = require('crypto');
var algorithm = 'aes-256-ctr';
function encrypt(text) {
    var cipher = crypto.createCipher(algorithm, password);
    try {
        var crypted = cipher.update(text, 'utf8', 'hex');
        crypted += cipher.final('hex');
    } catch (e) {
        return;
    }
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(algorithm, password);
    try {
        var dec = decipher.update(text, 'hex', 'utf8');
        dec += decipher.final('utf8');
    } catch (e) {
        return;
    }
    return dec;
}

(пароль хранится отдельно от закодированного текста). Новая версия пакета nodejs / crypt жалуется:

(node:5212) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.

Как мне переписать это, чтобы обновить мой исходный код?

1 Ответ

4 голосов
/ 24 февраля 2020

Итак, скажем так:

Заменить устаревшее crypto.createDecipher использование на crypto.createDecipheriv

почему? потому что:

в соответствии с устаревшим документами, это было связано с проблемами безопасности.

Использование crypto.createCipher() и crypto.createDecipher() следует избегать, так как они используют функцию вывода слабого ключа (MD5 без соли) и stati c векторы инициализации . Для получения ключа рекомендуется использовать crypto.pbkdf2() или crypto.scrypt() и использовать crypto.createCipheriv() и crypto.createDecipheriv() для получения объектов Cipher и Decipher соответственно.

Ссылка на ссылку выше: Нажмите Здесь

Кто-то также сказал:

Согласно crypto_crypto_createdecipher_algorithm_password_options , теперь нужно переключиться на crypto.createDecipheriv.

Пример кода:

const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const ENCRYPTION_KEY = 'Put_Your_Password_Here'; // or generate sample key Buffer.from('FoCKvdLslUuB4y3EZlKate7XGottHski1LmyqJHvUhs=', 'base64');
const IV_LENGTH = 16;

function encrypt(text) {
    let iv = crypto.randomBytes(IV_LENGTH);
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return iv.toString('hex') + ':' + encrypted.toString('hex');
}

function decrypt(text) {
    let textParts = text.split(':');
    let iv = Buffer.from(textParts.shift(), 'hex');
    let encryptedText = Buffer.from(textParts.join(':'), 'hex');
    let decipher = crypto.createDecipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

Для полного выполнения примера клона node-cheat и запуска node crypto-create-cipheriv.js.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...