Skip to content

Instantly share code, notes, and snippets.

@chris-burkhardt
Last active July 15, 2021 03:23
Show Gist options
  • Save chris-burkhardt/80ac5b52e40b346b41cc6a7fec324a70 to your computer and use it in GitHub Desktop.
Save chris-burkhardt/80ac5b52e40b346b41cc6a7fec324a70 to your computer and use it in GitHub Desktop.
JS Crypto Encryption Service
'use strict'
// use the following online tool for encryption and decryption testing
// https://www.javainuse.com/aesgenerator
const CryptoJS = require('crypto-js');
class EncryptionService {
/**
* Encrypts a plain-text string using AES-256 cipher with the following settings
* Mode: CBC, Key Size: 256, Output Format: Base64
* Intialization Vector (from config)
* Secret Key (from config)
*
* @param {*} plainTextToken
* @param {*} configData Reference to location of config data
* @returns Encrypted Token string
*/
encryptAES256Token(plainTextToken, configData) {
const encryptionKey = CryptoJS.enc.Utf8.parse(configData.encryptionKey);
const iv = CryptoJS.enc.Utf8.parse(configData.initializationVector);
const encryptedToken = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plainTextToken), encryptionKey, {
iv,
mode: CryptoJS.mode.CBC
})
return encryptedToken.toString();
}
/**
* Decrypts an AES-256 encrypted string with the following settings
* Mode: CBC, Key Size: 256, Output Format: Base64
* Intialization Vector (from config)
* Secret Key (from config)
*
* @param {string} token Encrypted token
* @param {*} configData Reference to location of config data
* @returns Decrypted Token string
*/
decryptAES256Token(token, configData) {
const encryptionKey = CryptoJS.enc.Utf8.parse(configData.encryptionKey);
const iv = CryptoJS.enc.Utf8.parse(configData.initializationVector);
const decrypted = CryptoJS.AES.decrypt(token, encryptionKey, {
iv,
mode: CryptoJS.mode.CBC
})
return decrypted.toString(CryptoJS.enc.Utf8);
}
}
module.exports = {
encryptionService: new EncryptionService()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment