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