· 7 years ago · Jul 10, 2018, 11:12 AM
1public partial class VehicleClusteringActivity
2 {
3 const string RegionName = "ap-southeast-1"; //This is the regionName
4 const string ServiceName = "es";
5 const string Algorithm = "AWS4-HMAC-SHA256";
6 const string ContentType = "application/x-www-form-urlencoded";
7 const string Host = "search-armissearch-3vqxybdiyqasnrhwiqpigyvvxa.ap-southeast-1.es.amazonaws.com";
8 const string SignedHeaders = "content-length;content-type;host;x-amz-date";
9
10
11 public static WebRequest RequestPost(string canonicalUri, string canonicalQueriString, string jsonString)
12 {
13 string hashedRequestPayload = CreateRequestPayload(jsonString);
14
15 string authorization = Sign(hashedRequestPayload, "POST", canonicalUri, canonicalQueriString);
16 string requestDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + "Z";
17
18 WebRequest webRequest = WebRequest.Create("https://" + Host + canonicalUri);
19
20 webRequest.Timeout = 20000;
21 webRequest.Method = "POST";
22
23 webRequest.ContentType = ContentType;
24 webRequest.Headers.Add("X-Amz-date", requestDate);
25 webRequest.Headers.Add("Authorization", authorization);
26 webRequest.Headers.Add("x-amz-content-sha256", hashedRequestPayload);
27 webRequest.ContentLength = jsonString.Length;
28 webRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
29
30 ASCIIEncoding encoding = new ASCIIEncoding();
31 byte[] data = encoding.GetBytes(jsonString);
32
33 Stream newStream = webRequest.GetRequestStream();
34 newStream.Write(data, 0, data.Length);
35
36
37 return webRequest;
38 }
39
40 private static string CreateRequestPayload(string jsonString)
41 {
42 //Here should be JSON object of the model we are sending with POST request
43 //var jsonToSerialize = new { Data = String.Empty };
44
45 //We parse empty string to the serializer if we are makeing GET request
46 //string requestPayload = new JavaScriptSerializer().Serialize(jsonToSerialize);
47 string hashedRequestPayload = HexEncode(Hash(ToBytes(jsonString)));
48
49 return hashedRequestPayload;
50 }
51
52 private static string Sign(string hashedRequestPayload, string requestMethod, string canonicalUri, string canonicalQueryString)
53 {
54 var currentDateTime = DateTime.UtcNow;
55 var accessKey = "***********"; //Here place your app ACCESS_KEY
56 var secretKey = "*************"; //Here is a place for you app SECRET_KEY
57
58 var dateStamp = currentDateTime.ToString("yyyyMMdd");
59 var requestDate = currentDateTime.ToString("yyyyMMddTHHmmss") + "Z";
60 var credentialScope = string.Format("{0}/{1}/{2}/aws4_request", dateStamp, RegionName, ServiceName);
61
62 var headers = new SortedDictionary<string, string> {
63 { "content-type", ContentType },
64 { "host", Host },
65 { "x-amz-date", requestDate }
66 };
67
68 string canonicalHeaders = string.Join("n", headers.Select(x => x.Key.ToLowerInvariant() + ":" + x.Value.Trim())) + "n";
69
70 // Task 1: Create a Canonical Request For Signature Version 4
71 string canonicalRequest = requestMethod + "n" + canonicalUri + "n" + canonicalQueryString + "n" + canonicalHeaders + "n" + SignedHeaders + "n" + hashedRequestPayload;
72 string hashedCanonicalRequest = HexEncode(Hash(ToBytes(canonicalRequest)));
73
74 // Task 2: Create a String to Sign for Signature Version 4
75 string stringToSign = Algorithm + "n" + requestDate + "n" + credentialScope + "n" + hashedCanonicalRequest;
76
77 // Task 3: Calculate the AWS Signature Version 4
78 byte[] signingKey = GetSignatureKey(secretKey, dateStamp, RegionName, ServiceName);
79 string signature = HexEncode(HmacSha256(stringToSign, signingKey));
80
81 // Task 4: Prepare a signed request
82 // Authorization: algorithm Credential=access key ID/credential scope, SignedHeadaers=SignedHeaders, Signature=signature
83
84 // string authorization = string.Format("{0} Credential={1}/{2}/{3}/{4}/aws4_request, SignedHeaders={5}, Signature={6}",
85 // Algorithm, accessKey, dateStamp, RegionName, ServiceName, SignedHeaders, signature);
86
87 string authorization = "AWS4-HMAC-SHA256 Credential=AKIAIIPBK3IMTEWNIMVA/20180706/ap-southeast-1/es/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=0253634c37993e9d39132eb743244e2082c66e9dabe97c6bc8f473f7aac9d3af";
88 return authorization;
89 }
90
91 private static byte[] GetSignatureKey(string key, string dateStamp, string regionName, string serviceName)
92 {
93 byte[] kDate = HmacSha256(dateStamp, ToBytes("AWS4" + key));
94 byte[] kRegion = HmacSha256(regionName, kDate);
95 byte[] kService = HmacSha256(serviceName, kRegion);
96 return HmacSha256("aws4_request", kService);
97 }
98
99 private static byte[] ToBytes(string str)
100 {
101 return Encoding.UTF8.GetBytes(str.ToCharArray());
102 }
103
104 private static string HexEncode(byte[] bytes)
105 {
106 return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
107 }
108
109 private static byte[] Hash(byte[] bytes)
110 {
111 return SHA256.Create().ComputeHash(bytes);
112 }
113
114 private static byte[] HmacSha256(string data, byte[] key)
115 {
116 return new HMACSHA256(key).ComputeHash(ToBytes(data));
117 }
118
119
120
121
122
123
124
125
126
127
128 }
129 }
130
131
132 }
133 }