Class: Moneta::Transforms::HMAC
- Inherits:
-
Moneta::Transform
- Object
- Moneta::Transform
- Moneta::Transforms::HMAC
- Defined in:
- lib/moneta/transforms/hmac.rb
Overview
Instance Method Summary collapse
-
#decode(value) ⇒ String
Verifies the digest and returns the original string if valid.
-
#encode(value) ⇒ String
Hashes the
value
using HMAC, and returns the hash plus the original string concatenated. -
#encoded?(value) ⇒ Boolean
Verifies the digest at the start of the string using the secret.
-
#initialize(secret:, algorithm: "sha256", **options) ⇒ HMAC
constructor
A new instance of HMAC.
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.
11 12 13 14 15 16 |
# File 'lib/moneta/transforms/hmac.rb', line 11 def initialize(secret:, algorithm: "sha256", **) 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
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
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
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 |