Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active February 25, 2023 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/16907cd0f327119ccc5d7f2a168c5a0f to your computer and use it in GitHub Desktop.
Save primaryobjects/16907cd0f327119ccc5d7f2a168c5a0f to your computer and use it in GitHub Desktop.
How to protect a JavaScript file with encryption. https://jsfiddle.net/yo0dvrjt/2/
U2FsdGVkX1/7DNglflcflNX1NepqxK7hBWR8E7BW3ZYSrQ4a7/EuyFNJe2mVXZqb63/Ln0Jf93I+ZX3h7oT1ew==
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<div id="decrypted"></div>
<button id="load">Load</button>
<script>
//
// Decrypt
//
// 1. Define a password.
var key = "secret";
// 2. Download the encrypted file.
$.get('https://gist.githubusercontent.com/primaryobjects/16907cd0f327119ccc5d7f2a168c5a0f/raw/4913ade697e5312c679f42c2576f8cbd07f44fd9/data.dat', data => {
// 3. Decrypt the string and evaluate back to an array named 'arr'.
arr = eval(CryptoJS.AES.decrypt(data, key).toString(CryptoJS.enc.Utf8));
});
// 4. When clicking the 'Load' button, print the contents of arr. This variable is now global!
$('#load').click(() => {
document.getElementById('decrypted').innerHTML = JSON.stringify(arr);
});
</script>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<div id="encrypted"></div>
<script>
//
// Encrypt Utility
//
// 1. Define a password.
var key = "secret";
// 2. Define an array that you want to encrypt in a separate file.
const payload = `[
'one',
'two',
'three'
]`;
// 3. Encrypt the array.
const encrypted = CryptoJS.AES.encrypt(payload, key);
// 4. Print the encrypted text to the web page.
document.getElementById('encrypted').innerHTML = encrypted;
// 5. Copy the encrytped string in the textbox, save to a new file, and upload to destination. This example is using github.
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment