Skip to content

Instantly share code, notes, and snippets.

@rigwild
Last active April 28, 2024 12:47
Show Gist options
  • Save rigwild/7af6558bd01d698c693dfef9897e13c2 to your computer and use it in GitHub Desktop.
Save rigwild/7af6558bd01d698c693dfef9897e13c2 to your computer and use it in GitHub Desktop.
Easily encrypt string or object using Crypto-JS AES encryption
'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)
<!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>
@JgBr123
Copy link

JgBr123 commented Jan 10, 2022

Thanks bro, this helped a lot

@PineappleRind
Copy link

This worked well except I had to remove .content from the end of the decrypt function (as I didn't have a content field on my object)

@mrtampan
Copy link

thank bro, this worked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment