2007-11-13 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / class / corlib / System.Reflection / StrongNameKeyPair.cs
1 //
2 // System.Reflection.StrongNameKeyPair.cs
3 //
4 // Authors:
5 //      Kevin Winchester (kwin@ns.sympatico.ca)
6 //      Sebastien Pouliot (sebastien@ximian.com)
7 //
8 // (C) 2002 Kevin Winchester
9 // Portions (C) 2002 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.IO;
33 using System.Security.Cryptography;
34 using System.Security.Permissions;
35 using System.Runtime.InteropServices;
36 using System.Runtime.Serialization;
37
38 using Mono.Security;
39 using Mono.Security.Cryptography;
40
41 namespace System.Reflection {
42
43 #if NET_2_0
44         [ComVisible (true)]
45 #endif
46 [Serializable]
47 public class StrongNameKeyPair 
48 #if NET_2_0
49         : ISerializable, IDeserializationCallback
50 #endif
51 {               
52         private byte[] _publicKey;
53         private string _keyPairContainer;
54         private bool _keyPairExported;
55         private byte[] _keyPairArray;
56         
57         [NonSerialized]
58         private RSA _rsa;
59
60         // note: we ask for UnmanagedCode because we do not want everyone
61         // to be able to generate strongnamed assemblies
62
63         [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
64         public StrongNameKeyPair (byte[] keyPairArray) 
65         {
66                 if (keyPairArray == null)
67                         throw new ArgumentNullException ("keyPairArray");
68
69                 LoadKey (keyPairArray);
70                 GetRSA ();
71         }
72         
73         [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
74         public StrongNameKeyPair (FileStream keyPairFile) 
75         {
76                 if (keyPairFile == null)
77                         throw new ArgumentNullException ("keyPairFile");
78
79                 byte[] input = new byte [keyPairFile.Length];
80                 keyPairFile.Read (input, 0, input.Length);
81                 LoadKey (input);
82                 GetRSA ();
83         }
84         
85         [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
86         public StrongNameKeyPair (string keyPairContainer) 
87         {
88                 // named key container
89                 if (keyPairContainer == null)
90                         throw new ArgumentNullException ("keyPairContainer");
91
92                 _keyPairContainer = keyPairContainer;
93                 GetRSA ();
94         }
95 #if NET_2_0
96         protected StrongNameKeyPair (SerializationInfo info, StreamingContext context)
97         {
98                 _publicKey = (byte []) info.GetValue ("_publicKey", typeof (byte []));
99                 _keyPairContainer = info.GetString ("_keyPairContainer");
100                 _keyPairExported = info.GetBoolean ("_keyPairExported");
101                 _keyPairArray = (byte []) info.GetValue ("_keyPairArray", typeof (byte []));
102         }
103
104         void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
105         {
106                 info.AddValue ("_publicKey", _publicKey, typeof (byte []));
107                 info.AddValue ("_keyPairContainer", _keyPairContainer);
108                 info.AddValue ("_keyPairExported", _keyPairExported);
109                 info.AddValue ("_keyPairArray", _keyPairArray, typeof (byte []));
110         }
111
112         void IDeserializationCallback.OnDeserialization (object sender)
113         {
114         }
115 #endif
116         private RSA GetRSA ()
117         {
118                 if (_rsa != null) return _rsa;
119                 
120                 if (_keyPairArray != null) {
121                         try {
122                                 _rsa = CryptoConvert.FromCapiKeyBlob (_keyPairArray);
123                         }
124                         catch {
125                                 // exception is thrown when getting PublicKey
126                                 // to match MS implementation
127                                 _keyPairArray = null;
128                         }
129                 }
130                 else if (_keyPairContainer != null) {
131                         CspParameters csp = new CspParameters ();
132                         csp.KeyContainerName = _keyPairContainer;
133                         _rsa = new RSACryptoServiceProvider (csp);
134                 }
135                 return _rsa;
136         }
137
138         private void LoadKey (byte[] key) 
139         {
140                 try {
141                         // check for ECMA key
142                         if (key.Length == 16) {
143                                 int i = 0;
144                                 int sum = 0;
145                                 while (i < key.Length)
146                                         sum += key [i++];
147                                 if (sum == 4) {
148                                         // it is the ECMA key
149                                         _publicKey = (byte[]) key.Clone ();
150                                 }
151                         }
152                         else
153                                 _keyPairArray = key;
154                 }
155                 catch
156                 {
157                         // exception is thrown when getting PublicKey
158                         // to match MS implementation
159                 }
160         }
161
162         public byte[] PublicKey {
163                 get {
164                         if (_publicKey == null) {
165                                 RSA rsa = GetRSA ();
166                                 // ECMA "key" is valid but doesn't produce a RSA instance
167                                 if (rsa == null)
168                                         throw new ArgumentException ("invalid keypair");
169
170                                 byte[] blob = CryptoConvert.ToCapiKeyBlob (rsa, false);
171                                 _publicKey = new byte [blob.Length + 12];
172                                 // The first 12 bytes are documented at:
173                                 // http://msdn.microsoft.com/library/en-us/cprefadd/html/grfungethashfromfile.asp
174                                 // ALG_ID - Signature
175                                 _publicKey[0] = 0x00;
176                                 _publicKey[1] = 0x24;   
177                                 _publicKey[2] = 0x00;   
178                                 _publicKey[3] = 0x00;   
179                                 // ALG_ID - Hash
180                                 _publicKey[4] = 0x04;
181                                 _publicKey[5] = 0x80;
182                                 _publicKey[6] = 0x00;
183                                 _publicKey[7] = 0x00;
184                                 // Length of Public Key (in bytes)
185                                 int lastPart = blob.Length;
186                                 _publicKey[8] = (byte)(lastPart % 256);
187                                 _publicKey[9] = (byte)(lastPart / 256); // just in case
188                                 _publicKey[10] = 0x00;
189                                 _publicKey[11] = 0x00;
190
191                                 Buffer.BlockCopy (blob, 0, _publicKey, 12, blob.Length);
192                         }
193                         return _publicKey;
194                 }
195         }
196
197         internal StrongName StrongName () 
198         {
199                 RSA rsa = GetRSA ();
200                 if (rsa != null)
201                         return new StrongName (rsa);
202                 if (_publicKey != null)
203                         return new StrongName (_publicKey);
204                 return null;
205         }
206 }
207
208 }