public
Last active

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
require 'openssl'
require 'url_safe_base64'
 
original = "Hello World"
 
pem = <<-PEM
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,A6B5D10FFA23D7BC66CE4FB46B754E8C
 
gvYFJmzetWSwpf1Ut6USm4IReFLA6bpp5nVUfU2Xa9dJmrCu0cTupTkdzNmGp14/
mzeT/a5WplK1hWV41Y7bLm57hOpaoxbEx2h3IW9cxuqgAp422AbafRu6hEvjUONO
qUEm63I4d7/FKo0he4IVVx0UHaX5eEq8pdY1AZR9+fqlxWvjpgZlB0anT3AMpfVL
CY4sGc/Es14M9A4zUpOkp+09PbV3WNG8A4G4IJA3wx6tYBxrd2866Te2ccP6/BL8
HA2uoqeD+70ziybvd//CtGAD1xoTDvOCwzXXT5A4fCuec3apFp8O6WyJ63ao99R4
E0r6AvD4iOkLMC8K2YUSc1zFLJAkhlfhBb8qFbXOwOomazWf2Z8rDtkP1VCfB9gC
W6oYRBOyVUkbaBSBOOPBJtxjuTL/cJBvFhn6r0zdC67g0CD4cabMPd1VY92lUVbl
JvE9CouDB5O39jwfpgfxo3kGev2UzwRze9U2uw6EdYIUB/ixyC8/5BoN8lKZXdTn
7vQBmcBsC3boMqQiq2c/dVGW7yrt/Y4q8wq9aGFwdBAY1pYhRlOZ0MwFmlAJKOzo
Y3i2OILtPM0sdfqIeAvrwicQULGAzLGEhecDOQ1r0GwZRy5/Sl3ILxKMW8ngdaK4
iNDM56u6F9dwqqArrZDZgkfwnKakXU2ZbltSOWTCleCfYrc1D75Yw3FHKcWozB/l
uyMTIqzBXzO6OiNDUv7zAE1xzVaV+VeBH/5KGx18dAuRP3TnpYltGSUVDyGk9FX7
m7nhvkqOcF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kmTG1KfAVchNj3iLSHBb5v9jlXNo8XHBwtBd7KUt6TNs6UK29sdRXVoshhCek9TLzjE3V79Pdzcyup1moixRr_zk8U8rxvijHPMBziiP6oiwpxWpapGYHzirXPsPayg6gJ8ODXzMGlZ4w6S7Pcg-uIW7vSXNjp_Bh3mwuWnp-fZ-ueqIjuPD6m2x6Ar7TbaqUV1RVxrnIzs7woiW4oNsRMkgeFbAmn9ny1cvHg.UTEZoZT26O-ZP8HL.1RpYVQ7mMVbSSKA.SsLMclnhsALLXS1_qXcO_A'
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::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('.')[0, 3].join('.')
 
plain = cipher.update(cipher_text) + cipher.final
 
puts plain == original #=> true

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.