Skip to content

Instantly share code, notes, and snippets.

@thecodecafe
Created January 15, 2023 16:58
Show Gist options
  • Save thecodecafe/9a84c694f2533d591ad0e9fb459beb11 to your computer and use it in GitHub Desktop.
Save thecodecafe/9a84c694f2533d591ad0e9fb459beb11 to your computer and use it in GitHub Desktop.
AES, Base64, and MD5 Encryption with CryptoJS
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment