Last active
June 3, 2022 14:34
-
-
Save jrue/6f8419fb0d632c05df01 to your computer and use it in GitHub Desktop.
Encrypt static HTML with Ruby and CryptoJS.
This file contains hidden or 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
var payload = "{{ content | encrypt_data }}".split("|"); //content via Ruby | |
var iv = payload[0] | |
hmac = payload[1], | |
cipherText = payload[2]; | |
//CryptoJS keeps all objects as WordArrays, so you have to coerce as strings at times. | |
//Only get passphrase via input or cookie, convert to sha256 hex digest | |
//echo -n "passphrase" | openssl dgst -sha256 | |
//(In El Capitan, may need to run a sudo) | |
//var passphraseDgst = CryptoJS.SHA256("passphrase").toString(); | |
var key = passphraseDgst; | |
//compare above passphrase with HMAC signature of data (to see if key is the right one) | |
var decryptedhmac = CryptoJS.HmacSHA256(cipherText, CryptoJS.enc.Hex.parse(passphraseDgst)).toString().trim(); | |
//If they match... | |
if(CryptoJS.enc.Base64.parse(hmac).toString() === decryptedhmac){ | |
//decrypt based on key (passphrase) and iv | |
var decrypted = CryptoJS.AES.decrypt( | |
{ciphertext:CryptoJS.enc.Base64.parse(cipherText)}, | |
CryptoJS.enc.Hex.parse(passphraseDgst), | |
{iv:CryptoJS.enc.Base64.parse(iv)} | |
); | |
var html = CryptoJS.enc.Utf8.stringify(decrypted);//do something with html | |
} |
This file contains hidden or 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
def encrypt_data(input) | |
digest = Digest::SHA256.new | |
digest.update("passphrase") | |
key = digest.digest | |
cipher = OpenSSL::Cipher::AES256.new(:CBC) | |
cipher.encrypt | |
cipher.key = key | |
cipher.iv = iv = cipher.random_iv | |
encrypted = cipher.update(input) + cipher.final | |
encoded_msg = Base64.encode64(encrypted).gsub(/\n/, '') | |
encoded_iv = Base64.encode64(iv).gsub(/\n/, '') | |
hmac = Base64.encode64(OpenSSL::HMAC.digest('sha256', key, encoded_msg)).strip | |
"#{encoded_iv}|#{hmac}|#{encoded_msg}" | |
end |
This file contains hidden or 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
<!-- https://code.google.com/archive/p/crypto-js/ --> | |
<script src="js/rollups/aes.js"></script> | |
<script src="js/rollups/sha256-min.js"></script> | |
<script src="js/rollups/hmac-sha256.js"></script> | |
<script src="decrypt.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment