New test.
[mono.git] / mcs / class / Mono.Security / Mono.Security.Cryptography / CryptoConvert.cs
1 //
2 // CryptoConvert.cs - Crypto Convertion Routines
3 //
4 // Author:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //
7 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Globalization;
32 using System.Security.Cryptography;
33 using System.Text;
34
35 namespace Mono.Security.Cryptography {
36
37 #if INSIDE_CORLIB
38         internal
39 #else
40         public
41 #endif
42         sealed class CryptoConvert {
43
44                 private CryptoConvert () 
45                 {
46                 }
47
48                 static private int ToInt32LE (byte [] bytes, int offset)
49                 {
50                         return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
51                 }
52
53                 static private uint ToUInt32LE (byte [] bytes, int offset)
54                 {
55                         return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
56                 }
57
58                 static private byte [] GetBytesLE (int val)
59                 {
60                         return new byte [] { 
61                                 (byte) (val & 0xff), 
62                                 (byte) ((val >> 8) & 0xff), 
63                                 (byte) ((val >> 16) & 0xff), 
64                                 (byte) ((val >> 24) & 0xff)
65                         };
66                 }
67
68                 static private byte[] Trim (byte[] array) 
69                 {
70                         for (int i=0; i < array.Length; i++) {
71                                 if (array [i] != 0x00) {
72                                         byte[] result = new byte [array.Length - i];
73                                         Buffer.BlockCopy (array, i, result, 0, result.Length);
74                                         return result;
75                                 }
76                         }
77                         return null;
78                 }
79
80                 // convert the key from PRIVATEKEYBLOB to RSA
81                 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/Security/private_key_blobs.asp
82                 // e.g. SNK files, PVK files
83                 static public RSA FromCapiPrivateKeyBlob (byte[] blob) 
84                 {
85                         return FromCapiPrivateKeyBlob (blob, 0);
86                 }
87
88                 static public RSA FromCapiPrivateKeyBlob (byte[] blob, int offset) 
89                 {
90                         if (blob == null)
91                                 throw new ArgumentNullException ("blob");
92                         if (offset >= blob.Length)
93                                 throw new ArgumentException ("blob is too small.");
94
95                         try {
96                                 if ((blob [offset]   != 0x07) ||                                // PRIVATEKEYBLOB (0x07)
97                                     (blob [offset+1] != 0x02) ||                                // Version (0x02)
98                                     (blob [offset+2] != 0x00) ||                                // Reserved (word)
99                                     (blob [offset+3] != 0x00) ||
100                                     (ToUInt32LE (blob, offset+8) != 0x32415352))        // DWORD magic = RSA2
101                                         throw new CryptographicException ("Invalid blob header");
102                                 
103                                 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
104                                 // int algId = ToInt32LE (blob, offset+4);
105
106                                 // DWORD bitlen
107                                 int bitLen = ToInt32LE (blob, offset+12);
108
109                                 // DWORD public exponent
110                                 RSAParameters rsap = new RSAParameters ();
111                                 byte[] exp = new byte [4];
112                                 Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
113                                 Array.Reverse (exp);
114                                 rsap.Exponent = Trim (exp);
115                         
116                                 int pos = offset+20;
117                                 // BYTE modulus[rsapubkey.bitlen/8];
118                                 int byteLen = (bitLen >> 3);
119                                 rsap.Modulus = new byte [byteLen];
120                                 Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
121                                 Array.Reverse (rsap.Modulus);
122                                 pos += byteLen;
123
124                                 // BYTE prime1[rsapubkey.bitlen/16];
125                                 int byteHalfLen = (byteLen >> 1);
126                                 rsap.P = new byte [byteHalfLen];
127                                 Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen);
128                                 Array.Reverse (rsap.P);
129                                 pos += byteHalfLen;
130
131                                 // BYTE prime2[rsapubkey.bitlen/16];
132                                 rsap.Q = new byte [byteHalfLen];
133                                 Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen);
134                                 Array.Reverse (rsap.Q);
135                                 pos += byteHalfLen;
136
137                                 // BYTE exponent1[rsapubkey.bitlen/16];
138                                 rsap.DP = new byte [byteHalfLen];
139                                 Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen);
140                                 Array.Reverse (rsap.DP);
141                                 pos += byteHalfLen;
142
143                                 // BYTE exponent2[rsapubkey.bitlen/16];
144                                 rsap.DQ = new byte [byteHalfLen];
145                                 Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen);
146                                 Array.Reverse (rsap.DQ);
147                                 pos += byteHalfLen;
148
149                                 // BYTE coefficient[rsapubkey.bitlen/16];
150                                 rsap.InverseQ = new byte [byteHalfLen];
151                                 Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen);
152                                 Array.Reverse (rsap.InverseQ);
153                                 pos += byteHalfLen;
154
155                                 // ok, this is hackish but CryptoAPI support it so...
156                                 // note: only works because CRT is used by default
157                                 // http://bugzilla.ximian.com/show_bug.cgi?id=57941
158                                 rsap.D = new byte [byteLen]; // must be allocated
159                                 if (pos + byteLen + offset <= blob.Length) {
160                                         // BYTE privateExponent[rsapubkey.bitlen/8];
161                                         Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen);
162                                         Array.Reverse (rsap.D);
163                                 }
164
165                                 RSA rsa = null;
166                                 try {
167                                         rsa = RSA.Create ();
168                                         rsa.ImportParameters (rsap);
169                                 }
170                                 catch (CryptographicException) {
171                                         // this may cause problem when this code is run under
172                                         // the SYSTEM identity on Windows (e.g. ASP.NET). See
173                                         // http://bugzilla.ximian.com/show_bug.cgi?id=77559
174                                         CspParameters csp = new CspParameters ();
175                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
176                                         rsa = new RSACryptoServiceProvider (csp);
177                                         rsa.ImportParameters (rsap);
178                                 }
179                                 return rsa;
180                         }
181                         catch (Exception e) {
182                                 throw new CryptographicException ("Invalid blob.", e);
183                         }
184                 }
185
186                 static public byte[] ToCapiPrivateKeyBlob (RSA rsa) 
187                 {
188                         RSAParameters p = rsa.ExportParameters (true);
189                         int keyLength = p.Modulus.Length; // in bytes
190                         byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
191
192                         blob [0] = 0x07;        // Type - PRIVATEKEYBLOB (0x07)
193                         blob [1] = 0x02;        // Version - Always CUR_BLOB_VERSION (0x02)
194                         // [2], [3]             // RESERVED - Always 0
195                         blob [5] = 0x24;        // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
196                         blob [8] = 0x52;        // Magic - RSA2 (ASCII in hex)
197                         blob [9] = 0x53;
198                         blob [10] = 0x41;
199                         blob [11] = 0x32;
200
201                         byte[] bitlen = GetBytesLE (keyLength << 3);
202                         blob [12] = bitlen [0]; // bitlen
203                         blob [13] = bitlen [1]; 
204                         blob [14] = bitlen [2]; 
205                         blob [15] = bitlen [3];
206
207                         // public exponent (DWORD)
208                         int pos = 16;
209                         int n = p.Exponent.Length;
210                         while (n > 0)
211                                 blob [pos++] = p.Exponent [--n];
212                         // modulus
213                         pos = 20;
214                         byte[] part = p.Modulus;
215                         int len = part.Length;
216                         Array.Reverse (part, 0, len);
217                         Buffer.BlockCopy (part, 0, blob, pos, len);
218                         pos += len;
219                         // private key
220                         part = p.P;
221                         len = part.Length;
222                         Array.Reverse (part, 0, len);
223                         Buffer.BlockCopy (part, 0, blob, pos, len);
224                         pos += len;
225
226                         part = p.Q;
227                         len = part.Length;
228                         Array.Reverse (part, 0, len);
229                         Buffer.BlockCopy (part, 0, blob, pos, len);
230                         pos += len;
231
232                         part = p.DP;
233                         len = part.Length;
234                         Array.Reverse (part, 0, len);
235                         Buffer.BlockCopy (part, 0, blob, pos, len);
236                         pos += len;
237
238                         part = p.DQ;
239                         len = part.Length;
240                         Array.Reverse (part, 0, len);
241                         Buffer.BlockCopy (part, 0, blob, pos, len);
242                         pos += len;
243
244                         part = p.InverseQ;
245                         len = part.Length;
246                         Array.Reverse (part, 0, len);
247                         Buffer.BlockCopy (part, 0, blob, pos, len);
248                         pos += len;
249
250                         part = p.D;
251                         len = part.Length;
252                         Array.Reverse (part, 0, len);
253                         Buffer.BlockCopy (part, 0, blob, pos, len);
254
255                         return blob;
256                 }
257
258                 static public RSA FromCapiPublicKeyBlob (byte[] blob) 
259                 {
260                         return FromCapiPublicKeyBlob (blob, 0);
261                 }
262
263                 static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset) 
264                 {
265                         if (blob == null)
266                                 throw new ArgumentNullException ("blob");
267                         if (offset >= blob.Length)
268                                 throw new ArgumentException ("blob is too small.");
269
270                         try {
271                                 if ((blob [offset]   != 0x06) ||                                // PUBLICKEYBLOB (0x06)
272                                     (blob [offset+1] != 0x02) ||                                // Version (0x02)
273                                     (blob [offset+2] != 0x00) ||                                // Reserved (word)
274                                     (blob [offset+3] != 0x00) || 
275                                     (ToUInt32LE (blob, offset+8) != 0x31415352))        // DWORD magic = RSA1
276                                         throw new CryptographicException ("Invalid blob header");
277
278                                 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
279                                 // int algId = ToInt32LE (blob, offset+4);
280
281                                 // DWORD bitlen
282                                 int bitLen = ToInt32LE (blob, offset+12);
283
284                                 // DWORD public exponent
285                                 RSAParameters rsap = new RSAParameters ();
286                                 rsap.Exponent = new byte [3];
287                                 rsap.Exponent [0] = blob [offset+18];
288                                 rsap.Exponent [1] = blob [offset+17];
289                                 rsap.Exponent [2] = blob [offset+16];
290                         
291                                 int pos = offset+20;
292                                 // BYTE modulus[rsapubkey.bitlen/8];
293                                 int byteLen = (bitLen >> 3);
294                                 rsap.Modulus = new byte [byteLen];
295                                 Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
296                                 Array.Reverse (rsap.Modulus);
297
298                                 RSA rsa = null;
299                                 try {
300                                         rsa = RSA.Create ();
301                                         rsa.ImportParameters (rsap);
302                                 }
303                                 catch (CryptographicException) {
304                                         // this may cause problem when this code is run under
305                                         // the SYSTEM identity on Windows (e.g. ASP.NET). See
306                                         // http://bugzilla.ximian.com/show_bug.cgi?id=77559
307                                         CspParameters csp = new CspParameters ();
308                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
309                                         rsa = new RSACryptoServiceProvider (csp);
310                                         rsa.ImportParameters (rsap);
311                                 }
312                                 return rsa;
313                         }
314                         catch (Exception e) {
315                                 throw new CryptographicException ("Invalid blob.", e);
316                         }
317                 }
318
319                 static public byte[] ToCapiPublicKeyBlob (RSA rsa) 
320                 {
321                         RSAParameters p = rsa.ExportParameters (false);
322                         int keyLength = p.Modulus.Length; // in bytes
323                         byte[] blob = new byte [20 + keyLength];
324
325                         blob [0] = 0x06;        // Type - PUBLICKEYBLOB (0x06)
326                         blob [1] = 0x02;        // Version - Always CUR_BLOB_VERSION (0x02)
327                         // [2], [3]             // RESERVED - Always 0
328                         blob [5] = 0x24;        // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
329                         blob [8] = 0x52;        // Magic - RSA1 (ASCII in hex)
330                         blob [9] = 0x53;
331                         blob [10] = 0x41;
332                         blob [11] = 0x31;
333
334                         byte[] bitlen = GetBytesLE (keyLength << 3);
335                         blob [12] = bitlen [0]; // bitlen
336                         blob [13] = bitlen [1]; 
337                         blob [14] = bitlen [2]; 
338                         blob [15] = bitlen [3];
339
340                         // public exponent (DWORD)
341                         int pos = 16;
342                         int n = p.Exponent.Length;
343                         while (n > 0)
344                                 blob [pos++] = p.Exponent [--n];
345                         // modulus
346                         pos = 20;
347                         byte[] part = p.Modulus;
348                         int len = part.Length;
349                         Array.Reverse (part, 0, len);
350                         Buffer.BlockCopy (part, 0, blob, pos, len);
351                         pos += len;
352                         return blob;
353                 }
354
355                 // PRIVATEKEYBLOB
356                 // PUBLICKEYBLOB
357                 static public RSA FromCapiKeyBlob (byte[] blob) 
358                 {
359                         return FromCapiKeyBlob (blob, 0);
360                 }
361
362                 static public RSA FromCapiKeyBlob (byte[] blob, int offset) 
363                 {
364                         if (blob == null)
365                                 throw new ArgumentNullException ("blob");
366                         if (offset >= blob.Length)
367                                 throw new ArgumentException ("blob is too small.");
368
369                         switch (blob [offset]) {
370                                 case 0x00:
371                                         // this could be a public key inside an header
372                                         // like "sn -e" would produce
373                                         if (blob [offset + 12] == 0x06) {
374                                                 return FromCapiPublicKeyBlob (blob, offset + 12);
375                                         }
376                                         break;
377                                 case 0x06:
378                                         return FromCapiPublicKeyBlob (blob, offset);
379                                 case 0x07:
380                                         return FromCapiPrivateKeyBlob (blob, offset);
381                         }
382                         throw new CryptographicException ("Unknown blob format.");
383                 }
384
385                 static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey) 
386                 {
387                         if (keypair == null)
388                                 throw new ArgumentNullException ("keypair");
389
390                         // check between RSA and DSA (and potentially others like DH)
391                         if (keypair is RSA)
392                                 return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
393                         else
394                                 return null;    // TODO
395                 }
396
397                 static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey) 
398                 {
399                         if (rsa == null)
400                                 throw new ArgumentNullException ("rsa");
401
402                         if (includePrivateKey)
403                                 return ToCapiPrivateKeyBlob (rsa);
404                         else
405                                 return ToCapiPublicKeyBlob (rsa);
406                 }
407
408                 static public string ToHex (byte[] input) 
409                 {
410                         if (input == null)
411                                 return null;
412
413                         StringBuilder sb = new StringBuilder (input.Length * 2);
414                         foreach (byte b in input) {
415                                 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
416                         }
417                         return sb.ToString ();
418                 }
419
420                 static private byte FromHexChar (char c) 
421                 {
422                         if ((c >= 'a') && (c <= 'f'))
423                                 return (byte) (c - 'a' + 10);
424                         if ((c >= 'A') && (c <= 'F'))
425                                 return (byte) (c - 'A' + 10);
426                         if ((c >= '0') && (c <= '9'))
427                                 return (byte) (c - '0');
428                         throw new ArgumentException ("invalid hex char");
429                 }
430
431                 static public byte[] FromHex (string hex) 
432                 {
433                         if (hex == null)
434                                 return null;
435                         if ((hex.Length & 0x1) == 0x1)
436                                 throw new ArgumentException ("Length must be a multiple of 2");
437
438                         byte[] result = new byte [hex.Length >> 1];
439                         int n = 0;
440                         int i = 0;
441                         while (n < result.Length) {
442                                 result [n] = (byte) (FromHexChar (hex [i++]) << 4);
443                                 result [n++] += FromHexChar (hex [i++]);
444                         }
445                         return result;
446                 }
447         }
448 }