Class: Mac
- Inherits:
-
Object
- Object
- Mac
- Defined in:
- lib/mac.rb
Overview
Provides methods to sign and verify timestamped messages with HMAC SHA256.
Instance Attribute Summary collapse
-
#signature ⇒ Object
readonly
Returns the value of attribute signature.
-
#timestamp ⇒ Object
readonly
Returns the value of attribute timestamp.
Class Method Summary collapse
-
.sign(message:, secret:, timed: true, hexdigest: true) ⇒ Object
Sets up a message and calculates its current signature.
Instance Method Summary collapse
-
#initialize(message:, secret:, timed: true) ⇒ Mac
constructor
Sets up a message to be signed/verified with a secret.
-
#sign(timestamp: nil, hexdigest: true) ⇒ Object
Calculates the signature of the message.
-
#signed?(signature:, timestamp: nil, hexdigest: true) ⇒ Boolean
Returns whether the provided signature and timestamp match the signature of the message.
Constructor Details
#initialize(message:, secret:, timed: true) ⇒ Mac
Sets up a message to be signed/verified with a secret.
4 5 6 7 8 |
# File 'lib/mac.rb', line 4 def initialize(message:, secret:, timed: true) @message = @secret = secret @timed = timed end |
Instance Attribute Details
#signature ⇒ Object (readonly)
Returns the value of attribute signature.
17 18 19 |
# File 'lib/mac.rb', line 17 def signature @signature end |
#timestamp ⇒ Object (readonly)
Returns the value of attribute timestamp.
17 18 19 |
# File 'lib/mac.rb', line 17 def @timestamp end |
Class Method Details
.sign(message:, secret:, timed: true, hexdigest: true) ⇒ Object
Sets up a message and calculates its current signature.
11 12 13 14 15 |
# File 'lib/mac.rb', line 11 def self.sign(message:, secret:, timed: true, hexdigest: true) new(message: , secret: secret).tap do |mac| mac.sign timestamp: (Time.now if timed), hexdigest: hexdigest end end |
Instance Method Details
#sign(timestamp: nil, hexdigest: true) ⇒ Object
Calculates the signature of the message.
26 27 28 29 30 31 32 33 34 |
# File 'lib/mac.rb', line 26 def sign(timestamp: nil, hexdigest: true) @timestamp = .to_i.to_s if payload = [@timestamp, @message].compact.join '.' @signature = if hexdigest OpenSSL::HMAC.hexdigest 'SHA256', @secret, payload else Base64.strict_encode64(OpenSSL::HMAC.digest 'SHA256', @secret, payload) end end |
#signed?(signature:, timestamp: nil, hexdigest: true) ⇒ Boolean
Returns whether the provided signature and timestamp match the signature of the message.
20 21 22 23 |
# File 'lib/mac.rb', line 20 def signed?(signature:, timestamp: nil, hexdigest: true) sign hexdigest: hexdigest, timestamp: Rack::Utils.secure_compare @signature, signature end |