Simple encryption and decryption with secret in TypeScript

Simple encryption and decryption with secret in TypeScript

·

1 min read

In this article I will show you how to easier using built-in nodejs module crypto.

For this code we need SECRET_KEY and SECRET_IV environments.

You can write everything in this variables but if you change values after encrypted data, you decryption will fail.

// file: cryption.ts
export class Cryption {
  private static key = Crypto.createHash('sha512')
    .update(process.env['SECRET_KEY'], 'utf-8')
    .digest('hex')
    .substr(0, 32);
  private static iv = Crypto.createHash('sha512')
    .update(process.env['SECRET_IV'], 'utf-8')
    .digest('hex')
    .substr(0, 16);
  private static encryptionMethod = 'AES-256-CBC';

  static encrypt(plainData: string) {
    const encryptor = Crypto.createCipheriv(
      Cryption.encryptionMethod,
      Cryption.key,
      Cryption.iv,
    );
    return Buffer.from(
      encryptor.update(plainData, 'utf8', 'base64') + encryptor.final('base64'),
    ).toString('base64');
  }

  static decrypt(encryptedData) {
    const buff = Buffer.from(encryptedData, 'base64');
    encryptedData = buff.toString('utf-8');
    const decryptor: Crypto.Decipher = Crypto.createDecipheriv(
      Cryption.encryptionMethod,
      Cryption.key,
      Cryption.iv,
    );
    return (
      decryptor.update(encryptedData, 'base64', 'utf8') +
      decryptor.final('utf8')
    );
  }
}

And usage:

// file: index.ts
import {Cryption} from './cryption';

const plainData = 'plain message';

const encrypted = Cryption.encrypt(plainData);
console.log(encrypted);


const decrypted = Cryption.decrypt(ecrypted);
console.log(decrypted);

console.log(plainData === decrypted); // true