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

Constant Summary collapse

MIN_KEY_LENGTHS =

Minimum key lengths for HMAC algorithms based on RFC 7518 Section 3.2. Keys must be at least the size of the hash output to ensure sufficient entropy for the algorithm’s security level.

{
  'HS256' => 32,
  'HS384' => 48,
  'HS512' => 64
}.freeze

Instance Attribute Summary

Attributes included from SigningAlgorithm

#alg

Instance Method Summary collapse

Methods included from SigningAlgorithm

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

Constructor Details

#initialize(alg, digest) ⇒ Hmac

Returns a new instance of Hmac.



18
19
20
21
# File 'lib/jwt/jwa/hmac.rb', line 18

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

Instance Method Details

#sign(data:, signing_key:) ⇒ Object



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

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

  validate_key_length!(signing_key)

  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



36
37
38
39
40
41
42
43
# File 'lib/jwt/jwa/hmac.rb', line 36

def verify(data:, signature:, verification_key:)
  validation_key = verification_key || ''
  raise_verify_error!('HMAC key expected to be a String') unless validation_key.is_a?(String)

  validate_key_length!(validation_key)

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