Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistentDataStructures/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs @ 14648

Last change on this file since 14648 was 11700, checked in by jkarder, 10 years ago

#2077: created branch and added first version

File size: 7.6 KB
Line 
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
30using System;
31using System.Security.Cryptography;
32
33#if !(SILVERLIGHT || READ_ONLY)
34
35namespace Mono.Security.Cryptography {
36
37  static class CryptoConvert {
38
39    static private int ToInt32LE (byte [] bytes, int offset)
40    {
41      return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
42    }
43
44    static private uint ToUInt32LE (byte [] bytes, int offset)
45    {
46      return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
47    }
48
49    static private byte[] Trim (byte[] array)
50    {
51      for (int i=0; i < array.Length; i++) {
52        if (array [i] != 0x00) {
53          byte[] result = new byte [array.Length - i];
54          Buffer.BlockCopy (array, i, result, 0, result.Length);
55          return result;
56        }
57      }
58      return null;
59    }
60
61    static RSA FromCapiPrivateKeyBlob (byte[] blob, int offset)
62    {
63      RSAParameters rsap = new RSAParameters ();
64      try {
65        if ((blob [offset]   != 0x07) ||        // PRIVATEKEYBLOB (0x07)
66            (blob [offset+1] != 0x02) ||        // Version (0x02)
67            (blob [offset+2] != 0x00) ||        // Reserved (word)
68            (blob [offset+3] != 0x00) ||
69            (ToUInt32LE (blob, offset+8) != 0x32415352))  // DWORD magic = RSA2
70          throw new CryptographicException ("Invalid blob header");
71
72        // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
73        // int algId = ToInt32LE (blob, offset+4);
74
75        // DWORD bitlen
76        int bitLen = ToInt32LE (blob, offset+12);
77
78        // DWORD public exponent
79        byte[] exp = new byte [4];
80        Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
81        Array.Reverse (exp);
82        rsap.Exponent = Trim (exp);
83
84        int pos = offset+20;
85        // BYTE modulus[rsapubkey.bitlen/8];
86        int byteLen = (bitLen >> 3);
87        rsap.Modulus = new byte [byteLen];
88        Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
89        Array.Reverse (rsap.Modulus);
90        pos += byteLen;
91
92        // BYTE prime1[rsapubkey.bitlen/16];
93        int byteHalfLen = (byteLen >> 1);
94        rsap.P = new byte [byteHalfLen];
95        Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen);
96        Array.Reverse (rsap.P);
97        pos += byteHalfLen;
98
99        // BYTE prime2[rsapubkey.bitlen/16];
100        rsap.Q = new byte [byteHalfLen];
101        Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen);
102        Array.Reverse (rsap.Q);
103        pos += byteHalfLen;
104
105        // BYTE exponent1[rsapubkey.bitlen/16];
106        rsap.DP = new byte [byteHalfLen];
107        Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen);
108        Array.Reverse (rsap.DP);
109        pos += byteHalfLen;
110
111        // BYTE exponent2[rsapubkey.bitlen/16];
112        rsap.DQ = new byte [byteHalfLen];
113        Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen);
114        Array.Reverse (rsap.DQ);
115        pos += byteHalfLen;
116
117        // BYTE coefficient[rsapubkey.bitlen/16];
118        rsap.InverseQ = new byte [byteHalfLen];
119        Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen);
120        Array.Reverse (rsap.InverseQ);
121        pos += byteHalfLen;
122
123        // ok, this is hackish but CryptoAPI support it so...
124        // note: only works because CRT is used by default
125        // http://bugzilla.ximian.com/show_bug.cgi?id=57941
126        rsap.D = new byte [byteLen]; // must be allocated
127        if (pos + byteLen + offset <= blob.Length) {
128          // BYTE privateExponent[rsapubkey.bitlen/8];
129          Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen);
130          Array.Reverse (rsap.D);
131        }
132      }
133      catch (Exception e) {
134        throw new CryptographicException ("Invalid blob.", e);
135      }
136
137      RSA rsa = null;
138      try {
139        rsa = RSA.Create ();
140        rsa.ImportParameters (rsap);
141      }
142      catch (CryptographicException ce) {
143        // this may cause problem when this code is run under
144        // the SYSTEM identity on Windows (e.g. ASP.NET). See
145        // http://bugzilla.ximian.com/show_bug.cgi?id=77559
146        try {
147          CspParameters csp = new CspParameters ();
148          csp.Flags = CspProviderFlags.UseMachineKeyStore;
149          rsa = new RSACryptoServiceProvider (csp);
150          rsa.ImportParameters (rsap);
151        }
152        catch {
153          // rethrow original, not the later, exception if this fails
154          throw ce;
155        }
156      }
157      return rsa;
158    }
159
160    static RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
161    {
162      try {
163        if ((blob [offset]   != 0x06) ||        // PUBLICKEYBLOB (0x06)
164            (blob [offset+1] != 0x02) ||        // Version (0x02)
165            (blob [offset+2] != 0x00) ||        // Reserved (word)
166            (blob [offset+3] != 0x00) ||
167            (ToUInt32LE (blob, offset+8) != 0x31415352))  // DWORD magic = RSA1
168          throw new CryptographicException ("Invalid blob header");
169
170        // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
171        // int algId = ToInt32LE (blob, offset+4);
172
173        // DWORD bitlen
174        int bitLen = ToInt32LE (blob, offset+12);
175
176        // DWORD public exponent
177        RSAParameters rsap = new RSAParameters ();
178        rsap.Exponent = new byte [3];
179        rsap.Exponent [0] = blob [offset+18];
180        rsap.Exponent [1] = blob [offset+17];
181        rsap.Exponent [2] = blob [offset+16];
182
183        int pos = offset+20;
184        // BYTE modulus[rsapubkey.bitlen/8];
185        int byteLen = (bitLen >> 3);
186        rsap.Modulus = new byte [byteLen];
187        Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
188        Array.Reverse (rsap.Modulus);
189
190        RSA rsa = null;
191        try {
192          rsa = RSA.Create ();
193          rsa.ImportParameters (rsap);
194        }
195        catch (CryptographicException) {
196          // this may cause problem when this code is run under
197          // the SYSTEM identity on Windows (e.g. ASP.NET). See
198          // http://bugzilla.ximian.com/show_bug.cgi?id=77559
199          CspParameters csp = new CspParameters ();
200          csp.Flags = CspProviderFlags.UseMachineKeyStore;
201          rsa = new RSACryptoServiceProvider (csp);
202          rsa.ImportParameters (rsap);
203        }
204        return rsa;
205      }
206      catch (Exception e) {
207        throw new CryptographicException ("Invalid blob.", e);
208      }
209    }
210
211    // PRIVATEKEYBLOB
212    // PUBLICKEYBLOB
213    static public RSA FromCapiKeyBlob (byte[] blob)
214    {
215      return FromCapiKeyBlob (blob, 0);
216    }
217
218    static public RSA FromCapiKeyBlob (byte[] blob, int offset)
219    {
220      if (blob == null)
221        throw new ArgumentNullException ("blob");
222      if (offset >= blob.Length)
223        throw new ArgumentException ("blob is too small.");
224
225      switch (blob [offset]) {
226        case 0x00:
227          // this could be a public key inside an header
228          // like "sn -e" would produce
229          if (blob [offset + 12] == 0x06) {
230            return FromCapiPublicKeyBlob (blob, offset + 12);
231          }
232          break;
233        case 0x06:
234          return FromCapiPublicKeyBlob (blob, offset);
235        case 0x07:
236          return FromCapiPrivateKeyBlob (blob, offset);
237      }
238      throw new CryptographicException ("Unknown blob format.");
239    }
240  }
241}
242
243#endif
Note: See TracBrowser for help on using the repository browser.