Created
February 2, 2023 15:49
-
-
Save MarcosSantosDev/29bab0fd030ffe519d34ecc7b8e0b7fe to your computer and use it in GitHub Desktop.
Using the "crypto-js" library with encryption and decryption methods
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
import CryptoJS from 'crypto-js'; | |
export const encryptData = <T = unknown>(secretPass: string, data: T) => { | |
const encryptedData = CryptoJS.AES.encrypt( | |
JSON.stringify(data), | |
secretPass, | |
).toString(); | |
return encryptedData; | |
}; | |
export const decryptData = <T = unknown>( | |
secretPass: string, | |
encryptedData: string, | |
): T => { | |
const bytes = CryptoJS.AES.decrypt(encryptedData, secretPass); | |
const decryptedData: T = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); | |
return decryptedData; | |
}; | |
const cripto = <T>(secretPass: string) => { | |
return { | |
encrypt: (data: T) => encryptData<T>(secretPass, data), | |
decrypt: (encryptedData: string) => { | |
return decryptData<T>(secretPass, encryptedData); | |
}, | |
}; | |
}; | |
export default cripto; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment