Create a gist now

Instantly share code, notes, and snippets.

@nov /gist:5311749
Last active Mar 8, 2016

require 'openssl'
require 'url_safe_base64'
plain_text = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJmb28iOiJiYXIifQ.'
pem = <<-PEM
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA88kMUkTuNGdEyo5xVv/xP01UjhfOGOq9h4LkOIDBsOytvyO9
D0SDWzLnItjdbniHeMqnc9gCk80O7Nwb0bAvsO40GKLHaob8+hgzl8h0/HHPAB92
TA6E5bIAsnPEgav7rf+nOYvUxaonTYAf5fbYsMynNeWfaN+z7aYAaJcK0oveovvV
Lksdn25xGtI3K2zlGv5cTX+j17awm9y6k6uOdeXgUTMlZ/3UPy0H+qkbj9XMFkXS
gDqRtGtg9C57ja2pesBl2Ir3CACxrRxh8ef8vpvlDcZ8XsdPuEYYKp69EU1Wce/J
ZDRV75OwO5prAHxyER+I2vHitRO66Mnnf2qFbQIDAQABAoIBAQC7PoOhOOKBC4SR
0+CIAyOoDFxSm0QobTxPtiBWqcabft5gvjF7ZZNC3BEd+dXyAM+E3prJZnNsVIcP
NGyFnT60NfF7rqNeVfo+mZIfFc+NClkE7iVte4Vl61ePuU2Ij7FKzt8BWz586Bkx
9KQLfJKpETepNQpAgfnwIZ2Ut9aPKXF6O+i0tkEd01PaMfOYV/3VENsfPj/uqB4t
K5vmOD23o2b++6VVOds4JKxdlow91O1Bhj1lpy9xHKXRnG+RJx44+VBF2eIJDTla
ceFJ3caxYIVY7qTP7k+XMFqeuB8jfwslIuvmZtcDed2fVYV/TqK/kB06+jqy/q/a
nuB15FLhAoGBAPxo5uFloMxqXNxQGGWTLPHg0vhNJ3E2ktU8wHmfFYVeYEcYRvzh
Ae6NgqSOj7r6Bap9+86IztVaDEjA3gZpm8quDVYWDyB4RHmnkOEiCoom1aUCEc7I
uRXRtU0/OmRZBUVeZqsbYyIQWCrEWCmQZeZy0bWH4RZvzN7NHrUuGfF1AoGBA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yRt-9nwiTRL9ZyvJNZ-u35iH_OPiTF6FpUMyA7cgPfq76bbVuGZ0Gk4aksI9Kb4FG2w.5k2WC6Cv31eE7BmD.sIJpAVQ4WENPzGDvbHBbGgLs5Hpt1lUZs4l-duZmTeu0UrlG8SnnME6dUOc89uKyrkxwZurL4A.YXg504uUHYtFEndBcbbXXA'
header, encrypted_master_key, iv, cipher_text, integrity_value = jwe.split('.').collect do |segment|
UrlSafeBase64.decode64 segment
end
master_key = private_key.private_decrypt encrypted_master_key
cipher = OpenSSL::Cipher.new('aes-128-gcm') # OpenSSL::Cipher::AES.new(128, :GDM) doesn't work..
cipher.decrypt
cipher.key = master_key
cipher.iv = iv # if you set iv before key, you get an error..
cipher.auth_tag = integrity_value
cipher.auth_data = jwe.split('.').first
decrypted = cipher.update(cipher_text) + cipher.final
puts decrypted == plain_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment