Created
January 15, 2023 16:58
-
-
Save thecodecafe/9a84c694f2533d591ad0e9fb459beb11 to your computer and use it in GitHub Desktop.
Revisions
-
thecodecafe created this gist
Jan 15, 2023 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,69 @@ import CryptoJS, {AES, MD5} from 'crypto-js'; import {ENC_KEY} from '../configs/app.config'; /** * Encrypts any given data * @param {any} data * @return string | null */ export const encrypto = async ( data: any, customKey?: string, ): Promise<string | null> => { try { // encrypt data an return as string return AES.encrypt(JSON.stringify(data), customKey || ENC_KEY).toString(); } catch (e) { return null; } }; /** * Decrypts any system encrypted data * @param {string} data * @return string | null */ export async function decrypto<D = any>( data: string, customKey?: string, ): Promise<D | null> { try { // JSON parse decrypted data and return it return JSON.parse( AES.decrypt(data, customKey || ENC_KEY).toString(CryptoJS.enc.Utf8), ); } catch (e) { return Promise.resolve(null); } } /** * MD5 encrypt any given string * @param {string} data * @return string */ export const md5 = (data: string): string => { return MD5(data).toString(); }; /** * This function encodes a given string to base64 * @param data string * @returns string */ export function base64Encode(data: string): string { const encodedWord = CryptoJS.enc.Utf8.parse(data); const encoded = CryptoJS.enc.Base64.stringify(encodedWord); return encoded; } /** * This function decodes a given base64 string * @param encodedData string * @returns string */ export function base64Decode(encodedData: string): string { const encodedWord = CryptoJS.enc.Base64.parse(encodedData); const decoded = CryptoJS.enc.Utf8.stringify(encodedWord); return decoded; }