File: util.rb

package info (click to toggle)
ruby-telesign 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 104 kB
  • sloc: ruby: 254; makefile: 4
file content (39 lines) | stat: -rw-r--r-- 1,229 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'base64'
require 'openssl'
require 'securerandom'

module Telesign
  class Util

    def self.random_with_n_digits(n)
      n.times.map { SecureRandom.random_number(10) }.join
    end

    # Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature.
    #
    # * +api_key+ - the TeleSign API api_key associated with your account.
    # * +signature+ - the TeleSign Authorization header value supplied in the callback, as a string.
    # * +json_str+ - the POST body text, that is, the JSON string sent by TeleSign describing the transaction status.
    def verify_telesign_callback_signature(api_key, signature, json_str)

      digest = OpenSSL::Digest.new('sha256')
      key = Base64.decode64(api_key)

      your_signature = Base64.encode64(OpenSSL::HMAC.digest(digest, key, json_str)).strip

      unless signature.length == your_signature.length
        return false
      end

      # avoid timing attack with constant time equality check
      signatures_equal = true
      signature.split('').zip(your_signature.split('')).each do |x, y|
        unless x == y
          signatures_equal = false
        end
      end

      signatures_equal
    end
  end
end