поэтому я пытаюсь зашифровать текст (например: некоторый HTML-код), а затем снова расшифровать его, когда это необходимо … но когда я пытаюсь расшифровать хеш с указанным iv и солью, он терпит неудачу со следующей ошибкой:
node:internal/crypto/cipher:119
this[kHandle].initiv(cipher, credential, iv, authTagLength);
^
RangeError: Invalid key length
at Decipheriv.createCipherBase (node:internal/crypto/cipher:119:19)
at Decipheriv.createCipherWithIV (node:internal/crypto/cipher:138:3)
at new Decipheriv (node:internal/crypto/cipher:292:3)
at Object.createDecipheriv (node:crypto:146:10)
at EncryptionWorker.decrypt (/home/{USER}/Desktop/test.js:20:37)
at Object.<anonymous> (/home/{USER}/Desktop/test.js:31:30)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14) {
code: 'ERR_CRYPTO_INVALID_KEYLEN'
}
Мой код:
const crypto = require('crypto');
class EncryptionWorker {
constructor (algorithm) {
this.algorithm = algorithm;
}
encrypt (text, secret) {
const iv = crypto.randomBytes(16);
const salt = crypto.scryptSync(secret, crypto.randomBytes(16), 32);
const HashCipher = crypto.createCipheriv(this.algorithm, salt, iv, {
authTagLength: 16
});
return {
iv: iv.toString('hex'),
salt: salt.toString('hex'),
hash: (Buffer.concat([iv, Buffer.concat([Buffer.from(HashCipher.update(text, 'utf8', 'hex')), Buffer.from(HashCipher.final('hex'))]), HashCipher.getAuthTag()])).toString('hex')
};
}
decrypt (ciphertext, salt) {
const HashDecipher = crypto.createDecipheriv(this.algorithm, salt, ciphertext.slice(0, 12), { // Line number 20
authTagLength: 16
});
HashDecipher.setAuthTag(ciphertext.slice(-16));
return (Buffer.concat([Buffer.from(HashDecipher.update(ciphertext.slice(12, -16), 'hex', 'utf8')), Buffer.from(HashDecipher.final('utf8'))])).toString();
}
}
как я это использовал:
var Cryptoworker = new EncryptionWorker('aes-256-gcm');
var Encrypted = Cryptoworker.encrypt('Hey You', 'HeyYou$#');
console.log("Encrypted: " + Encrypted);
var decrypted = Cryptoworker.decrypt(Encrypted.hash, Encrypted.salt);
console.log("Decrypted: " + decrypted);
выход:
Encrypted: {
iv: 'f6debb9dad9f037218aa943e418755eb',
salt: 'b4312550312ccecdbef471d6e35232a5e78cb0063f7f9de4d03ba67d6eab9777',
hash: 'f6debb9dad9f037218aa943e418755eb64343763343664346566646633398408d4b3989b1b8886bc8f46936afa9d'
}