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 byte[] ToCapiPrivateKeyBlob (RSA rsa)
188 RSAParameters p = rsa.ExportParameters (true);
189 int keyLength = p.Modulus.Length; // in bytes
190 byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
192 blob [0] = 0x07; // Type - PRIVATEKEYBLOB (0x07)
193 blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02)
194 // [2], [3] // RESERVED - Always 0
195 blob [5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
196 blob [8] = 0x52; // Magic - RSA2 (ASCII in hex)
201 byte[] bitlen = GetBytesLE (keyLength << 3);
202 blob [12] = bitlen [0]; // bitlen
203 blob [13] = bitlen [1];
204 blob [14] = bitlen [2];
205 blob [15] = bitlen [3];
207 // public exponent (DWORD)
209 int n = p.Exponent.Length;
211 blob [pos++] = p.Exponent [--n];
214 byte[] part = p.Modulus;
215 int len = part.Length;
216 Array.Reverse (part, 0, len);
217 Buffer.BlockCopy (part, 0, blob, pos, len);
222 Array.Reverse (part, 0, len);
223 Buffer.BlockCopy (part, 0, blob, pos, len);
228 Array.Reverse (part, 0, len);
229 Buffer.BlockCopy (part, 0, blob, pos, len);
234 Array.Reverse (part, 0, len);
235 Buffer.BlockCopy (part, 0, blob, pos, len);
240 Array.Reverse (part, 0, len);
241 Buffer.BlockCopy (part, 0, blob, pos, len);
246 Array.Reverse (part, 0, len);
247 Buffer.BlockCopy (part, 0, blob, pos, len);
252 Array.Reverse (part, 0, len);
253 Buffer.BlockCopy (part, 0, blob, pos, len);
258 static public RSA FromCapiPublicKeyBlob (byte[] blob)
260 return FromCapiPublicKeyBlob (blob, 0);
263 static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
266 throw new ArgumentNullException ("blob");
267 if (offset >= blob.Length)
268 throw new ArgumentException ("blob is too small.");
271 if ((blob [offset] != 0x06) || // PUBLICKEYBLOB (0x06)
272 (blob [offset+1] != 0x02) || // Version (0x02)
273 (blob [offset+2] != 0x00) || // Reserved (word)
274 (blob [offset+3] != 0x00) ||
275 (ToUInt32LE (blob, offset+8) != 0x31415352)) // DWORD magic = RSA1
276 throw new CryptographicException ("Invalid blob header");
278 // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
279 // int algId = ToInt32LE (blob, offset+4);
282 int bitLen = ToInt32LE (blob, offset+12);
284 // DWORD public exponent
285 RSAParameters rsap = new RSAParameters ();
286 rsap.Exponent = new byte [3];
287 rsap.Exponent [0] = blob [offset+18];
288 rsap.Exponent [1] = blob [offset+17];
289 rsap.Exponent [2] = blob [offset+16];
292 // BYTE modulus[rsapubkey.bitlen/8];
293 int byteLen = (bitLen >> 3);
294 rsap.Modulus = new byte [byteLen];
295 Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
296 Array.Reverse (rsap.Modulus);
301 rsa.ImportParameters (rsap);
303 catch (CryptographicException) {
304 // this may cause problem when this code is run under
305 // the SYSTEM identity on Windows (e.g. ASP.NET). See
306 // http://bugzilla.ximian.com/show_bug.cgi?id=77559
307 CspParameters csp = new CspParameters ();
308 csp.Flags = CspProviderFlags.UseMachineKeyStore;
309 rsa = new RSACryptoServiceProvider (csp);
310 rsa.ImportParameters (rsap);
314 catch (Exception e) {
315 throw new CryptographicException ("Invalid blob.", e);
319 static public byte[] ToCapiPublicKeyBlob (RSA rsa)
321 RSAParameters p = rsa.ExportParameters (false);
322 int keyLength = p.Modulus.Length; // in bytes
323 byte[] blob = new byte [20 + keyLength];
325 blob [0] = 0x06; // Type - PUBLICKEYBLOB (0x06)
326 blob [1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02)
327 // [2], [3] // RESERVED - Always 0
328 blob [5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
329 blob [8] = 0x52; // Magic - RSA1 (ASCII in hex)
334 byte[] bitlen = GetBytesLE (keyLength << 3);
335 blob [12] = bitlen [0]; // bitlen
336 blob [13] = bitlen [1];
337 blob [14] = bitlen [2];
338 blob [15] = bitlen [3];
340 // public exponent (DWORD)
342 int n = p.Exponent.Length;
344 blob [pos++] = p.Exponent [--n];
347 byte[] part = p.Modulus;
348 int len = part.Length;
349 Array.Reverse (part, 0, len);
350 Buffer.BlockCopy (part, 0, blob, pos, len);
357 static public RSA FromCapiKeyBlob (byte[] blob)
359 return FromCapiKeyBlob (blob, 0);
362 static public RSA FromCapiKeyBlob (byte[] blob, int offset)
365 throw new ArgumentNullException ("blob");
366 if (offset >= blob.Length)
367 throw new ArgumentException ("blob is too small.");
369 switch (blob [offset]) {
371 // this could be a public key inside an header
372 // like "sn -e" would produce
373 if (blob [offset + 12] == 0x06) {
374 return FromCapiPublicKeyBlob (blob, offset + 12);
378 return FromCapiPublicKeyBlob (blob, offset);
380 return FromCapiPrivateKeyBlob (blob, offset);
382 throw new CryptographicException ("Unknown blob format.");
385 static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey)
388 throw new ArgumentNullException ("keypair");
390 // check between RSA and DSA (and potentially others like DH)
392 return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
397 static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey)
400 throw new ArgumentNullException ("rsa");
402 if (includePrivateKey)
403 return ToCapiPrivateKeyBlob (rsa);
405 return ToCapiPublicKeyBlob (rsa);
408 static public string ToHex (byte[] input)
413 StringBuilder sb = new StringBuilder (input.Length * 2);
414 foreach (byte b in input) {
415 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
417 return sb.ToString ();
420 static private byte FromHexChar (char c)
422 if ((c >= 'a') && (c <= 'f'))
423 return (byte) (c - 'a' + 10);
424 if ((c >= 'A') && (c <= 'F'))
425 return (byte) (c - 'A' + 10);
426 if ((c >= '0') && (c <= '9'))
427 return (byte) (c - '0');
428 throw new ArgumentException ("invalid hex char");
431 static public byte[] FromHex (string hex)
435 if ((hex.Length & 0x1) == 0x1)
436 throw new ArgumentException ("Length must be a multiple of 2");
438 byte[] result = new byte [hex.Length >> 1];
441 while (n < result.Length) {
442 result [n] = (byte) (FromHexChar (hex [i++]) << 4);
443 result [n++] += FromHexChar (hex [i++]);