Class: JWT::JWA::Hmac

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

Overview

Implementation of the HMAC family of algorithms

Defined Under Namespace

Modules: SecurityUtils

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) ⇒ Hmac

Returns a new instance of Hmac.



13
14
15
16
# File 'lib/jwt/jwa/hmac.rb', line 13

def initialize(alg, digest)
  @alg = alg
  @digest = digest
end

Class Method Details

.from_algorithm(algorithm) ⇒ Object



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

def self.from_algorithm(algorithm)
  new(algorithm, OpenSSL::Digest.new(algorithm.downcase.gsub('hs', 'sha')))
end

Instance Method Details

#sign(data:, signing_key:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/jwt/jwa/hmac.rb', line 18

def sign(data:, signing_key:)
  signing_key ||= ''
  raise_verify_error!('HMAC key expected to be a String') unless signing_key.is_a?(String)

  OpenSSL::HMAC.digest(digest.new, signing_key, data)
rescue OpenSSL::HMACError => e
  raise_verify_error!('OpenSSL 3.0 does not support nil or empty hmac_secret') if signing_key == '' && e.message == 'EVP_PKEY_new_mac_key: malloc failure'

  raise e
end

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



29
30
31
# File 'lib/jwt/jwa/hmac.rb', line 29

def verify(data:, signature:, verification_key:)
  SecurityUtils.secure_compare(signature, sign(data: data, signing_key: verification_key))
end