Skip to content

Instantly share code, notes, and snippets.

@yujingz
Created August 16, 2019 05:29
Show Gist options
  • Save yujingz/1ef4b559e917b9636ccd269341c56d25 to your computer and use it in GitHub Desktop.
Save yujingz/1ef4b559e917b9636ccd269341c56d25 to your computer and use it in GitHub Desktop.
Aliyun MTS API Signature Computation Ruby Version
def get_signature(params = {}, accessKeySecrt = '')
canonicalizedQueryString = ''
params.keys.sort.each do |key|
return if (params[key].nil?)
canonicalizedQueryString +=
'&' + URI.encode_www_form_component(key) + '=' +
URI.encode_www_form_component(params[key])
end
canonicalizedQueryString = canonicalizedQueryString[1..-1]
string_to_sign =
'GET' + '&' + URI.encode_www_form_component('/') + '&' +
URI.encode_www_form_component(canonicalizedQueryString)
return hmac_sha1(string_to_sign, accessKeySecrt)
end
def hmac_sha1(signature, key)
require 'base64'
require 'cgi'
require 'openssl'
raw = Base64.encode64(OpenSSL::HMAC.digest('sha1', key, signature).to_s)
CGI.escape(raw.strip)
end
# Testing Params From Official Document
# https://www.alibabacloud.com/help/zh/doc-detail/29217.htm?spm=a2c63.l28256.b99.76.738e76f5DfVxP8
test_params = {
"AccessKeyId": 'testId',
"Action": 'SearchTemplate',
"Version": '2014-06-18',
"PageSize": '2',
"Timestamp": '2015-05-14T09:03:45Z',
"SignatureMethod": 'HMAC-SHA1',
"SignatureVersion": '1.0',
"SignatureNonce": '4902260a-516a-4b6a-a455-45b653cf6150',
"Format": 'XML'
}
accessKeySecret = 'testKeySecret&'
puts get_signature(test_params, accessKeySecret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment