Class: Sandal::Sig::HS

Inherits:
Object
  • Object
show all
Defined in:
lib/sandal/sig/hs.rb

Overview

Base implementation of the HMAC-SHA family of signature algorithms.

Direct Known Subclasses

HS256, HS384, HS512

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, sha_size, key) ⇒ HS

Creates a new instance; it’s probably easier to use one of the subclass constructors.

Parameters:

  • sha_size (Integer)

    The size of the SHA algorithm.

  • key (String)

    The key to use for signing or validation.



18
19
20
21
22
# File 'lib/sandal/sig/hs.rb', line 18

def initialize(name, sha_size, key)
  @name = name
  @digest = OpenSSL::Digest.new("sha#{sha_size}")
  @key = key
end

Instance Attribute Details

#nameObject (readonly)

The JWA name of the algorithm.



10
11
12
# File 'lib/sandal/sig/hs.rb', line 10

def name
  @name
end

Instance Method Details

#sign(payload) ⇒ String

Signs a payload and returns the signature.

Parameters:

  • payload (String)

    The payload of the token to sign.

Returns:

  • (String)

    The signature.



28
29
30
# File 'lib/sandal/sig/hs.rb', line 28

def sign(payload)
  OpenSSL::HMAC.digest(@digest, @key, payload)
end

#valid?(signature, payload) ⇒ Boolean

Validates a payload signature and returns whether the signature matches.

Parameters:

  • signature (String)

    The signature to validate.

  • payload (String)

    The payload of the token.

Returns:

  • (Boolean)

    true if the signature is correct; otherwise false.



37
38
39
# File 'lib/sandal/sig/hs.rb', line 37

def valid?(signature, payload)
  Sandal::Util.jwt_strings_equal?(sign(payload), signature)
end