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