Last active
April 28, 2024 12:47
-
-
Save rigwild/7af6558bd01d698c693dfef9897e13c2 to your computer and use it in GitHub Desktop.
Easily encrypt string or object using Crypto-JS AES encryption
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' | |
const password = 'secure secret key' | |
const encrypt = (content, password) => CryptoJS.AES.encrypt(JSON.stringify({ content }), password).toString() | |
const decrypt = (crypted, password) => JSON.parse(CryptoJS.AES.decrypt(crypted, password).toString(CryptoJS.enc.Utf8)).content | |
// Encrypt | |
const encryptedString = encrypt('This is a string', password) | |
const encryptedObject = encrypt({ test: 'This is an object' }, password) | |
console.log(encryptedString) | |
console.log(encryptedObject) | |
// Decrypt | |
const decryptedString = decrypt(encryptedString, password) | |
const decryptedObject = decrypt(encryptedObject, password) | |
console.log(decryptedString) | |
console.log(decryptedObject) |
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<title>Page Title</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script> | |
<script type="module"> | |
'use strict' | |
console.log(CryptoJS) | |
const password = 'secure secret key' | |
const encrypt = (content, password) => CryptoJS.AES.encrypt(JSON.stringify({ content }), password).toString() | |
const decrypt = (crypted, password) => | |
JSON.parse(CryptoJS.AES.decrypt(crypted, password).toString(CryptoJS.enc.Utf8)).content | |
// Encrypt | |
const encryptedString = encrypt('This is a string', password) | |
const encryptedObject = encrypt({ test: 'This is an object' }, password) | |
console.log(encryptedString) | |
console.log(encryptedObject) | |
// Decrypt | |
const decryptedString = decrypt(encryptedString, password) | |
const decryptedObject = decrypt(encryptedObject, password) | |
console.log(decryptedString) | |
console.log(decryptedObject) | |
</script> | |
</head> | |
<body> | |
<h1>Hello</h1> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank bro, this worked