Skip to content

Instantly share code, notes, and snippets.

@jrue
Last active June 3, 2022 14:34
Show Gist options
  • Save jrue/6f8419fb0d632c05df01 to your computer and use it in GitHub Desktop.
Save jrue/6f8419fb0d632c05df01 to your computer and use it in GitHub Desktop.
Encrypt static HTML with Ruby and CryptoJS.
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
}
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
<!-- 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