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.");
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");
103 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
104 // int algId = ToInt32LE (blob, offset+4);
107 int bitLen = ToInt32LE (blob, offset+12);
109 // DWORD public exponent
110 RSAParameters rsap = new RSAParameters ();
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);
168 rsa.ImportParameters (rsap);
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);
181 catch (Exception e) {
182 throw new CryptographicException ("Invalid blob.", e);
186 static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob)
188 return FromCapiPrivateKeyBlobDSA (blob, 0);
191 static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset)
194 throw new ArgumentNullException ("blob");
195 if (offset >= blob.Length)
196 throw new ArgumentException ("blob is too small.");
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");
206 int bitlen = ToInt32LE (blob, offset + 12);
207 DSAParameters dsap = new DSAParameters ();
208 int bytelen = bitlen >> 3;
209 int pos = offset + 16;
211 dsap.P = new byte [bytelen];
212 Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
213 Array.Reverse (dsap.P);
216 dsap.Q = new byte [20];
217 Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
218 Array.Reverse (dsap.Q);
221 dsap.G = new byte [bytelen];
222 Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
223 Array.Reverse (dsap.G);
226 dsap.X = new byte [20];
227 Buffer.BlockCopy (blob, pos, dsap.X, 0, 20);
228 Array.Reverse (dsap.X);
231 dsap.Counter = ToInt32LE (blob, pos);
234 dsap.Seed = new byte [20];
235 Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
236 Array.Reverse (dsap.Seed);
239 DSA dsa = (DSA)DSA.Create ();
240 dsa.ImportParameters (dsap);
243 catch (Exception e) {
244 throw new CryptographicException ("Invalid blob.", e);
248 static public byte[] ToCapiPrivateKeyBlob (RSA rsa)
250 RSAParameters p = rsa.ExportParameters (true);
251 int keyLength = p.Modulus.Length; // in bytes
252 byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
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)
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];
269 // public exponent (DWORD)
271 int n = p.Exponent.Length;
273 blob [pos++] = p.Exponent [--n];
276 byte[] part = p.Modulus;
277 int len = part.Length;
278 Array.Reverse (part, 0, len);
279 Buffer.BlockCopy (part, 0, blob, pos, len);
284 Array.Reverse (part, 0, len);
285 Buffer.BlockCopy (part, 0, blob, pos, len);
290 Array.Reverse (part, 0, len);
291 Buffer.BlockCopy (part, 0, blob, pos, len);
296 Array.Reverse (part, 0, len);
297 Buffer.BlockCopy (part, 0, blob, pos, len);
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 static public byte[] ToCapiPrivateKeyBlob (DSA dsa)
322 DSAParameters p = dsa.ExportParameters (true);
323 int keyLength = p.P.Length; // in bytes
325 // header + P + Q + G + X + count + seed
326 byte[] blob = new byte [16 + keyLength + 20 + keyLength + 20 + 4 + 20];
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
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];
345 Array.Reverse (part);
346 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
350 Array.Reverse (part);
351 Buffer.BlockCopy (part, 0, blob, pos, 20);
355 Array.Reverse (part);
356 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
360 Array.Reverse (part);
361 Buffer.BlockCopy (part, 0, blob, pos, 20);
364 Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
368 Array.Reverse (part);
369 Buffer.BlockCopy (part, 0, blob, pos, 20);
374 static public RSA FromCapiPublicKeyBlob (byte[] blob)
376 return FromCapiPublicKeyBlob (blob, 0);
379 static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
382 throw new ArgumentNullException ("blob");
383 if (offset >= blob.Length)
384 throw new ArgumentException ("blob is too small.");
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");
394 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
395 // int algId = ToInt32LE (blob, offset+4);
398 int bitLen = ToInt32LE (blob, offset+12);
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];
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);
417 rsa.ImportParameters (rsap);
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);
430 catch (Exception e) {
431 throw new CryptographicException ("Invalid blob.", e);
435 static public DSA FromCapiPublicKeyBlobDSA (byte[] blob)
437 return FromCapiPublicKeyBlobDSA (blob, 0);
440 static public DSA FromCapiPublicKeyBlobDSA (byte[] blob, int offset)
443 throw new ArgumentNullException ("blob");
444 if (offset >= blob.Length)
445 throw new ArgumentException ("blob is too small.");
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");
455 int bitlen = ToInt32LE (blob, offset + 12);
456 DSAParameters dsap = new DSAParameters ();
457 int bytelen = bitlen >> 3;
458 int pos = offset + 16;
460 dsap.P = new byte [bytelen];
461 Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
462 Array.Reverse (dsap.P);
465 dsap.Q = new byte [20];
466 Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
467 Array.Reverse (dsap.Q);
470 dsap.G = new byte [bytelen];
471 Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
472 Array.Reverse (dsap.G);
475 dsap.Y = new byte [bytelen];
476 Buffer.BlockCopy (blob, pos, dsap.Y, 0, bytelen);
477 Array.Reverse (dsap.Y);
480 dsap.Counter = ToInt32LE (blob, pos);
483 dsap.Seed = new byte [20];
484 Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
485 Array.Reverse (dsap.Seed);
488 DSA dsa = (DSA)DSA.Create ();
489 dsa.ImportParameters (dsap);
492 catch (Exception e) {
493 throw new CryptographicException ("Invalid blob.", e);
497 static public byte[] ToCapiPublicKeyBlob (RSA rsa)
499 RSAParameters p = rsa.ExportParameters (false);
500 int keyLength = p.Modulus.Length; // in bytes
501 byte[] blob = new byte [20 + keyLength];
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)
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];
518 // public exponent (DWORD)
520 int n = p.Exponent.Length;
522 blob [pos++] = p.Exponent [--n];
525 byte[] part = p.Modulus;
526 int len = part.Length;
527 Array.Reverse (part, 0, len);
528 Buffer.BlockCopy (part, 0, blob, pos, len);
533 static public byte[] ToCapiPublicKeyBlob (DSA dsa)
535 DSAParameters p = dsa.ExportParameters (false);
536 int keyLength = p.P.Length; // in bytes
538 // header + P + Q + G + Y + count + seed
539 byte[] blob = new byte [16 + keyLength + 20 + keyLength + keyLength + 4 + 20];
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
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];
560 Array.Reverse (part);
561 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
565 Array.Reverse (part);
566 Buffer.BlockCopy (part, 0, blob, pos, 20);
570 Array.Reverse (part);
571 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
575 Array.Reverse (part);
576 Buffer.BlockCopy (part, 0, blob, pos, keyLength);
579 Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
583 Array.Reverse (part);
584 Buffer.BlockCopy (part, 0, blob, pos, 20);
591 static public RSA FromCapiKeyBlob (byte[] blob)
593 return FromCapiKeyBlob (blob, 0);
596 static public RSA FromCapiKeyBlob (byte[] blob, int offset)
599 throw new ArgumentNullException ("blob");
600 if (offset >= blob.Length)
601 throw new ArgumentException ("blob is too small.");
603 switch (blob [offset]) {
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);
612 return FromCapiPublicKeyBlob (blob, offset);
614 return FromCapiPrivateKeyBlob (blob, offset);
616 throw new CryptographicException ("Unknown blob format.");
619 static public DSA FromCapiKeyBlobDSA (byte[] blob)
621 return FromCapiKeyBlobDSA (blob, 0);
624 static public DSA FromCapiKeyBlobDSA (byte[] blob, int offset)
627 throw new ArgumentNullException ("blob");
628 if (offset >= blob.Length)
629 throw new ArgumentException ("blob is too small.");
631 switch (blob [offset]) {
633 return FromCapiPublicKeyBlobDSA (blob, offset);
635 return FromCapiPrivateKeyBlobDSA (blob, offset);
637 throw new CryptographicException ("Unknown blob format.");
640 static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey)
643 throw new ArgumentNullException ("keypair");
645 // check between RSA and DSA (and potentially others like DH)
647 return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
648 else if (keypair is DSA)
649 return ToCapiKeyBlob ((DSA)keypair, includePrivateKey);
654 static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey)
657 throw new ArgumentNullException ("rsa");
659 if (includePrivateKey)
660 return ToCapiPrivateKeyBlob (rsa);
662 return ToCapiPublicKeyBlob (rsa);
665 static public byte[] ToCapiKeyBlob (DSA dsa, bool includePrivateKey)
668 throw new ArgumentNullException ("dsa");
670 if (includePrivateKey)
671 return ToCapiPrivateKeyBlob (dsa);
673 return ToCapiPublicKeyBlob (dsa);
676 static public string ToHex (byte[] input)
681 StringBuilder sb = new StringBuilder (input.Length * 2);
682 foreach (byte b in input) {
683 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
685 return sb.ToString ();
688 static private byte FromHexChar (char c)
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");
699 static public byte[] FromHex (string hex)
703 if ((hex.Length & 0x1) == 0x1)
704 throw new ArgumentException ("Length must be a multiple of 2");
706 byte[] result = new byte [hex.Length >> 1];
709 while (n < result.Length) {
710 result [n] = (byte) (FromHexChar (hex [i++]) << 4);
711 result [n++] += FromHexChar (hex [i++]);