Class: JWT::JWA::Ecdsa

Inherits:
Object
  • Object
show all
Includes:
SigningAlgorithm
Defined in:
lib/jwt/jwa/ecdsa.rb

Constant Summary collapse

NAMED_CURVES =
{
  'prime256v1' => {
    algorithm: 'ES256',
    digest: 'sha256'
  },
  'secp256r1' => { # alias for prime256v1
    algorithm: 'ES256',
    digest: 'sha256'
  },
  'secp384r1' => {
    algorithm: 'ES384',
    digest: 'sha384'
  },
  'secp521r1' => {
    algorithm: 'ES512',
    digest: 'sha512'
  },
  'secp256k1' => {
    algorithm: 'ES256K',
    digest: 'sha256'
  }
}.freeze

Instance Attribute Summary

Attributes included from SigningAlgorithm

#alg

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SigningAlgorithm

#header, included, #raise_sign_error!, #raise_verify_error!, #valid_alg?

Constructor Details

#initialize(alg, digest) ⇒ Ecdsa

Returns a new instance of Ecdsa.



8
9
10
11
# File 'lib/jwt/jwa/ecdsa.rb', line 8

def initialize(alg, digest)
  @alg = alg
  @digest = OpenSSL::Digest.new(digest)
end

Class Method Details

.curve_by_name(name) ⇒ Object



66
67
68
69
70
# File 'lib/jwt/jwa/ecdsa.rb', line 66

def self.curve_by_name(name)
  NAMED_CURVES.fetch(name) do
    raise UnsupportedEcdsaCurve, "The ECDSA curve '#{name}' is not supported"
  end
end

.from_algorithm(algorithm) ⇒ Object



62
63
64
# File 'lib/jwt/jwa/ecdsa.rb', line 62

def self.from_algorithm(algorithm)
  new(algorithm, algorithm.downcase.gsub('es', 'sha'))
end

Instance Method Details

#sign(data:, signing_key:) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/jwt/jwa/ecdsa.rb', line 13

def sign(data:, signing_key:)
  curve_definition = curve_by_name(signing_key.group.curve_name)
  key_algorithm = curve_definition[:algorithm]
  if alg != key_algorithm
    raise IncorrectAlgorithm, "payload algorithm is #{alg} but #{key_algorithm} signing key was provided"
  end

  asn1_to_raw(signing_key.dsa_sign_asn1(digest.digest(data)), signing_key)
end

#verify(data:, signature:, verification_key:) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/jwt/jwa/ecdsa.rb', line 23

def verify(data:, signature:, verification_key:)
  curve_definition = curve_by_name(verification_key.group.curve_name)
  key_algorithm = curve_definition[:algorithm]
  if alg != key_algorithm
    raise IncorrectAlgorithm, "payload algorithm is #{alg} but #{key_algorithm} verification key was provided"
  end

  verification_key.dsa_verify_asn1(digest.digest(data), raw_to_asn1(signature, verification_key))
rescue OpenSSL::PKey::PKeyError
  raise JWT::VerificationError, 'Signature verification raised'
end