Module: JWT::Signature

Extended by:
Signature
Included in:
Signature
Defined in:
lib/jwt/signature.rb

Overview

Signature logic for JWT

Constant Summary collapse

HMAC_ALGORITHMS =
%w[HS256 HS512256 HS384 HS512].freeze
RSA_ALGORITHMS =
%w[RS256 RS384 RS512].freeze
ECDSA_ALGORITHMS =
%w[ES256 ES384 ES512].freeze
NAMED_CURVES =
{
  'prime256v1' => 'ES256',
  'secp384r1' => 'ES384',
  'secp521r1' => 'ES512'
}.freeze

Instance Method Summary collapse

Instance Method Details

#sign(algorithm, msg, key) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/jwt/signature.rb', line 27

def sign(algorithm, msg, key)
  if HMAC_ALGORITHMS.include?(algorithm)
    sign_hmac(algorithm, msg, key)
  elsif RSA_ALGORITHMS.include?(algorithm)
    sign_rsa(algorithm, msg, key)
  elsif ECDSA_ALGORITHMS.include?(algorithm)
    sign_ecdsa(algorithm, msg, key)
  else
    raise NotImplementedError, 'Unsupported signing method'
  end
end

#verify(algo, key, signing_input, signature) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/jwt/signature.rb', line 39

def verify(algo, key, signing_input, signature)
  verified = if HMAC_ALGORITHMS.include?(algo)
    verify_hmac(algo, key, signing_input, signature)
  elsif RSA_ALGORITHMS.include?(algo)
    SecurityUtils.verify_rsa(algo, key, signing_input, signature)
  elsif ECDSA_ALGORITHMS.include?(algo)
    verify_ecdsa(algo, key, signing_input, signature)
  else
    raise JWT::VerificationError, 'Algorithm not supported'
  end

  raise(JWT::VerificationError, 'Signature verification raised') unless verified
rescue OpenSSL::PKey::PKeyError
  raise JWT::VerificationError, 'Signature verification raised'
ensure
  OpenSSL.errors.clear
end