Skip to content

Instantly share code, notes, and snippets.

@maraisr
Created November 27, 2017 03:07
Show Gist options
  • Save maraisr/01248a1debecd7ea82324b9ff1b13f33 to your computer and use it in GitHub Desktop.
Save maraisr/01248a1debecd7ea82324b9ff1b13f33 to your computer and use it in GitHub Desktop.
Encrypt / Decrypt using createCipheriv
const {createCipheriv, createDecipheriv, createHash, randomBytes} = require('crypto');
function encrypt (input, password) {
const IV = Buffer.from(randomBytes(16));
const encryptor = createCipheriv(
'aes-128-cbc',
createHash('md5').update(password).digest(),
IV
);
encryptor.setAutoPadding(true);
encryptor.write(input);
encryptor.end();
return Buffer.concat([
IV,
encryptor.read()
]).toString('base64');
}
function decrypt (cipher, password) {
const un_base64 = Buffer.from(cipher, 'base64');
const IV = un_base64.slice(0, 16);
const cipher_text = un_base64.slice(16);
const decrypter = createDecipheriv(
'aes-128-cbc',
createHash('md5').update(password).digest(),
IV
);
decrypter.write(cipher_text);
decrypter.end();
return decrypter.read().toString('utf8');
}
const encrypted = encrypt('https://www.youtube.com/watch?v=ab8GtuPdrUQ', 'somepassword');
const decrypted = decrypt(encrypted, 'somepassword');
console.log({encrypted});
console.log({decrypted});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment