Last active
October 20, 2024 09:44
-
-
Save siwalikm/8311cf0a287b98ef67c73c1b03b47154 to your computer and use it in GitHub Desktop.
AES-256-CBC implementation in nodeJS with built-in Crypto library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const crypto = require('crypto'); | |
const ENC_KEY = "bf3c199c2470cb477d907b1e0917c17b"; // set random encryption key | |
const IV = "5183666c72eec9e4"; // set random initialisation vector | |
// ENC_KEY and IV can be generated as crypto.randomBytes(32).toString('hex'); | |
const phrase = "who let the dogs out"; | |
var encrypt = ((val) => { | |
let cipher = crypto.createCipheriv('aes-256-cbc', ENC_KEY, IV); | |
let encrypted = cipher.update(val, 'utf8', 'base64'); | |
encrypted += cipher.final('base64'); | |
return encrypted; | |
}); | |
var decrypt = ((encrypted) => { | |
let decipher = crypto.createDecipheriv('aes-256-cbc', ENC_KEY, IV); | |
let decrypted = decipher.update(encrypted, 'base64', 'utf8'); | |
return (decrypted + decipher.final('utf8')); | |
}); | |
encrypted_key = encrypt(phrase); | |
original_phrase = decrypt(encrypted_key); | |
// star this gist if you found it useful |
Hey anyone help me on this issue please
Error: Trying to add data in unsupported state
at Decipheriv.update
hey! @siwalikm
can you help me with this following problem.
I am provided a key which is 64 byte long, and we are supposed to use aes-256-cbc algorithm for encryption.
How should we use it for encryption, since at max we can use 32 bytes long key.
So is there any standard way of dealing with such problem, since I am not the one who is going to decrypt the data or I need to talk with that person who is going to decrypt it and ask for how is he decreasing its key length.
Kindly help!
Much obliged, it helped for my current case.
FYI, if someone still has problem creating random keys, this is how you can do it:
const ENC_KEY = "bf3c199c2470cb477d907b1e0917c17b"; // # Generate: crypto.randomBytes(32).toString("hex").slice(0, 32);
const IV = "5183666c72eec9e4"; //Generate: crypto.randomBytes(16).toString("hex").slice(0, 16);
Danny Bullo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have to import/require crypto module. You don't need to install it because it's built-in in nodeJS.
If your problem hasn't solved, please try to update nodejs to latest version