Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created February 5, 2019 22:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/e18de5fa23ec1c49e3feab493d579909 to your computer and use it in GitHub Desktop.
Save havenwood/e18de5fa23ec1c49e3feab493d579909 to your computer and use it in GitHub Desktop.
Example AES256-GCM encryption with JWTs.
# gem install jose
require 'jose'
payload = {
'secret' => 'Cicadoidea'
}
##
# Encrypt your payload.
key = JOSE::JWK.from_oct SecureRandom.random_bytes 32 # Decrypt with this same key.
alg = 'A256GCMKW'
encrypted = JOSE::JWE.block_encrypt key, payload.to_json, {'alg' => alg, 'enc' => 'A256GCM'}
encrypted_payload = encrypted.compact
##
# Decrypt your payload.
decrypted_json_payload, decrypted = JOSE::JWE.block_decrypt key, encrypted_payload
decrypted_alg = decrypted.alg.algorithm
raise SecurityError, "alg `#{decrypted_alg}' does not match expected alg `#{alg}'" unless decrypted_alg == alg
decrypted_payload = JSON.parse decrypted_json_payload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment