Module: JsonWebToken::Algorithm::Hmac

Extended by:
Common
Defined in:
lib/json_web_token/algorithm/hmac.rb

Overview

Sign or verify a JSON Web Signature (JWS) structure using HMAC with SHA-2 algorithms

Constant Summary

Constants included from Common

Common::SHA_BITS

Class Method Summary collapse

Methods included from Common

digest_new, validate_key, validate_sha_bits

Class Method Details

.sign(sha_bits, shared_key, signing_input) ⇒ BinaryString

Returns a digital signature, or mac.

Examples:

shared_key = "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C"
Hmac.sign('256', shared_key, 'signing_input').bytes
# => [90, 34, 44, 252, 147, 130, 167, 173, 86, 191, 247, 93, 94, 12, 200, 30, 173, 115, 248, 89, 246, 222, 4, 213, 119, 74, 70, 20, 231, 194, 104, 103]

Parameters:

  • sha_bits (String)

    size of the hash output

  • shared_key (String)

    secret key used to sign and verify a digital signature, or mac

  • signing_input (String)

    input payload for a mac computation

Returns:

  • (BinaryString)

    a digital signature, or mac



22
23
24
25
# File 'lib/json_web_token/algorithm/hmac.rb', line 22

def sign(sha_bits, shared_key, signing_input)
  validate_key(sha_bits, shared_key)
  OpenSSL::HMAC.digest(digest_new(sha_bits), shared_key, signing_input)
end

.verify?(mac, sha_bits, shared_key, signing_input) ⇒ Boolean

Returns a predicate to verify the signing_input by comparing a given mac to the mac for a newly signed message; comparison done in a constant-time manner to thwart timing attacks.

Examples:

shared_key = "gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C"
Hmac.verify?(< binary_string >, '256', shared_key, 'signing_input')
# => true

Parameters:

  • mac (BinaryString)

    a digital signature, or mac

  • sha_bits (String)

    size of the hash output

  • shared_key (String)

    secret key used to sign and verify a digital signature, or mac

  • signing_input (String)

    input payload for a mac computation

Returns:

  • (Boolean)

    a predicate to verify the signing_input by comparing a given mac to the mac for a newly signed message; comparison done in a constant-time manner to thwart timing attacks



36
37
38
# File 'lib/json_web_token/algorithm/hmac.rb', line 36

def verify?(mac, sha_bits, shared_key, signing_input)
  Util.constant_time_compare?(mac, sign(sha_bits, shared_key, signing_input))
end