Skip to content

Commit

Permalink
implement HS512 as instance of Hmac
Browse files Browse the repository at this point in the history
  • Loading branch information
MatteoPierro committed Aug 17, 2024
1 parent 8761f3e commit d32e9d1
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
43 changes: 40 additions & 3 deletions lib/jwt/jwa/hmac.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,54 @@

module JWT
module JWA
module Hmac
class Hmac
include JWT::JWA::SignatureAlgorithm

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

register_algorithm(*DIGEST_MAPPING.keys)

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

def valid_alg?(alg_to_check)
alg&.casecmp(alg_to_check)&.zero? == true
end

def sign(data:, signing_key:)
signing_key ||= ''

raise JWT::DecodeError, '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 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

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

def header(*)
{ 'alg' => alg }
end

HS512 = Hmac.new('HS512', OpenSSL::Digest::SHA512)
::JWT::JWA.register_algorithm_v2(HS512, 'HS512')

private

attr_reader :alg, :digest

class << self
def sign(algorithm, msg, key)
key ||= ''
Expand Down
6 changes: 6 additions & 0 deletions lib/jwt/jwa/signature_algorithm.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ def register_algorithm(klass, *algos)
end
end

def register_algorithm_v2(klass, *algos)
algos.each do |algo|
algorithms[algo.to_s.downcase] = klass
end
end

def find(algo)
algorithms[algo.to_s.downcase]
end
Expand Down

0 comments on commit d32e9d1

Please sign in to comment.