jwt-0.1.8/0000755000004100000410000000000012147471124012357 5ustar www-datawww-datajwt-0.1.8/Rakefile0000644000004100000410000000071712147471124014031 0ustar www-datawww-datarequire 'rubygems' require 'rake' require 'echoe' Echoe.new('jwt', '0.1.8') do |p| p.description = "JSON Web Token implementation in Ruby" p.url = "http://github.com/progrium/ruby-jwt" p.author = "Jeff Lindsay" p.email = "progrium@gmail.com" p.ignore_pattern = ["tmp/*"] p.runtime_dependencies = ["multi_json >=1.5"] p.development_dependencies = ["echoe >=4.6.3"] end task :test do sh "rspec spec/jwt_spec.rb" end jwt-0.1.8/spec/0000755000004100000410000000000012147471124013311 5ustar www-datawww-datajwt-0.1.8/spec/jwt_spec.rb0000644000004100000410000001221512147471124015455 0ustar www-datawww-datarequire 'helper' describe JWT do before do @payload = {"foo" => "bar"} end it "encodes and decodes JWTs" do secret = "secret" jwt = JWT.encode(@payload, secret) decoded_payload = JWT.decode(jwt, secret) decoded_payload.should == @payload end it "encodes and decodes JWTs for RSA signatures" do private_key = OpenSSL::PKey::RSA.generate(512) jwt = JWT.encode(@payload, private_key, "RS256") decoded_payload = JWT.decode(jwt, private_key.public_key) decoded_payload.should == @payload end it "encodes and decodes JWTs with custom header fields" do private_key = OpenSSL::PKey::RSA.generate(512) jwt = JWT.encode(@payload, private_key, "RS256", {"kid" => 'default'}) decoded_payload = JWT.decode(jwt) do |header| header["kid"].should == 'default' private_key.public_key end decoded_payload.should == @payload end it "decodes valid JWTs" do example_payload = {"hello" => "world"} example_secret = 'secret' example_jwt = 'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8' decoded_payload = JWT.decode(example_jwt, example_secret) decoded_payload.should == example_payload end it "raises exception when the token is invalid" do example_secret = 'secret' # Same as above exmaple with some random bytes replaced example_jwt = 'eyJhbGciOiAiSFMyNTYiLCAidHiMomlwIjogIkJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8' lambda { JWT.decode(example_jwt, example_secret) }.should raise_error(JWT::DecodeError) end it "raises exception with wrong hmac key" do right_secret = 'foo' bad_secret = 'bar' jwt_message = JWT.encode(@payload, right_secret, "HS256") lambda { JWT.decode(jwt_message, bad_secret) }.should raise_error(JWT::DecodeError) end it "raises exception with wrong rsa key" do right_private_key = OpenSSL::PKey::RSA.generate(512) bad_private_key = OpenSSL::PKey::RSA.generate(512) jwt = JWT.encode(@payload, right_private_key, "RS256") lambda { JWT.decode(jwt, bad_private_key.public_key) }.should raise_error(JWT::DecodeError) end it "allows decoding without key" do right_secret = 'foo' bad_secret = 'bar' jwt = JWT.encode(@payload, right_secret) decoded_payload = JWT.decode(jwt, bad_secret, false) decoded_payload.should == @payload end it "checks the key when verify is truthy" do right_secret = 'foo' bad_secret = 'bar' jwt = JWT.encode(@payload, right_secret) verify = "yes" =~ /^y/i lambda { JWT.decode(jwt, bad_secret, verify) }.should raise_error(JWT::DecodeError) end it "raises exception on unsupported crypto algorithm" do lambda { JWT.encode(@payload, "secret", 'HS1024') }.should raise_error(NotImplementedError) end it "encodes and decodes plaintext JWTs" do jwt = JWT.encode(@payload, nil, nil) jwt.split('.').length.should == 2 decoded_payload = JWT.decode(jwt, nil, nil) decoded_payload.should == @payload end it "does not use == to compare digests" do secret = "secret" jwt = JWT.encode(@payload, secret) crypto_segment = jwt.split(".").last signature = JWT.base64url_decode(crypto_segment) signature.should_not_receive('==') JWT.should_receive(:base64url_decode).with(crypto_segment).once.and_return(signature) JWT.should_receive(:base64url_decode).any_number_of_times.and_call_original JWT.decode(jwt, secret) end describe "secure comparison" do it "returns true if strings are equal" do expect(JWT.secure_compare("Foo", "Foo")).to be_true end it "returns false if either input is nil or empty" do [nil, ""].each do |bad| expect(JWT.secure_compare(bad, "Foo")).to be_false expect(JWT.secure_compare("Foo", bad)).to be_false end end it "retuns falise of the strings are different" do expect(JWT.secure_compare("Foo", "Bar")).to be_false end end it "raise exception on invalid signature" do pubkey = OpenSSL::PKey::RSA.new(<<-PUBKEY) -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxCaY7425h964bjaoLeUm SlZ8sK7VtVk9zHbGmZh2ygGYwfuUf2bmMye2Ofv99yDE/rd4loVIAcu7RVvDRgHq 3/CZTnIrSvHsiJQsHBNa3d+F1ihPfzURzf1M5k7CFReBj2SBXhDXd57oRfBQj12w CVhhwP6kGTAWuoppbIIIBfNF2lE/Nvm7lVVYQqL9xOrP/AQ4xRbpQlB8Ll9sO9Or SvbWhCDa/LMOWxHdmrcJi6XoSg1vnOyCoKbyAoauTt/XqdkHbkDdQ6HFbJieu9il LDZZNliPhfENuKeC2MCGVXTEu8Cqhy1w6e4axavLlXoYf4laJIZ/e7au8SqDbY0B xwIDAQAB -----END PUBLIC KEY----- PUBKEY jwt = ( 'eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiY' + 'XVkIjoiMTA2MDM1Nzg5MTY4OC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSI' + 'sImNpZCI6IjEwNjAzNTc4OTE2ODguYXBwcy5nb29nbGV1c2VyY29udGVudC5jb' + '20iLCJpZCI6IjExNjQ1MjgyNDMwOTg1Njc4MjE2MyIsInRva2VuX2hhc2giOiJ' + '0Z2hEOUo4bjhWME4ydmN3NmVNaWpnIiwiaWF0IjoxMzIwNjcwOTc4LCJleHAiO' + 'jEzMjA2NzQ4Nzh9.D8x_wirkxDElqKdJBcsIws3Ogesk38okz6MN7zqC7nEAA7' + 'wcy1PxsROY1fmBvXSer0IQesAqOW-rPOCNReSn-eY8d53ph1x2HAF-AzEi3GOl' + '6hFycH8wj7Su6JqqyEbIVLxE7q7DkAZGaMPkxbTHs1EhSd5_oaKQ6O4xO3ZnnT4' ) lambda { JWT.decode(jwt, pubkey, true) }.should raise_error(JWT::DecodeError) end end jwt-0.1.8/spec/helper.rb0000644000004100000410000000013712147471124015116 0ustar www-datawww-datarequire 'rspec' require "#{File.dirname(__FILE__)}/../lib/jwt.rb" RSpec.configure do |c| end jwt-0.1.8/jwt.gemspec0000644000004100000410000000241012147471124014525 0ustar www-datawww-data# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "jwt" s.version = "0.1.8" s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version= s.authors = ["Jeff Lindsay"] s.date = "2013-03-14" s.description = "JSON Web Token implementation in Ruby" s.email = "progrium@gmail.com" s.extra_rdoc_files = ["lib/jwt.rb"] s.files = ["Rakefile", "lib/jwt.rb", "spec/helper.rb", "spec/jwt_spec.rb", "Manifest", "jwt.gemspec"] s.homepage = "http://github.com/progrium/ruby-jwt" s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Jwt", "--main", "README.md"] s.require_paths = ["lib"] s.rubyforge_project = "jwt" s.rubygems_version = "1.8.23" s.summary = "JSON Web Token implementation in Ruby" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q, [">= 1.5"]) s.add_development_dependency(%q, [">= 4.6.3"]) else s.add_dependency(%q, [">= 1.5"]) s.add_dependency(%q, [">= 4.6.3"]) end else s.add_dependency(%q, [">= 1.5"]) s.add_dependency(%q, [">= 4.6.3"]) end end jwt-0.1.8/Manifest0000644000004100000410000000007512147471124014052 0ustar www-datawww-dataRakefile lib/jwt.rb spec/helper.rb spec/jwt_spec.rb Manifest jwt-0.1.8/metadata.yml0000644000004100000410000000360612147471124014667 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: jwt version: !ruby/object:Gem::Version version: 0.1.8 prerelease: platform: ruby authors: - Jeff Lindsay autorequire: bindir: bin cert_chain: [] date: 2013-03-14 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: multi_json requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '1.5' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '1.5' - !ruby/object:Gem::Dependency name: echoe requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 4.6.3 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 4.6.3 description: JSON Web Token implementation in Ruby email: progrium@gmail.com executables: [] extensions: [] extra_rdoc_files: - lib/jwt.rb files: - Rakefile - lib/jwt.rb - spec/helper.rb - spec/jwt_spec.rb - Manifest - jwt.gemspec homepage: http://github.com/progrium/ruby-jwt licenses: [] post_install_message: rdoc_options: - --line-numbers - --inline-source - --title - Jwt - --main - README.md require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '1.2' requirements: [] rubyforge_project: jwt rubygems_version: 1.8.23 signing_key: specification_version: 3 summary: JSON Web Token implementation in Ruby test_files: [] jwt-0.1.8/lib/0000755000004100000410000000000012147471124013125 5ustar www-datawww-datajwt-0.1.8/lib/jwt.rb0000644000004100000410000000667112147471124014270 0ustar www-datawww-data# # JSON Web Token implementation # # Should be up to date with the latest spec: # http://self-issued.info/docs/draft-jones-json-web-token-06.html require "base64" require "openssl" require "multi_json" module JWT class DecodeError < StandardError; end def self.sign(algorithm, msg, key) if ["HS256", "HS384", "HS512"].include?(algorithm) sign_hmac(algorithm, msg, key) elsif ["RS256", "RS384", "RS512"].include?(algorithm) sign_rsa(algorithm, msg, key) else raise NotImplementedError.new("Unsupported signing method") end end def self.sign_rsa(algorithm, msg, private_key) private_key.sign(OpenSSL::Digest::Digest.new(algorithm.sub('RS', 'sha')), msg) end def self.verify_rsa(algorithm, public_key, signing_input, signature) public_key.verify(OpenSSL::Digest::Digest.new(algorithm.sub('RS', 'sha')), signature, signing_input) end def self.sign_hmac(algorithm, msg, key) OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new(algorithm.sub('HS', 'sha')), key, msg) end def self.base64url_decode(str) str += '=' * (4 - str.length.modulo(4)) Base64.decode64(str.gsub("-", "+").gsub("_", "/")) end def self.base64url_encode(str) Base64.encode64(str).gsub("+", "-").gsub("/", "_").gsub("\n", "").gsub('=', '') end def self.encode(payload, key, algorithm='HS256', header_fields={}) algorithm ||= "none" segments = [] header = {"typ" => "JWT", "alg" => algorithm}.merge(header_fields) segments << base64url_encode(MultiJson.encode(header)) segments << base64url_encode(MultiJson.encode(payload)) signing_input = segments.join('.') if algorithm != "none" signature = sign(algorithm, signing_input, key) segments << base64url_encode(signature) else segments << "" end segments.join('.') end def self.decode(jwt, key=nil, verify=true, &keyfinder) segments = jwt.split('.') raise JWT::DecodeError.new("Not enough or too many segments") unless [2,3].include? segments.length header_segment, payload_segment, crypto_segment = segments signing_input = [header_segment, payload_segment].join('.') begin header = MultiJson.decode(base64url_decode(header_segment)) payload = MultiJson.decode(base64url_decode(payload_segment)) signature = base64url_decode(crypto_segment) if verify rescue MultiJson::LoadError => e raise JWT::DecodeError.new("Invalid segment encoding") end if verify algo = header['alg'] if keyfinder key = keyfinder.call(header) end begin if ["HS256", "HS384", "HS512"].include?(algo) raise JWT::DecodeError.new("Signature verification failed") unless secure_compare(signature, sign_hmac(algo, signing_input, key)) elsif ["RS256", "RS384", "RS512"].include?(algo) raise JWT::DecodeError.new("Signature verification failed") unless verify_rsa(algo, key, signing_input, signature) else raise JWT::DecodeError.new("Algorithm not supported") end rescue OpenSSL::PKey::PKeyError raise JWT::DecodeError.new("Signature verification failed") end end payload end # From devise # constant-time comparison algorithm to prevent timing attacks def self.secure_compare(a, b) return false if a.nil? || b.nil? || a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end end