Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. function getSignatureKey(key, date, region, service) {
  2. const kDate = AWS.util.crypto.hmac('AWS4' + key, date, 'buffer');
  3. const kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
  4. const kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
  5. const kCredentials = AWS.util.crypto.hmac(kService, 'aws4_request', 'buffer');
  6. return kCredentials;
  7. }
  8.  
  9. function getSignedUrl(host, region, credentials) {
  10. const datetime = AWS.util.date.iso8601(new Date()).replace(/[:\-]|\.\d{3}/g, '');
  11. const date = datetime.substr(0, 8);
  12.  
  13. // date is in format of YYYYMMDD - for example 20190605
  14. console.log('date', date);
  15.  
  16. const method = 'GET';
  17. const protocol = 'wss';
  18. const uri = '/mqtt';
  19. const service = 'iotdevicegateway';
  20. const algorithm = 'AWS4-HMAC-SHA256';
  21.  
  22. let credentialScope = date + '/' + region + '/' + service + '/' + 'aws4_request';
  23. let canonicalQuerystring = 'X-Amz-Algorithm=' + algorithm;
  24. canonicalQuerystring += '&X-Amz-Credential=' + encodeURIComponent(credentials.accessKeyId + '/' + credentialScope);
  25. canonicalQuerystring += '&X-Amz-Date=' + datetime;
  26. canonicalQuerystring += '&X-Amz-SignedHeaders=host';
  27.  
  28. const canonicalHeaders = 'host:' + host + '\n';
  29. const payloadHash = AWS.util.crypto.sha256('', 'hex');
  30. const canonicalRequest = method + '\n' + uri + '\n' + canonicalQuerystring + '\n' + canonicalHeaders + '\nhost\n' + payloadHash;
  31.  
  32. const stringToSign = algorithm + '\n' + datetime + '\n' + credentialScope + '\n' + AWS.util.crypto.sha256(canonicalRequest, 'hex');
  33. const signingKey = getSignatureKey(credentials.secretAccessKey, date, region, service);
  34. const signature = AWS.util.crypto.hmac(signingKey, stringToSign, 'hex');
  35.  
  36. canonicalQuerystring += '&X-Amz-Signature=' + signature;
  37. if (credentials.sessionToken) {
  38. canonicalQuerystring += '&X-Amz-Security-Token=' + encodeURIComponent(credentials.sessionToken);
  39. }
  40.  
  41. const requestUrl = protocol + '://' + host + uri + '?' + canonicalQuerystring;
  42. return requestUrl;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement