# Stronger Encryption and Decryption in Node.js

[**encryption.js**](https://gist.github.com/vlucas/2bd40f62d20c1d49237a109d491974eb#file-encryption-js)

```
'use strict';

const crypto = require('crypto');

const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY; // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16

function encrypt(text) {
 let iv = crypto.randomBytes(IV_LENGTH);
 let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
 let encrypted = cipher.update(text);

 encrypted = Buffer.concat([encrypted, cipher.final()]);

 return iv.toString('hex') + ':' + encrypted.toString('hex');
}

function decrypt(text) {
 let textParts = text.split(':');
 let iv = Buffer.from(textParts.shift(), 'hex');
 let encryptedText = Buffer.from(textParts.join(':'), 'hex');
 let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
 let decrypted = decipher.update(encryptedText);

 decrypted = Buffer.concat([decrypted, decipher.final()]);

 return decrypted.toString();
}

module.exports = { decrypt, encrypt };
```

<figure><img src="https://2541687234-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh5QFWMbYdzucMPDzF250%2Fuploads%2F6veaafpwvVm2lxzccJgZ%2Flogotipo.png?alt=media&#x26;token=f769cbb7-2e60-47d5-b242-f822f8bf95a7" alt=""><figcaption><p>By Morgan Bin Bash</p></figcaption></figure>
