Skip to content

Instantly share code, notes, and snippets.

@AlbertoDePena
Last active February 22, 2018 15:35
Show Gist options
  • Save AlbertoDePena/aa97f505975e31ecc1597d717398ca6a to your computer and use it in GitHub Desktop.
Save AlbertoDePena/aa97f505975e31ecc1597d717398ca6a to your computer and use it in GitHub Desktop.
import * as Crypto from "crypto-js";
function tryExecute<T>(func: () => T, error: string) {
try { return func(); } catch { throw error; }
}
export function encrypt(key: string, plainText: string): string {
if (!key) { throw "key is required (encrypt)"; }
if (!plainText) { throw "plainText is required (encrypt)"; }
const func = (): string => Crypto.AES.encrypt(plainText, key).toString();
return tryExecute(func, "Failed to encrypt text");
}
export function decrypt(key: string, encryptedText: string): string {
if (!key) { throw "key is required (decrypt)"; }
if (!encryptedText) { throw "encryptedText is required (decrypt)"; }
const func = (): string => Crypto.AES.decrypt(encryptedText, key).toString(Crypto.enc.Utf8);
return tryExecute(func, "Failed to decrypt text");
}
export function hash(text: string): string {
if (!text) { throw "text is required (hash)"; }
const func = (): string => Crypto.SHA256(text).toString(Crypto.enc.Base64);
return tryExecute(func, "Failed to hash text");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment