Class: AftershipAPI::SignString
- Inherits:
-
Object
- Object
- AftershipAPI::SignString
- Defined in:
- lib/aftership-tracking-sdk/sign_string.rb
Class Method Summary collapse
Class Method Details
.sign(params) ⇒ Object
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/aftership-tracking-sdk/sign_string.rb', line 10 def sign(params) content_md5 = '' content_type = '' # Computed MD5 hash of the request body in uppercase hex format. if params['body'].to_s != '' content_md5 = Digest::MD5.hexdigest(params['body']).upcase content_type = params['content_type'] end # Extract all request headers with the as- prefix key as_headers = params['headers'].select { |k, _| k.start_with?('as-') } # Convert all the request header key to lowercase, sort the headers in ASCII code order as_headers = as_headers.transform_keys(&:downcase).sort.to_h # Remove leading spaces and trailing spaces from the header key and value as_headers.transform_keys!(&:strip) as_headers.transform_values!(&:strip) # Concatenate each of the header key and value with :, to form a header pair header_pairs = as_headers.map { |k, v| "#{k}:#{v}" } # Concatenate all header pairs with the new line character (ASCII code 10) canonicalized_headers = header_pairs.join("\n") # canonicalized_resource is the path of the URL, including the query parameters url = URI.parse params['url'] canonicalized_resource = url.path if !params['query'].nil? && params['query'].length > 0 sorted_query = params['query'].sort_by { |k, v| [k, v] } canonicalized_resource += '?' + URI.encode_www_form(sorted_query) end # Form the string to sign string_to_sign = [ params['method'].upcase, content_md5, content_type, params['date'], canonicalized_headers, canonicalized_resource ].join("\n") # Generate the signature signature = '' if params['auth_type'] == AUTHENTICATION_TYPE_AES signature = sign_aes(string_to_sign, params['secret']) elsif params['auth_type'] == AUTHENTICATION_TYPE_RSA signature = sign_rsa(string_to_sign, params['secret']) else raise InvalidOptionError, "Invalid authentication type: #{params['auth_type']}" end signature end |
.sign_aes(msg, key) ⇒ Object
65 66 67 68 |
# File 'lib/aftership-tracking-sdk/sign_string.rb', line 65 def sign_aes(msg, key) digest = OpenSSL::HMAC.digest("SHA256", key, msg) Base64.strict_encode64(digest).strip end |
.sign_rsa(msg, key) ⇒ Object
70 71 72 73 74 |
# File 'lib/aftership-tracking-sdk/sign_string.rb', line 70 def sign_rsa(msg, key) private_key = OpenSSL::PKey::RSA.new(key) signature = private_key.sign_pss('SHA256', msg, salt_length: :digest, mgf1_hash: 'SHA256') Base64.strict_encode64(signature).strip end |