Module: Transbank::Onepay::Utils::SignatureUtils

Included in:
Request, Response
Defined in:
lib/transbank/sdk/onepay/utils/signature_utils.rb

Overview

Utils for creating signatures, included on classes that need to be signed

Instance Method Summary collapse

Instance Method Details

#hmac_sha256(data, secret) ⇒ String

Digest data and secret, creating a hashed string

Parameters:

  • data (String)

    a string created from the signable, created using #to_data

  • secret (String)

    the string to hash the data with.

Returns:

  • (String)

    the result of the hashing of data with secret.



25
26
27
# File 'lib/transbank/sdk/onepay/utils/signature_utils.rb', line 25

def hmac_sha256(data, secret)
  OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), secret, data)
end

#signature_for(data, secret) ⇒ String

Return the base64 of the hmac_sha256’d data & secret

Parameters:

  • data (String)

    a string created from the signable, created using #to_data

  • secret (String)

    the string to hash the data with.

Returns:

  • (String)

    Base64 representation of the hmac_sha256 hashing of data & secret



33
34
35
# File 'lib/transbank/sdk/onepay/utils/signature_utils.rb', line 33

def signature_for(data, secret)
  Base64.encode64(hmac_sha256(data, secret)).strip
end

#to_dataObject

Transform the instance of the class that calls this method into a string in the format required for the signature, using the params defined in the class’ SIGNATURE_PARAMS array constant

Raises:

  • (RuntimeError)

    if self.class::SIGNATURE_PARAMS is nil or empty



10
11
12
13
14
15
16
17
18
19
# File 'lib/transbank/sdk/onepay/utils/signature_utils.rb', line 10

def to_data
  if self.class::SIGNATURE_PARAMS.nil? || self.class::SIGNATURE_PARAMS.empty?
    raise RuntimeError, 'SIGNATURE_PARAMS is empty or nil!'
  end
  self.class::SIGNATURE_PARAMS.reduce('') do |data_string, current_value|
    value_of_getter = send(current_value)
    # Integer#digits is ruby 2.4 upwards :(
    data_string + value_of_getter.to_s.length.to_s + value_of_getter.to_s
  end
end

#valid_signature?(secret) ⇒ boolean

Compare the @signature of self with the one recreated from self using the secret param. Return true if equal

Parameters:

  • secret (String)

    the secret used to create the signature with.

Returns:

  • (boolean)

    return true if signatures match, false otherwise



41
42
43
44
45
# File 'lib/transbank/sdk/onepay/utils/signature_utils.rb', line 41

def valid_signature?(secret)
  # We should be able to recreate the same signature from the signable's data
  # and the secret
  self.signature == signature_for(self.to_data, secret)
end