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
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?
The text was updated successfully, but these errors were encountered:
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:
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.
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 samedecrypt
function. Is this expected?The text was updated successfully, but these errors were encountered: