9a3ae26563340a5e5bda4d4d389524779e05ba13
[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                         RSAParameters rsap = new RSAParameters ();
96                         try {
97                                 if ((blob [offset]   != 0x07) ||                                // PRIVATEKEYBLOB (0x07)
98                                     (blob [offset+1] != 0x02) ||                                // Version (0x02)
99                                     (blob [offset+2] != 0x00) ||                                // Reserved (word)
100                                     (blob [offset+3] != 0x00) ||
101                                     (ToUInt32LE (blob, offset+8) != 0x32415352))        // DWORD magic = RSA2
102                                         throw new CryptographicException ("Invalid blob header");
103                                 
104                                 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
105                                 // int algId = ToInt32LE (blob, offset+4);
106
107                                 // DWORD bitlen
108                                 int bitLen = ToInt32LE (blob, offset+12);
109
110                                 // DWORD public exponent
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                         catch (Exception e) {
166                                 throw new CryptographicException ("Invalid blob.", e);
167                         }
168
169                         RSA rsa = null;
170                         try {
171                                 rsa = RSA.Create ();
172                                 rsa.ImportParameters (rsap);
173                         }
174                         catch (CryptographicException ce) {
175                                 // this may cause problem when this code is run under
176                                 // the SYSTEM identity on Windows (e.g. ASP.NET). See
177                                 // http://bugzilla.ximian.com/show_bug.cgi?id=77559
178                                 try {
179                                         CspParameters csp = new CspParameters ();
180                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
181                                         rsa = new RSACryptoServiceProvider (csp);
182                                         rsa.ImportParameters (rsap);
183                                 }
184                                 catch {
185                                         // rethrow original, not the later, exception if this fails
186                                         throw ce;
187                                 }
188                         }
189                         return rsa;
190                 }
191
192                 static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob)
193                 {
194                         return FromCapiPrivateKeyBlobDSA (blob, 0);
195                 }
196
197                 static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset)
198                 {
199                         if (blob == null)
200                                 throw new ArgumentNullException ("blob");
201                         if (offset >= blob.Length)
202                                 throw new ArgumentException ("blob is too small.");
203
204                         DSAParameters dsap = new DSAParameters ();
205                         try {
206                                 if ((blob [offset] != 0x07) ||                          // PRIVATEKEYBLOB (0x07)
207                                     (blob [offset + 1] != 0x02) ||                      // Version (0x02)
208                                     (blob [offset + 2] != 0x00) ||                      // Reserved (word)
209                                     (blob [offset + 3] != 0x00) ||
210                                     (ToUInt32LE (blob, offset + 8) != 0x32535344))      // DWORD magic
211                                         throw new CryptographicException ("Invalid blob header");
212
213                                 int bitlen = ToInt32LE (blob, offset + 12);
214                                 int bytelen = bitlen >> 3;
215                                 int pos = offset + 16;
216
217                                 dsap.P = new byte [bytelen];
218                                 Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
219                                 Array.Reverse (dsap.P);
220                                 pos += bytelen;
221
222                                 dsap.Q = new byte [20];
223                                 Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
224                                 Array.Reverse (dsap.Q);
225                                 pos += 20;
226
227                                 dsap.G = new byte [bytelen];
228                                 Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
229                                 Array.Reverse (dsap.G);
230                                 pos += bytelen;
231
232                                 dsap.X = new byte [20];
233                                 Buffer.BlockCopy (blob, pos, dsap.X, 0, 20);
234                                 Array.Reverse (dsap.X);
235                                 pos += 20;
236
237                                 dsap.Counter = ToInt32LE (blob, pos);
238                                 pos += 4;
239
240                                 dsap.Seed = new byte [20];
241                                 Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
242                                 Array.Reverse (dsap.Seed);
243                                 pos += 20;
244                         }
245                         catch (Exception e) {
246                                 throw new CryptographicException ("Invalid blob.", e);
247                         }
248
249                         DSA dsa = null;
250                         try {
251                                 dsa = (DSA)DSA.Create ();
252                                 dsa.ImportParameters (dsap);
253                         }
254                         catch (CryptographicException ce) {
255                                 // this may cause problem when this code is run under
256                                 // the SYSTEM identity on Windows (e.g. ASP.NET). See
257                                 // http://bugzilla.ximian.com/show_bug.cgi?id=77559
258                                 try {
259                                         CspParameters csp = new CspParameters ();
260                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
261                                         dsa = new DSACryptoServiceProvider (csp);
262                                         dsa.ImportParameters (dsap);
263                                 }
264                                 catch {
265                                         // rethrow original, not the later, exception if this fails
266                                         throw ce;
267                                 }
268                         }
269                         return dsa;
270                 }
271
272                 static public byte[] ToCapiPrivateKeyBlob (RSA rsa) 
273                 {
274                         RSAParameters p = rsa.ExportParameters (true);
275                         int keyLength = p.Modulus.Length; // in bytes
276                         byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
277
278                         blob [0] = 0x07;        // Type - PRIVATEKEYBLOB (0x07)
279                         blob [1] = 0x02;        // Version - Always CUR_BLOB_VERSION (0x02)
280                         // [2], [3]             // RESERVED - Always 0
281                         blob [5] = 0x24;        // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
282                         blob [8] = 0x52;        // Magic - RSA2 (ASCII in hex)
283                         blob [9] = 0x53;
284                         blob [10] = 0x41;
285                         blob [11] = 0x32;
286
287                         byte[] bitlen = GetBytesLE (keyLength << 3);
288                         blob [12] = bitlen [0]; // bitlen
289                         blob [13] = bitlen [1]; 
290                         blob [14] = bitlen [2]; 
291                         blob [15] = bitlen [3];
292
293                         // public exponent (DWORD)
294                         int pos = 16;
295                         int n = p.Exponent.Length;
296                         while (n > 0)
297                                 blob [pos++] = p.Exponent [--n];
298                         // modulus
299                         pos = 20;
300                         byte[] part = p.Modulus;
301                         int len = part.Length;
302                         Array.Reverse (part, 0, len);
303                         Buffer.BlockCopy (part, 0, blob, pos, len);
304                         pos += len;
305                         // private key
306                         part = p.P;
307                         len = part.Length;
308                         Array.Reverse (part, 0, len);
309                         Buffer.BlockCopy (part, 0, blob, pos, len);
310                         pos += len;
311
312                         part = p.Q;
313                         len = part.Length;
314                         Array.Reverse (part, 0, len);
315                         Buffer.BlockCopy (part, 0, blob, pos, len);
316                         pos += len;
317
318                         part = p.DP;
319                         len = part.Length;
320                         Array.Reverse (part, 0, len);
321                         Buffer.BlockCopy (part, 0, blob, pos, len);
322                         pos += len;
323
324                         part = p.DQ;
325                         len = part.Length;
326                         Array.Reverse (part, 0, len);
327                         Buffer.BlockCopy (part, 0, blob, pos, len);
328                         pos += len;
329
330                         part = p.InverseQ;
331                         len = part.Length;
332                         Array.Reverse (part, 0, len);
333                         Buffer.BlockCopy (part, 0, blob, pos, len);
334                         pos += len;
335
336                         part = p.D;
337                         len = part.Length;
338                         Array.Reverse (part, 0, len);
339                         Buffer.BlockCopy (part, 0, blob, pos, len);
340
341                         return blob;
342                 }
343
344                 static public byte[] ToCapiPrivateKeyBlob (DSA dsa)
345                 {
346                         DSAParameters p = dsa.ExportParameters (true);
347                         int keyLength = p.P.Length; // in bytes
348
349                         // header + P + Q + G + X + count + seed
350                         byte[] blob = new byte [16 + keyLength + 20 + keyLength + 20 + 4 + 20];
351
352                         blob [0] = 0x07;        // Type - PRIVATEKEYBLOB (0x07)
353                         blob [1] = 0x02;        // Version - Always CUR_BLOB_VERSION (0x02)
354                         // [2], [3]             // RESERVED - Always 0
355                         blob [5] = 0x22;        // ALGID
356                         blob [8] = 0x44;        // Magic
357                         blob [9] = 0x53;
358                         blob [10] = 0x53;
359                         blob [11] = 0x32;
360
361                         byte[] bitlen = GetBytesLE (keyLength << 3);
362                         blob [12] = bitlen [0];
363                         blob [13] = bitlen [1];
364                         blob [14] = bitlen [2];
365                         blob [15] = bitlen [3];
366
367                         int pos = 16;
368                         byte[] part = p.P;
369                         Array.Reverse (part);
370                         Buffer.BlockCopy (part, 0, blob, pos, keyLength);
371                         pos += keyLength;
372
373                         part = p.Q;
374                         Array.Reverse (part);
375                         Buffer.BlockCopy (part, 0, blob, pos, 20);
376                         pos += 20;
377
378                         part = p.G;
379                         Array.Reverse (part);
380                         Buffer.BlockCopy (part, 0, blob, pos, keyLength);
381                         pos += keyLength;
382
383                         part = p.X;
384                         Array.Reverse (part);
385                         Buffer.BlockCopy (part, 0, blob, pos, 20);
386                         pos += 20;
387
388                         Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
389                         pos += 4;
390
391                         part = p.Seed;
392                         Array.Reverse (part);
393                         Buffer.BlockCopy (part, 0, blob, pos, 20);
394
395                         return blob;
396                 }
397
398                 static public RSA FromCapiPublicKeyBlob (byte[] blob) 
399                 {
400                         return FromCapiPublicKeyBlob (blob, 0);
401                 }
402
403                 static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset) 
404                 {
405                         if (blob == null)
406                                 throw new ArgumentNullException ("blob");
407                         if (offset >= blob.Length)
408                                 throw new ArgumentException ("blob is too small.");
409
410                         try {
411                                 if ((blob [offset]   != 0x06) ||                                // PUBLICKEYBLOB (0x06)
412                                     (blob [offset+1] != 0x02) ||                                // Version (0x02)
413                                     (blob [offset+2] != 0x00) ||                                // Reserved (word)
414                                     (blob [offset+3] != 0x00) || 
415                                     (ToUInt32LE (blob, offset+8) != 0x31415352))        // DWORD magic = RSA1
416                                         throw new CryptographicException ("Invalid blob header");
417
418                                 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
419                                 // int algId = ToInt32LE (blob, offset+4);
420
421                                 // DWORD bitlen
422                                 int bitLen = ToInt32LE (blob, offset+12);
423
424                                 // DWORD public exponent
425                                 RSAParameters rsap = new RSAParameters ();
426                                 rsap.Exponent = new byte [3];
427                                 rsap.Exponent [0] = blob [offset+18];
428                                 rsap.Exponent [1] = blob [offset+17];
429                                 rsap.Exponent [2] = blob [offset+16];
430                         
431                                 int pos = offset+20;
432                                 // BYTE modulus[rsapubkey.bitlen/8];
433                                 int byteLen = (bitLen >> 3);
434                                 rsap.Modulus = new byte [byteLen];
435                                 Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
436                                 Array.Reverse (rsap.Modulus);
437
438                                 RSA rsa = null;
439                                 try {
440                                         rsa = RSA.Create ();
441                                         rsa.ImportParameters (rsap);
442                                 }
443                                 catch (CryptographicException) {
444                                         // this may cause problem when this code is run under
445                                         // the SYSTEM identity on Windows (e.g. ASP.NET). See
446                                         // http://bugzilla.ximian.com/show_bug.cgi?id=77559
447                                         CspParameters csp = new CspParameters ();
448                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
449                                         rsa = new RSACryptoServiceProvider (csp);
450                                         rsa.ImportParameters (rsap);
451                                 }
452                                 return rsa;
453                         }
454                         catch (Exception e) {
455                                 throw new CryptographicException ("Invalid blob.", e);
456                         }
457                 }
458
459                 static public DSA FromCapiPublicKeyBlobDSA (byte[] blob)
460                 {
461                         return FromCapiPublicKeyBlobDSA (blob, 0);
462                 }
463
464                 static public DSA FromCapiPublicKeyBlobDSA (byte[] blob, int offset)
465                 {
466                         if (blob == null)
467                                 throw new ArgumentNullException ("blob");
468                         if (offset >= blob.Length)
469                                 throw new ArgumentException ("blob is too small.");
470
471                         try {
472                                 if ((blob [offset] != 0x06) ||                          // PUBLICKEYBLOB (0x06)
473                                     (blob [offset + 1] != 0x02) ||                      // Version (0x02)
474                                     (blob [offset + 2] != 0x00) ||                      // Reserved (word)
475                                     (blob [offset + 3] != 0x00) ||
476                                     (ToUInt32LE (blob, offset + 8) != 0x31535344))      // DWORD magic
477                                         throw new CryptographicException ("Invalid blob header");
478
479                                 int bitlen = ToInt32LE (blob, offset + 12);
480                                 DSAParameters dsap = new DSAParameters ();
481                                 int bytelen = bitlen >> 3;
482                                 int pos = offset + 16;
483
484                                 dsap.P = new byte [bytelen];
485                                 Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
486                                 Array.Reverse (dsap.P);
487                                 pos += bytelen;
488
489                                 dsap.Q = new byte [20];
490                                 Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
491                                 Array.Reverse (dsap.Q);
492                                 pos += 20;
493
494                                 dsap.G = new byte [bytelen];
495                                 Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
496                                 Array.Reverse (dsap.G);
497                                 pos += bytelen;
498
499                                 dsap.Y = new byte [bytelen];
500                                 Buffer.BlockCopy (blob, pos, dsap.Y, 0, bytelen);
501                                 Array.Reverse (dsap.Y);
502                                 pos += bytelen;
503
504                                 dsap.Counter = ToInt32LE (blob, pos);
505                                 pos += 4;
506
507                                 dsap.Seed = new byte [20];
508                                 Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
509                                 Array.Reverse (dsap.Seed);
510                                 pos += 20;
511
512                                 DSA dsa = (DSA)DSA.Create ();
513                                 dsa.ImportParameters (dsap);
514                                 return dsa;
515                         }
516                         catch (Exception e) {
517                                 throw new CryptographicException ("Invalid blob.", e);
518                         }
519                 }
520
521                 static public byte[] ToCapiPublicKeyBlob (RSA rsa) 
522                 {
523                         RSAParameters p = rsa.ExportParameters (false);
524                         int keyLength = p.Modulus.Length; // in bytes
525                         byte[] blob = new byte [20 + keyLength];
526
527                         blob [0] = 0x06;        // Type - PUBLICKEYBLOB (0x06)
528                         blob [1] = 0x02;        // Version - Always CUR_BLOB_VERSION (0x02)
529                         // [2], [3]             // RESERVED - Always 0
530                         blob [5] = 0x24;        // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
531                         blob [8] = 0x52;        // Magic - RSA1 (ASCII in hex)
532                         blob [9] = 0x53;
533                         blob [10] = 0x41;
534                         blob [11] = 0x31;
535
536                         byte[] bitlen = GetBytesLE (keyLength << 3);
537                         blob [12] = bitlen [0]; // bitlen
538                         blob [13] = bitlen [1]; 
539                         blob [14] = bitlen [2]; 
540                         blob [15] = bitlen [3];
541
542                         // public exponent (DWORD)
543                         int pos = 16;
544                         int n = p.Exponent.Length;
545                         while (n > 0)
546                                 blob [pos++] = p.Exponent [--n];
547                         // modulus
548                         pos = 20;
549                         byte[] part = p.Modulus;
550                         int len = part.Length;
551                         Array.Reverse (part, 0, len);
552                         Buffer.BlockCopy (part, 0, blob, pos, len);
553                         pos += len;
554                         return blob;
555                 }
556
557                 static public byte[] ToCapiPublicKeyBlob (DSA dsa)
558                 {
559                         DSAParameters p = dsa.ExportParameters (false);
560                         int keyLength = p.P.Length; // in bytes
561
562                         // header + P + Q + G + Y + count + seed
563                         byte[] blob = new byte [16 + keyLength + 20 + keyLength + keyLength + 4 + 20];
564
565                         blob [0] = 0x06;        // Type - PUBLICKEYBLOB (0x06)
566                         blob [1] = 0x02;        // Version - Always CUR_BLOB_VERSION (0x02)
567                         // [2], [3]             // RESERVED - Always 0
568                         blob [5] = 0x22;        // ALGID
569                         blob [8] = 0x44;        // Magic
570                         blob [9] = 0x53;
571                         blob [10] = 0x53;
572                         blob [11] = 0x31;
573
574                         byte[] bitlen = GetBytesLE (keyLength << 3);
575                         blob [12] = bitlen [0];
576                         blob [13] = bitlen [1];
577                         blob [14] = bitlen [2];
578                         blob [15] = bitlen [3];
579
580                         int pos = 16;
581                         byte[] part;
582
583                         part = p.P;
584                         Array.Reverse (part);
585                         Buffer.BlockCopy (part, 0, blob, pos, keyLength);
586                         pos += keyLength;
587
588                         part = p.Q;
589                         Array.Reverse (part);
590                         Buffer.BlockCopy (part, 0, blob, pos, 20);
591                         pos += 20;
592
593                         part = p.G;
594                         Array.Reverse (part);
595                         Buffer.BlockCopy (part, 0, blob, pos, keyLength);
596                         pos += keyLength;
597
598                         part = p.Y;
599                         Array.Reverse (part);
600                         Buffer.BlockCopy (part, 0, blob, pos, keyLength);
601                         pos += keyLength;
602
603                         Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
604                         pos += 4;
605
606                         part = p.Seed;
607                         Array.Reverse (part);
608                         Buffer.BlockCopy (part, 0, blob, pos, 20);
609
610                         return blob;
611                 }
612
613                 // PRIVATEKEYBLOB
614                 // PUBLICKEYBLOB
615                 static public RSA FromCapiKeyBlob (byte[] blob) 
616                 {
617                         return FromCapiKeyBlob (blob, 0);
618                 }
619
620                 static public RSA FromCapiKeyBlob (byte[] blob, int offset) 
621                 {
622                         if (blob == null)
623                                 throw new ArgumentNullException ("blob");
624                         if (offset >= blob.Length)
625                                 throw new ArgumentException ("blob is too small.");
626
627                         switch (blob [offset]) {
628                                 case 0x00:
629                                         // this could be a public key inside an header
630                                         // like "sn -e" would produce
631                                         if (blob [offset + 12] == 0x06) {
632                                                 return FromCapiPublicKeyBlob (blob, offset + 12);
633                                         }
634                                         break;
635                                 case 0x06:
636                                         return FromCapiPublicKeyBlob (blob, offset);
637                                 case 0x07:
638                                         return FromCapiPrivateKeyBlob (blob, offset);
639                         }
640                         throw new CryptographicException ("Unknown blob format.");
641                 }
642
643                 static public DSA FromCapiKeyBlobDSA (byte[] blob)
644                 {
645                         return FromCapiKeyBlobDSA (blob, 0);
646                 }
647
648                 static public DSA FromCapiKeyBlobDSA (byte[] blob, int offset)
649                 {
650                         if (blob == null)
651                                 throw new ArgumentNullException ("blob");
652                         if (offset >= blob.Length)
653                                 throw new ArgumentException ("blob is too small.");
654
655                         switch (blob [offset]) {
656                                 case 0x06:
657                                         return FromCapiPublicKeyBlobDSA (blob, offset);
658                                 case 0x07:
659                                         return FromCapiPrivateKeyBlobDSA (blob, offset);
660                         }
661                         throw new CryptographicException ("Unknown blob format.");
662                 }
663
664                 static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey) 
665                 {
666                         if (keypair == null)
667                                 throw new ArgumentNullException ("keypair");
668
669                         // check between RSA and DSA (and potentially others like DH)
670                         if (keypair is RSA)
671                                 return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
672                         else if (keypair is DSA)
673                                 return ToCapiKeyBlob ((DSA)keypair, includePrivateKey);
674                         else
675                                 return null;    // TODO
676                 }
677
678                 static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey) 
679                 {
680                         if (rsa == null)
681                                 throw new ArgumentNullException ("rsa");
682
683                         if (includePrivateKey)
684                                 return ToCapiPrivateKeyBlob (rsa);
685                         else
686                                 return ToCapiPublicKeyBlob (rsa);
687                 }
688
689                 static public byte[] ToCapiKeyBlob (DSA dsa, bool includePrivateKey)
690                 {
691                         if (dsa == null)
692                                 throw new ArgumentNullException ("dsa");
693
694                         if (includePrivateKey)
695                                 return ToCapiPrivateKeyBlob (dsa);
696                         else
697                                 return ToCapiPublicKeyBlob (dsa);
698                 }
699
700                 static public string ToHex (byte[] input) 
701                 {
702                         if (input == null)
703                                 return null;
704
705                         StringBuilder sb = new StringBuilder (input.Length * 2);
706                         foreach (byte b in input) {
707                                 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
708                         }
709                         return sb.ToString ();
710                 }
711
712                 static private byte FromHexChar (char c) 
713                 {
714                         if ((c >= 'a') && (c <= 'f'))
715                                 return (byte) (c - 'a' + 10);
716                         if ((c >= 'A') && (c <= 'F'))
717                                 return (byte) (c - 'A' + 10);
718                         if ((c >= '0') && (c <= '9'))
719                                 return (byte) (c - '0');
720                         throw new ArgumentException ("invalid hex char");
721                 }
722
723                 static public byte[] FromHex (string hex) 
724                 {
725                         if (hex == null)
726                                 return null;
727                         if ((hex.Length & 0x1) == 0x1)
728                                 throw new ArgumentException ("Length must be a multiple of 2");
729
730                         byte[] result = new byte [hex.Length >> 1];
731                         int n = 0;
732                         int i = 0;
733                         while (n < result.Length) {
734                                 result [n] = (byte) (FromHexChar (hex [i++]) << 4);
735                                 result [n++] += FromHexChar (hex [i++]);
736                         }
737                         return result;
738                 }
739         }
740 }