2011-10-03

C#, Compact .NET, WP7 SDK 7.1 & AWS EC2

That title sounds like the beginning of some ancient joke. Well, it's anything but ancient! I just wanted to post some quick code on how to sign AWS EC2 query requests using Compact .NET in C#.

Since there is no high level API for AWS for the compact version of .NET (ie. when used for the WP7 SDK), your best bet is to make query requests directly. That also means you need to sign your requests yourself. Since I was unable to find a working example, I turned to an old piece of code and ported that to work with the compact version of .NET / WP7 SDK 7.1 (Mango) instead.



There weren't too many gotchas, really. Just had to get rid of a SortedDictionary and use LINQ instead, and make some minor modifications to the code thanks to the differences of the two AWS services.
I left the Amazon copyright comments intact, let me dump the entire SignedRequestHelper.cs file here:

1
2
3
4
5
6
7
8
9
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/**********************************************************************************************
 * Copyright 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
 * except in compliance with the License. A copy of the License is located at
 *
 *
 * or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under the License.
 *
 * ********************************************************************************************
 *
 *  Signed Requests Sample Code
 *
 *  API Version: 2009-03-31
 *
 */
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Security.Cryptography;
using System.Linq;
 
namespace AmazonWPSignatureApi
{
    class SignedRequestHelper
    {
        private string endPoint;
        private string akid;
        private byte[] secret;
        private HMAC signer;
 
        private const string REQUEST_URI = "/";
        private const string REQUEST_METHOD = "GET";
        private const string REQUEST_VERSION = "2011-07-15";
        private const string REQUEST_SIGNATUREVERSION = "2";
        private const string REQUEST_SIGNATUREMETHOD = "HmacSHA256";
 
 
        /*
         * Use this constructor to create the object. Endpoints (destinations) are available on
         */
        public SignedRequestHelper(string awsAccessKeyId, string awsSecretKey, string destination)
        {
            this.endPoint = destination.ToLower();
            this.akid = awsAccessKeyId;
            this.secret = Encoding.UTF8.GetBytes(awsSecretKey);
            this.signer = new HMACSHA256(this.secret);
        }
 
        /*
         * Sign a request in the form of a Dictionary of name-value pairs.
         *
         * This method returns a complete URL to use. Modifying the returned URL
         * in any way invalidates the signature and Amazon will reject the requests.
         */
        public string Sign(IDictionary< string, string=""> request)
        {
            // Add the AWSAccessKeyId and Timestamp to the requests.
            request.Add("Version", REQUEST_VERSION);
            request.Add("SignatureVersion", REQUEST_SIGNATUREVERSION);
            request.Add("SignatureMethod", REQUEST_SIGNATUREMETHOD);
            request.Add("Timestamp", this.GetTimestamp()); // perhaps Expires?
 
            // sort the dictionary
            var sortedMap = (from entry in request orderby entry.Key ascending select entry).ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value);
 
            // Get the canonical query string
            string canonicalQS = this.ConstructCanonicalQueryString(sortedMap);
 
            // Derive the bytes needs to be signed.
            StringBuilder builder = new StringBuilder();
            builder.Append(REQUEST_METHOD)
                .Append("\n")
                .Append(this.endPoint)
                .Append("\n")
                .Append(REQUEST_URI)
                .Append("\n")
                .Append("AWSAccessKeyId=")
                .Append(this.akid)
                .Append("&amp;")
                .Append(canonicalQS);
 
            string stringToSign = builder.ToString();
            byte[] toSign = Encoding.UTF8.GetBytes(stringToSign);
 
            // Compute the signature and convert to Base64.
            byte[] sigBytes = signer.ComputeHash(toSign);
            string signature = Convert.ToBase64String(sigBytes);
             
            // now construct the complete URL and return to caller.
            StringBuilder qsBuilder = new StringBuilder();
            qsBuilder.Append("http://")
                .Append(this.endPoint)
                .Append(REQUEST_URI)
                .Append("?")
                .Append("AWSAccessKeyId=")
                .Append(this.akid)
                .Append("&amp;")
                .Append(canonicalQS)
                .Append("&amp;Signature=")
                .Append(this.PercentEncodeRfc3986(signature));
 
            return qsBuilder.ToString();
        }
 
        /*
         * Sign a request in the form of a query string.
         *
         * This method returns a complete URL to use. Modifying the returned URL
         * in any way invalidates the signature and Amazon will reject the requests.
         */
        public string Sign(string queryString)
        {
            IDictionary<string, string=""> request = this.CreateDictionary(queryString);
            return this.Sign(request);
        }
 
