forked from jwt/ruby-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hmac.rb
34 lines (31 loc) · 1.09 KB
/
hmac.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
module JWT
module Algos
module Hmac
module_function
SUPPORTED = %w[HS256 HS512256 HS384 HS512].freeze
def sign(to_sign)
algorithm, msg, key = to_sign.values
key ||= ''
authenticator, padded_key = SecurityUtils.rbnacl_fixup(algorithm, key)
if authenticator && padded_key
authenticator.auth(padded_key, msg.encode('binary'))
else
OpenSSL::HMAC.digest(OpenSSL::Digest.new(algorithm.sub('HS', 'sha')), key, msg)
end
end
def verify(to_verify)
algorithm, public_key, signing_input, signature = to_verify.values
authenticator, padded_key = SecurityUtils.rbnacl_fixup(algorithm, public_key)
if authenticator && padded_key
begin
authenticator.verify(padded_key, signature.encode('binary'), signing_input.encode('binary'))
rescue RbNaCl::BadAuthenticatorError
false
end
else
SecurityUtils.secure_compare(signature, sign(JWT::Signature::ToSign.new(algorithm, signing_input, public_key)))
end
end
end
end
end