Skip to content

Creating Cipher with IV inconsistent behaviour #2367

Closed
@jithinsk

Description

@jithinsk

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions