AES-256 Encryption / Decryption with Key in environment variable

AES-256 Encryption / Decryption with Key in environment variable

This is a very simple AES-256 string encryption/decryption program written in Node.JS using the built-in crypto library.

// aes256.js
const crypto = require('crypto');

const ENCODING = 'base64';
const KEY = process.env.MY_SECRET_KEY;

function verifyKey() {
    if (!KEY) {
        throw new Error('MY_SECRET_KEY was not found!');
    }
}

function encrypt(msg) {
    const cipheringKey = Buffer.from(crypto.createHash('sha256').update(KEY, 'utf-8').digest());
    const iv = Buffer.from(crypto.randomBytes(16));
    const cipher = crypto.createCipheriv('aes256', cipheringKey, iv);
    return Buffer.concat([
        iv, 
        cipher.update(msg),
        cipher.final()
    ]).toString(ENCODING);
}

function decrypt(encMsg) {
    const cipheringKey = Buffer.from(crypto.createHash('sha256').update(KEY, 'utf-8').digest());
    const iv = Buffer.from(Buffer.from(encMsg, ENCODING).slice(0, 16));
    const decipher = crypto.createDecipheriv('aes256', cipheringKey, iv);
    const cipheredMessage = Buffer.from( Buffer.from(encMsg, ENCODING).slice(16) );
    return Buffer.concat([
        decipher.update(cipheredMessage),
        decipher.final()
    ]).toString('utf-8');
}

function test() {
    verifyKey();
    const encryptedMessage = encrypt('test');
    const decryptedMessage = decrypt(encryptedMessage);
    return decryptedMessage === 'test'; // true / false
}

function main() {
    verifyKey();
    if (process.argv[2] === 'encrypt') {
        const encryptedMessage = encrypt(process.argv[3]);
        console.log(encryptedMessage);
    } else if (process.argv[2] === 'decrypt') {
        const decryptedMessage = decrypt(process.argv[3]);
        console.log(decryptedMessage);
    } else {
        console.log('Usage: node aes.js encrypt|decrypt EncryptedMessage|DecryptedMessage');
    }
}

// --- Program --------------------
test();
main();

In the terminal:

export MY_SECRET_KEY=SomeSecretKey

node aes256.js encrypt "Hello World"
# prints: jT5KnFhZLAZpUMt93eac8GQuhTL5apQhAmjWb5gzSFo=

node aes256.js decrypt jT5KnFhZLAZpUMt93eac8GQuhTL5apQhAmjWb5gzSFo=
# prints: Hello World