class JWT::JWA::Hmac

Attributes

digest[R]

Public Class Methods

from_algorithm(algorithm) click to toggle source
# File lib/jwt/jwa/hmac.rb, line 8
def self.from_algorithm(algorithm)
  new(algorithm, OpenSSL::Digest.new(algorithm.downcase.gsub('hs', 'sha')))
end
new(alg, digest) click to toggle source
# File lib/jwt/jwa/hmac.rb, line 12
def initialize(alg, digest)
  @alg = alg
  @digest = digest
end

Public Instance Methods

sign(data:, signing_key:) click to toggle source
# File lib/jwt/jwa/hmac.rb, line 17
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
  if signing_key == '' && e.message == 'EVP_PKEY_new_mac_key: malloc failure'
    raise_verify_error!('OpenSSL 3.0 does not support nil or empty hmac_secret')
  end

  raise e
end
verify(data:, signature:, verification_key:) click to toggle source
# File lib/jwt/jwa/hmac.rb, line 30
def verify(data:, signature:, verification_key:)
  SecurityUtils.secure_compare(signature, sign(data: data, signing_key: verification_key))
end