Module: JWT::Algos::Hmac

Defined in:
lib/jwt/algos/hmac.rb

Defined Under Namespace

Modules: SecurityUtils

Constant Summary collapse

MAPPING =
{
  'HS256' => OpenSSL::Digest::SHA256,
  'HS384' => OpenSSL::Digest::SHA384,
  'HS512' => OpenSSL::Digest::SHA512
}.freeze
SUPPORTED =
MAPPING.keys

Class Method Summary collapse

Class Method Details

.sign(algorithm, msg, key) ⇒ Object



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

def sign(algorithm, msg, key)
  key ||= ''

  raise JWT::DecodeError, 'HMAC key expected to be a String' unless key.is_a?(String)

  OpenSSL::HMAC.digest(MAPPING[algorithm].new, key, msg)
rescue OpenSSL::HMACError => e
  if key == '' && e.message == 'EVP_PKEY_new_mac_key: malloc failure'
    raise JWT::DecodeError, 'OpenSSL 3.0 does not support nil or empty hmac_secret'
  end

  raise e
end

.verify(algorithm, key, signing_input, signature) ⇒ Object



30
31
32
# File 'lib/jwt/algos/hmac.rb', line 30

def verify(algorithm, key, signing_input, signature)
  SecurityUtils.secure_compare(signature, sign(algorithm, signing_input, key))
end