2 // CryptoConvert.cs - Crypto Convertion Routines
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
31 using System.Globalization;
32 using System.Security.Cryptography;
35 namespace Mono.Security.Cryptography {
42 sealed class CryptoConvert {
44 private CryptoConvert ()
48 static private int ToInt32LE (byte [] bytes, int offset)
50 return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
53 static private uint ToUInt32LE (byte [] bytes, int offset)
55 return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
58 static private byte [] GetBytesLE (int val)
62 (byte) ((val >> 8) & 0xff),
63 (byte) ((val >> 16) & 0xff),
64 (byte) ((val >> 24) & 0xff)
68 static private byte[] Trim (byte[] array)
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);
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)
85 return FromCapiPrivateKeyBlob (blob, 0);
88 static public RSA FromCapiPrivateKeyBlob (byte[] blob, int offset)
91 throw new ArgumentNullException ("blob");
92 if (offset >= blob.Length)
93 throw new ArgumentException ("blob is too small.");
95 RSAParameters rsap = new RSAParameters ();
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");
104 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
105 // int algId = ToInt32LE (blob, offset+4);
108 int bitLen = ToInt32LE (blob, offset+12);
110 // DWORD public exponent
111 byte[] exp = new byte [4];
112 Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
114 rsap.Exponent = Trim (exp);
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);
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);
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);
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);
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);
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);
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);
165 catch (Exception e) {
166 throw new CryptographicException ("Invalid blob.", e);
172 rsa.ImportParameters (rsap);
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
179 CspParameters csp = new CspParameters ();
180 csp.Flags = CspProviderFlags.UseMachineKeyStore;
181 rsa = new RSACryptoServiceProvider (csp);
182 rsa.ImportParameters (rsap);
185 // rethrow original, not the later, exception if this fails
192 static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob)
194 return FromCapiPrivateKeyBlobDSA (blob, 0);
197 static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset)
200 throw new ArgumentNullException ("blob");
201 if (offset >= blob.Length)
202 throw new ArgumentException ("blob is too small.");
204 DSAParameters dsap = new DSAParameters ();
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");
213 int bitlen = ToInt32LE (blob, offset + 12);
214 int bytelen = bitlen >> 3;
215 int pos = offset + 16;
217 dsap.P = new byte [bytelen];
218 Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
219 Array.Reverse (dsap.P);
222 dsap.Q = new byte [20];
223 Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
224 Array.Reverse (dsap.Q);
227 dsap.G = new byte [bytelen];
228 Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
229 Array.Reverse (dsap.G);
232 dsap.X = new byte [20];
233 Buffer.BlockCopy (blob, pos, dsap.X, 0, 20);
234 Array.Reverse (dsap.X);
237 dsap.Counter = ToInt32LE (blob, pos);
240 dsap.Seed = new byte [20];
241 Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
242 Array.Reverse (dsap.Seed);
245 catch (Exception e) {
246 throw new CryptographicException ("Invalid blob.", e);
251 dsa = (DSA)DSA.Create ();
252 dsa.ImportParameters (dsap);
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
259 CspParameters csp = new CspParameters ();
260 csp.Flags = CspProviderFlags.UseMachineKeyStore;
261 dsa = new DSACryptoServiceProvider (csp);
262 dsa.ImportParameters (dsap);
265 // rethrow original, not the later, exception if this fails
272 static public byte[] ToCapiPrivateKeyBlob (RSA rsa)
274 RSAParameters p = rsa.ExportParameters (true);
275 int keyLength = p.Modulus.Length; // in bytes
276 byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
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)
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];
293 // public exponent (DWORD)
295 int n = p.Exponent.Length;
297 blob [pos++] = p.Exponent [--n];
300 byte[] part = p.Modulus;
301 int len = part.Length;
302 Array.Reverse (part, 0, len);
303 Buffer.BlockCopy (part, 0, blob, pos, len);
308 Array.Reverse (part, 0, len);
309 Buffer.BlockCopy (part, 0, blob, pos, len);
314 Array.Reverse (part, 0, len);
315 Buffer.BlockCopy (part, 0, blob, pos, len);
320 Array.Reverse (part, 0, len);
321 Buffer.BlockCopy (part, 0, blob, pos, len);
326 Array.Reverse (part, 0, len);
327 Buffer.BlockCopy (part, 0, blob, pos, len);
332 Array.Reverse (part, 0, len);
333 Buffer.BlockCopy (part, 0, blob, pos, len);
338 Array.Reverse (part, 0, len);
339 Buffer.BlockCopy (part, 0, blob, pos, len);
344 static public byte[] ToCapiPrivateKeyBlob (DSA dsa)
346 DSAParameters p = dsa.ExportParameters (true);
347 int keyLength = p.P.Length; // in bytes
349 // header + P + Q + G + X + count + seed
350 byte[] blob = new byte [16 + keyLength + 20 + keyLength + 20 + 4 + 20];
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
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];
369 Array.Reverse (part);
370 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
374 Array.Reverse (part);
375 Buffer.BlockCopy (part, 0, blob, pos, 20);
379 Array.Reverse (part);
380 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
384 Array.Reverse (part);
385 Buffer.BlockCopy (part, 0, blob, pos, 20);
388 Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
392 Array.Reverse (part);
393 Buffer.BlockCopy (part, 0, blob, pos, 20);
398 static public RSA FromCapiPublicKeyBlob (byte[] blob)
400 return FromCapiPublicKeyBlob (blob, 0);
403 static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
406 throw new ArgumentNullException ("blob");
407 if (offset >= blob.Length)
408 throw new ArgumentException ("blob is too small.");
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");
418 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
419 // int algId = ToInt32LE (blob, offset+4);
422 int bitLen = ToInt32LE (blob, offset+12);
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];
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);
441 rsa.ImportParameters (rsap);
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);
454 catch (Exception e) {
455 throw new CryptographicException ("Invalid blob.", e);
459 static public DSA FromCapiPublicKeyBlobDSA (byte[] blob)
461 return FromCapiPublicKeyBlobDSA (blob, 0);
464 static public DSA FromCapiPublicKeyBlobDSA (byte[] blob, int offset)
467 throw new ArgumentNullException ("blob");
468 if (offset >= blob.Length)
469 throw new ArgumentException ("blob is too small.");
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");
479 int bitlen = ToInt32LE (blob, offset + 12);
480 DSAParameters dsap = new DSAParameters ();
481 int bytelen = bitlen >> 3;
482 int pos = offset + 16;
484 dsap.P = new byte [bytelen];
485 Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
486 Array.Reverse (dsap.P);
489 dsap.Q = new byte [20];
490 Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
491 Array.Reverse (dsap.Q);
494 dsap.G = new byte [bytelen];
495 Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
496 Array.Reverse (dsap.G);
499 dsap.Y = new byte [bytelen];
500 Buffer.BlockCopy (blob, pos, dsap.Y, 0, bytelen);
501 Array.Reverse (dsap.Y);
504 dsap.Counter = ToInt32LE (blob, pos);
507 dsap.Seed = new byte [20];
508 Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
509 Array.Reverse (dsap.Seed);
512 DSA dsa = (DSA)DSA.Create ();
513 dsa.ImportParameters (dsap);
516 catch (Exception e) {
517 throw new CryptographicException ("Invalid blob.", e);
521 static public byte[] ToCapiPublicKeyBlob (RSA rsa)
523 RSAParameters p = rsa.ExportParameters (false);
524 int keyLength = p.Modulus.Length; // in bytes
525 byte[] blob = new byte [20 + keyLength];
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)
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];
542 // public exponent (DWORD)
544 int n = p.Exponent.Length;
546 blob [pos++] = p.Exponent [--n];
549 byte[] part = p.Modulus;
550 int len = part.Length;
551 Array.Reverse (part, 0, len);
552 Buffer.BlockCopy (part, 0, blob, pos, len);
557 static public byte[] ToCapiPublicKeyBlob (DSA dsa)
559 DSAParameters p = dsa.ExportParameters (false);
560 int keyLength = p.P.Length; // in bytes
562 // header + P + Q + G + Y + count + seed
563 byte[] blob = new byte [16 + keyLength + 20 + keyLength + keyLength + 4 + 20];
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
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];
584 Array.Reverse (part);
585 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
589 Array.Reverse (part);
590 Buffer.BlockCopy (part, 0, blob, pos, 20);
594 Array.Reverse (part);
595 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
599 Array.Reverse (part);
600 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
603 Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
607 Array.Reverse (part);
608 Buffer.BlockCopy (part, 0, blob, pos, 20);
615 static public RSA FromCapiKeyBlob (byte[] blob)
617 return FromCapiKeyBlob (blob, 0);
620 static public RSA FromCapiKeyBlob (byte[] blob, int offset)
623 throw new ArgumentNullException ("blob");
624 if (offset >= blob.Length)
625 throw new ArgumentException ("blob is too small.");
627 switch (blob [offset]) {
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);
636 return FromCapiPublicKeyBlob (blob, offset);
638 return FromCapiPrivateKeyBlob (blob, offset);
640 throw new CryptographicException ("Unknown blob format.");
643 static public DSA FromCapiKeyBlobDSA (byte[] blob)
645 return FromCapiKeyBlobDSA (blob, 0);
648 static public DSA FromCapiKeyBlobDSA (byte[] blob, int offset)
651 throw new ArgumentNullException ("blob");
652 if (offset >= blob.Length)
653 throw new ArgumentException ("blob is too small.");
655 switch (blob [offset]) {
657 return FromCapiPublicKeyBlobDSA (blob, offset);
659 return FromCapiPrivateKeyBlobDSA (blob, offset);
661 throw new CryptographicException ("Unknown blob format.");
664 static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey)
667 throw new ArgumentNullException ("keypair");
669 // check between RSA and DSA (and potentially others like DH)
671 return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
672 else if (keypair is DSA)
673 return ToCapiKeyBlob ((DSA)keypair, includePrivateKey);
678 static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey)
681 throw new ArgumentNullException ("rsa");
683 if (includePrivateKey)
684 return ToCapiPrivateKeyBlob (rsa);
686 return ToCapiPublicKeyBlob (rsa);
689 static public byte[] ToCapiKeyBlob (DSA dsa, bool includePrivateKey)
692 throw new ArgumentNullException ("dsa");
694 if (includePrivateKey)
695 return ToCapiPrivateKeyBlob (dsa);
697 return ToCapiPublicKeyBlob (dsa);
700 static public string ToHex (byte[] input)
705 StringBuilder sb = new StringBuilder (input.Length * 2);
706 foreach (byte b in input) {
707 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
709 return sb.ToString ();
712 static private byte FromHexChar (char c)
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");
723 static public byte[] FromHex (string hex)
727 if ((hex.Length & 0x1) == 0x1)
728 throw new ArgumentException ("Length must be a multiple of 2");
730 byte[] result = new byte [hex.Length >> 1];
733 while (n < result.Length) {
734 result [n] = (byte) (FromHexChar (hex [i++]) << 4);
735 result [n++] += FromHexChar (hex [i++]);