        /*
         * Current time in IS0 8601 format as required by Amazon
         */
        private string GetTimestamp()
        {
            DateTime currentTime = DateTime.UtcNow;
            string timestamp = currentTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
            return timestamp;
        }
 
        /*
         * Percent-encode (URL Encode) according to RFC 3986 as required by Amazon.
         *
         * This is necessary because .NET's HttpUtility.UrlEncode does not encode
         * according to the above standard. Also, .NET returns lower-case encoding
         * by default and Amazon requires upper-case encoding.
         */
        private string PercentEncodeRfc3986(string str)
        {
            str = HttpUtility.UrlEncode(str);
            str = str.Replace("'", "%27").Replace("(", "%28").Replace(")", "%29").Replace("*", "%2A").Replace("!", "%21").Replace("%7e", "~").Replace("+", "%20");
 
            StringBuilder sbuilder = new StringBuilder(str);
            for (int i = 0; i &lt; sbuilder.Length; i++)
            {
                if (sbuilder[i] == '%')
                {
                    if (Char.IsLetter(sbuilder[i + 1]) || Char.IsLetter(sbuilder[i + 2]))
                    {
                        sbuilder[i + 1] = Char.ToUpper(sbuilder[i + 1]);
                        sbuilder[i + 2] = Char.ToUpper(sbuilder[i + 2]);
                    }
                }
            }
            return sbuilder.ToString();
        }
 
        /*
         * Convert a query string to corresponding dictionary of name-value pairs.
         */
        private IDictionary<string, string=""> CreateDictionary(string queryString)
        {
            Dictionary<string, string=""> map = new Dictionary<string, string="">();
 
            string[] requestParams = queryString.Split('&amp;');
 
            for (int i = 0; i &lt; requestParams.Length; i++)
            {
                if (requestParams[i].Length &lt; 1)
                {
                    continue;
                }
 
                char[] sep = { '=' };
                string[] param = requestParams[i].Split(sep);
                for (int j = 0; j &lt; param.Length; j++)
                {
                    param[j] = HttpUtility.UrlDecode(param[j]);
                }
                switch (param.Length)
                {
                    case 1:
                        {
                            if (requestParams[i].Length &gt;= 1)
                            {
                                if (requestParams[i].ToCharArray()[0] == '=')
                                {
                                    map[""] = param[0];
                                }
                                else
                                {
                                    map[param[0]] = "";
                                }
                            }
                            break;
                        }
                    case 2:
                        {
                            if (!string.IsNullOrEmpty(param[0]))
                            {
                                map[param[0]] = param[1];
                            }
                        }
                        break;
                }
            }
 
            return map;
        }
 
        /*
         * Consttuct the canonical query string from the sorted parameter map.
         */
        private string ConstructCanonicalQueryString(Dictionary<string, string=""> sortedParamMap)
        {
            StringBuilder builder = new StringBuilder();
 
            if (sortedParamMap.Count == 0)
            {
                builder.Append("");
                return builder.ToString();
            }
 
            foreach (KeyValuePair<string, string=""> kvp in sortedParamMap)
            {
                builder.Append(this.PercentEncodeRfc3986(kvp.Key));
                builder.Append("=");
                builder.Append(this.PercentEncodeRfc3986(kvp.Value));
                builder.Append("&amp;");
            }
            string canonicalString = builder.ToString();
            canonicalString = canonicalString.Substring(0, canonicalString.Length - 1);
            return canonicalString;
        }
    }
 
}

To make use of this, define these constants in your class:
1
2
3
private const string MY_AWS_ACCESS_KEY_ID = "<INSERT AWS ACCESS KEY ID HERE>";
private const string MY_AWS_SECRET_KEY = "<INSERT AWS SECRET ACCESS KEY HERE>";
private const string DESTINATION = "ec2.amazonaws.com";

Check out the Making Query Requests page to refine your DESTINATION or leave it like that to default to us-east-1. Then do something like this:
1
2
SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION);
String requestUrl = helper.Sign("Action=DescribeInstances");

Parameters such as AWSAccessKeyID, Version, Timestamp, SignatureMethod and SignatureVersion are automatically added along with of course the signature itself, so you only need to worry about your action and its relevant parameters. Find a list of actions here.

No comments:

Post a Comment