Last active
July 15, 2021 03:23
-
-
Save chris-burkhardt/80ac5b52e40b346b41cc6a7fec324a70 to your computer and use it in GitHub Desktop.
JS Crypto Encryption Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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