Closed
Description
- Version: 13.0.1
- Platform: Linux WORKPC 4.15.0-72-generic fs: fix fd leak on early readstream destroy node#81-Ubuntu SMP Tue Nov 26 12:20:02 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
- Subsystem: crypto
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?
Metadata
Metadata
Assignees
Labels
No labels