Class: Moneta::Transforms::HMAC

Inherits:
Moneta::Transform show all
Defined in:
lib/moneta/transforms/hmac.rb

Overview

Prepends an HMAC digest to the string. This requires a secret to be provided.

You may wish to additionally encode the combined string using Base64, Hex, etc.

Instance Method Summary collapse

Methods inherited from Moneta::Transform

#decodable?, delegate_to, #method_missing, #respond_to_missing?

Constructor Details

#initialize(secret:, algorithm: "sha256", **options) ⇒ HMAC

Returns a new instance of HMAC.

Parameters:

  • secret (String)
  • algorithm (String) (defaults to: "sha256")

    Any algorithm understood by OpenSSL::Digest can be used



11
12
13
14
15
16
# File 'lib/moneta/transforms/hmac.rb', line 11

def initialize(secret:, algorithm: "sha256", **options)
  super

  @digest = OpenSSL::Digest.new(algorithm)
  @secret = secret
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Moneta::Transform

Instance Method Details

#decode(value) ⇒ String

Verifies the digest and returns the original string if valid

Parameters:

  • value (String)

Returns:

  • (String)


40
41
42
43
# File 'lib/moneta/transforms/hmac.rb', line 40

def decode(value)
  raise "value does not have correct HMAC" unless encoded? value
  value.byteslice(@digest.digest_length..-1)
end

#encode(value) ⇒ String

Hashes the value using HMAC, and returns the hash plus the original string concatenated

Parameters:

  • value (String)

Returns:

  • (String)

    HMAC followed by the original string



22
23
24
# File 'lib/moneta/transforms/hmac.rb', line 22

def encode(value)
  OpenSSL::HMAC.digest(@digest, @secret, value) << value
end

#encoded?(value) ⇒ Boolean

Verifies the digest at the start of the string using the secret

Parameters:

  • value (String)

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/moneta/transforms/hmac.rb', line 30

def encoded?(value)
  hash = value.byteslice(0, @digest.digest_length)
  rest = value.byteslice(@digest.digest_length..-1)
  hash == OpenSSL::HMAC.digest(@digest, @secret, rest)
end