Created
June 5, 2020 19:22
-
-
Save twopoint718/68d28072f5caa56a6e88b824cee4fc7e to your computer and use it in GitHub Desktop.
A script to decode a JSON Web Token given on standard input
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
| #!/usr/bin/env ruby | |
| require 'base64' | |
| require 'json' | |
| require 'openssl' | |
| if ARGV.include?('-h') || ARGV.include?('--help') | |
| puts <<~EOS | |
| USAGE | |
| read_jwt.rb [BASE64_KEY] | |
| Decodes a JSON Web Token given on standard input. If a base64-encoded secret | |
| key is given as the first argument to read_jwt.rb, then it will attempt to | |
| verify the authenticity of the token. Currently, this only works for | |
| tokens using the HMAC-SHA256 authentication algorithm (alg = 'HS256'). | |
| OPTIONS | |
| -h --help This help message | |
| EXAMPLES | |
| pbpaste | ./read_jwt.rb bXkgc2VjcmV0IGtleQo= | |
| EOS | |
| exit 0 | |
| end | |
| header, payload, signature = $stdin.read.split('.') | |
| puts JSON.pretty_generate(JSON.parse(Base64.decode64(header))) | |
| puts | |
| puts JSON.pretty_generate(JSON.parse(Base64.decode64(payload))) | |
| if ARGV[0] | |
| key = Base64.decode64(ARGV[0]) | |
| verification_string = "#{header}.#{payload}" | |
| hmac = OpenSSL::HMAC.digest('sha256', key, verification_string) | |
| computed_signature = Base64.urlsafe_encode64(hmac, padding: false) | |
| puts | |
| if computed_signature == signature | |
| puts "(signature verified)" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment