~ubuntu-branches/ubuntu/trusty/ruby-jwt/trusty-proposed

« back to all changes in this revision

Viewing changes to lib/jwt.rb

  • Committer: Package Import Robot
  • Author(s): Markus Tornow
  • Date: 2013-10-08 23:42:19 UTC
  • mto: This revision was merged to the branch mainline in revision 3.
  • Revision ID: package-import@ubuntu.com-20131008234219-dxm6ufbuifed0836
Tags: upstream-0.1.8
ImportĀ upstreamĀ versionĀ 0.1.8

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
require "multi_json"
10
10
 
11
11
module JWT
12
 
  class DecodeError < Exception; end
 
12
  class DecodeError < StandardError; end
13
13
 
14
14
  def self.sign(algorithm, msg, key)
15
15
    if ["HS256", "HS384", "HS512"].include?(algorithm)
67
67
      header = MultiJson.decode(base64url_decode(header_segment))
68
68
      payload = MultiJson.decode(base64url_decode(payload_segment))
69
69
      signature = base64url_decode(crypto_segment) if verify
70
 
    rescue JSON::ParserError
 
70
    rescue MultiJson::LoadError => e
71
71
      raise JWT::DecodeError.new("Invalid segment encoding")
72
72
    end
73
 
    if verify == true
 
73
    if verify
74
74
      algo = header['alg']
75
75
 
76
76
      if keyfinder
79
79
 
80
80
      begin
81
81
        if ["HS256", "HS384", "HS512"].include?(algo)
82
 
          raise JWT::DecodeError.new("Signature verification failed") unless signature == sign_hmac(algo, signing_input, key)
 
82
          raise JWT::DecodeError.new("Signature verification failed") unless secure_compare(signature, sign_hmac(algo, signing_input, key))
83
83
        elsif ["RS256", "RS384", "RS512"].include?(algo)
84
84
          raise JWT::DecodeError.new("Signature verification failed") unless verify_rsa(algo, key, signing_input, signature)
85
85
        else
92
92
    payload
93
93
  end
94
94
 
 
95
  # From devise
 
96
  # constant-time comparison algorithm to prevent timing attacks
 
97
  def self.secure_compare(a, b)
 
98
    return false if a.nil? || b.nil? || a.empty? || b.empty? || a.bytesize != b.bytesize
 
99
    l = a.unpack "C#{a.bytesize}"
 
100
 
 
101
    res = 0
 
102
    b.each_byte { |byte| res |= byte ^ l.shift }
 
103
    res == 0
 
104
  end
 
105
 
95
106
end