You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Creating Cipher with IV inconsistent behaviour #2367
I have been trying to encrypt and decrypt text using crypto package. I was able to implement it successfully. Below is my code for the same:
const algorithm = 'aes-128-cfb';
const iv = crypto.randomBytes(16);
const key = 'dq14Bopnw1A1FaUi';
//Concatenating iv before cipher.update
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, key, iv);
text = Buffer.concat([Buffer.from(iv), Buffer.from(text)]);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return encrypted.toString('base64');
}
//Decrypting text
function decrypt(base64Encoded) {
let decodedData = Buffer.from(base64Encoded, "base64").toString('hex');
let decodedIV = new Buffer.from(decodedData.substring(0, 32), 'hex');
let decipher = crypto.createDecipheriv(algorithm, key, decodedIV);
let decrypted = decipher.update(decodedData.substring(32), 'hex', 'utf8') + decipher.final('utf8');
return decrypted;
}
In the encrypt function, I am concatenating the IV and text initially, then only updating the cipher.
On further research I came up with the following function to do the same.
//Concatenating iv after cipher.update
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(Buffer.from(text));
encrypted = Buffer.concat([Buffer.from(iv), encrypted, cipher.final()]);
return encrypted.toString('base64');
}
In the encrypt function, I am concatenating the IV and text at last, only after updating the cipher with text.
Output of both encrypt functions can be decrypted using the same decrypt function. Is this expected?
Activity
bnoordhuis commentedon Dec 24, 2019
See https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Feedback_(CFB) - aes-128-cfb is a self-synchronizing cipher.
If you want that a cipher that also preserves message integrity, turn to something like aes-256-gcm. Consult https://en.wikipedia.org/wiki/Authenticated_encryption for more info.
PoojaDurgad commentedon Sep 29, 2020
ping- @jithinsk
gireeshpunathil commentedon Nov 7, 2020
answered, closing. feel free to re-open if it is outstanding