Created
February 5, 2019 22:29
-
-
Save havenwood/e18de5fa23ec1c49e3feab493d579909 to your computer and use it in GitHub Desktop.
Example AES256-GCM encryption with JWTs.
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
# 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