Jay seen
Jay seen

Reputation: 509

How to use node-js crypto in javascript?

I need following encryption decryption, but in java script for client-side. This code is written in Node-JS and using crypto library, i couldn't find same solution for java script for client side run.

const crypto = require('crypto');

const decrypt = (textBase64, keyBase64, ivBase64) => {
    const algorithm = 'aes-256-cbc';
    const ivBuffer = Buffer.from(ivBase64, 'base64');
    const keyBuffer = Buffer.from(keyBase64, 'base64');

    const decipher = crypto.createDecipheriv(algorithm, keyBuffer, ivBuffer);
    decipher.setAutoPadding(false);

    let decrypted = decipher.update(textBase64, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

const encryptedMessage = '';


const key = 'cGFzc3dvcmQxMjM0NTY3ODk=';

const iv = Buffer.from(encryptedMessage, 'base64').slice(0, 16);

// the message comes from the bytes AFTER the IV - this is what you should decrypt
const message = Buffer.from(encryptedMessage, 'base64').slice(16);

const result = decrypt(message, key, iv);
console.log(result);
//console.log(Buffer.from(encryptedMessage, 'base64').slice(0, 16))

Upvotes: 1

Views: 1630

Answers (1)

tsamaya
tsamaya

Reputation: 396

First I would say it is not recommended to decrypt on the client side as the key is visible. but you know what you do.

this library is pure JS and should be working in a browser without any pain : ricmoo/aes-js

Upvotes: 1

Related Questions