This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[mono.git] / mcs / class / corlib / System.Security.Cryptography / RSACryptoServiceProvider.cs
1 //
2 // RSACryptoServiceProvider.cs: Handles an RSA implementation.
3 //
4 // Authors:
5 //      Sebastien Pouliot <sebastien@ximian.com>
6 //      Ben Maurer (bmaurer@users.sf.net)
7 //
8 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Portions (C) 2003 Ben Maurer
10 // (C) 2004 Novell (http://www.novell.com)
11 //
12
13 //
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 // 
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 // 
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 //
35
36 using System;
37 using System.IO;
38
39 using Mono.Math;
40 using Mono.Security.Cryptography;
41
42 namespace System.Security.Cryptography {
43
44         public sealed class RSACryptoServiceProvider : RSA {
45         
46                 private const int PROV_RSA_FULL = 1;    // from WinCrypt.h
47
48                 private KeyPairPersistence store;
49                 private bool persistKey;
50                 private bool persisted;
51         
52                 private bool privateKeyExportable = true; 
53                 private bool m_disposed;
54
55                 private RSAManaged rsa;
56         
57                 public RSACryptoServiceProvider ()
58                 {
59                         // Here it's not clear if we need to generate a keypair
60                         // (note: MS implementation generates a keypair in this case).
61                         // However we:
62                         // (a) often use this constructor to import an existing keypair.
63                         // (b) take a LOT of time to generate the RSA keypair
64                         // So we'll generate the keypair only when (and if) it's being
65                         // used (or exported). This should save us a lot of time (at 
66                         // least in the unit tests).
67                         Common (1024, null);
68                 }
69         
70                 public RSACryptoServiceProvider (CspParameters parameters) 
71                 {
72                         Common (1024, parameters);
73                         // no keypair generation done at this stage
74                 }
75         
76                 public RSACryptoServiceProvider (int dwKeySize) 
77                 {
78                         // Here it's clear that we need to generate a new keypair
79                         Common (dwKeySize, null);
80                         // no keypair generation done at this stage
81                 }
82         
83                 public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters) 
84                 {
85                         Common (dwKeySize, parameters);
86                         // no keypair generation done at this stage
87                 }
88         
89                 private void Common (int dwKeySize, CspParameters p) 
90                 {
91                         // Microsoft RSA CSP can do between 384 and 16384 bits keypair
92                         LegalKeySizesValue = new KeySizes [1];
93                         LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
94                         base.KeySize = dwKeySize;
95
96                         rsa = new RSAManaged (KeySize);
97                         rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
98
99                         persistKey = (p != null);
100                         if (p == null) {
101                                 p = new CspParameters (PROV_RSA_FULL);
102 #if ! NET_1_0
103                                 if (useMachineKeyStore)
104                                         p.Flags |= CspProviderFlags.UseMachineKeyStore;
105 #endif
106                                 store = new KeyPairPersistence (p);
107                                 // no need to load - it cannot exists
108                         }
109                         else {
110                                 store = new KeyPairPersistence (p);
111                                 store.Load ();
112                                 if (store.KeyValue != null) {
113                                         persisted = true;
114                                         this.FromXmlString (store.KeyValue);
115                                 }
116                         }
117                 }
118
119 #if ! NET_1_0
120                 private static bool useMachineKeyStore = false;
121
122                 public static bool UseMachineKeyStore {
123                         get { return useMachineKeyStore; }
124                         set { useMachineKeyStore = value; }
125                 }
126 #endif
127         
128                 ~RSACryptoServiceProvider () 
129                 {
130                         // Zeroize private key
131                         Dispose (false);
132                 }
133         
134                 public override string KeyExchangeAlgorithm {
135                         get { return "RSA-PKCS1-KeyEx"; }
136                 }
137         
138                 public override int KeySize {
139                         get { 
140                                 if (rsa == null)
141                                       return KeySizeValue; 
142                                 else
143                                       return rsa.KeySize;
144                         }
145                 }
146
147                 public bool PersistKeyInCsp {
148                         get { return persistKey; }
149                         set {
150                                 persistKey = value;
151                                 if (persistKey)
152                                         OnKeyGenerated (rsa, null);
153                         }
154                 }
155
156 #if (NET_1_0 || NET_1_1)
157                 internal
158 #else
159                 public 
160 #endif
161                 bool PublicOnly {
162                         get { return rsa.PublicOnly; }
163                 }
164         
165                 public override string SignatureAlgorithm {
166                         get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
167                 }
168         
169                 public byte[] Decrypt (byte[] rgb, bool fOAEP) 
170                 {
171 #if NET_1_1
172                         if (m_disposed)
173                                 throw new ObjectDisposedException ("rsa");
174 #endif
175                         // choose between OAEP or PKCS#1 v.1.5 padding
176                         AsymmetricKeyExchangeDeformatter def = null;
177                         if (fOAEP)
178                                 def = new RSAOAEPKeyExchangeDeformatter (rsa);
179                         else
180                                 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
181
182                         return def.DecryptKeyExchange (rgb);
183                 }
184         
185                 // NOTE: Unlike MS we need this method
186                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
187                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
188                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
189                 // Using this method to decrypt data IS dangerous (and very slow).
190                 public override byte[] DecryptValue (byte[] rgb) 
191                 {
192                         return rsa.DecryptValue (rgb);
193                 }
194         
195                 public byte[] Encrypt (byte[] rgb, bool fOAEP) 
196                 {
197                         // choose between OAEP or PKCS#1 v.1.5 padding
198                         AsymmetricKeyExchangeFormatter fmt = null;
199                         if (fOAEP)
200                                 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
201                         else
202                                 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
203
204                         return fmt.CreateKeyExchange (rgb);
205                 }
206         
207                 // NOTE: Unlike MS we need this method
208                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
209                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
210                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
211                 // Using this method to encrypt data IS dangerous (and very slow).
212                 public override byte[] EncryptValue (byte[] rgb) 
213                 {
214                         return rsa.EncryptValue (rgb);
215                 }
216         
217                 public override RSAParameters ExportParameters (bool includePrivateParameters) 
218                 {
219                         if ((includePrivateParameters) && (!privateKeyExportable))
220                                 throw new CryptographicException ("cannot export private key");
221
222                         return rsa.ExportParameters (includePrivateParameters);
223                 }
224         
225                 public override void ImportParameters (RSAParameters parameters) 
226                 {
227                         rsa.ImportParameters (parameters);
228                 }
229         
230                 private HashAlgorithm GetHash (object halg) 
231                 {
232                         if (halg == null)
233                                 throw new ArgumentNullException ("halg");
234
235                         HashAlgorithm hash = null;
236                         if (halg is String)
237                                 hash = HashAlgorithm.Create ((String)halg);
238                         else if (halg is HashAlgorithm)
239                                 hash = (HashAlgorithm) halg;
240                         else if (halg is Type)
241                                 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
242                         else
243                                 throw new ArgumentException ("halg");
244
245                         return hash;
246                 }
247         
248                 // NOTE: this method can work with ANY configured (OID in machine.config) 
249                 // HashAlgorithm descendant
250                 public byte[] SignData (byte[] buffer, object halg) 
251                 {
252 #if NET_1_1
253                         if (buffer == null)
254                                 throw new ArgumentNullException ("buffer");
255 #endif
256                         return SignData (buffer, 0, buffer.Length, halg);
257                 }
258         
259                 // NOTE: this method can work with ANY configured (OID in machine.config) 
260                 // HashAlgorithm descendant
261                 public byte[] SignData (Stream inputStream, object halg) 
262                 {
263                         HashAlgorithm hash = GetHash (halg);
264                         byte[] toBeSigned = hash.ComputeHash (inputStream);
265                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
266                 }
267         
268                 // NOTE: this method can work with ANY configured (OID in machine.config) 
269                 // HashAlgorithm descendant
270                 public byte[] SignData (byte[] buffer, int offset, int count, object halg) 
271                 {
272                         HashAlgorithm hash = GetHash (halg);
273                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
274                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
275                 }
276         
277                 private string GetHashNameFromOID (string oid) 
278                 {
279                         switch (oid) {
280                                 case "1.3.14.3.2.26":
281                                         return "SHA1";
282                                 case "1.2.840.113549.2.5":
283                                         return "MD5";
284                                 default:
285                                         throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
286                         }
287                 }
288
289                 // LAMESPEC: str is not the hash name but an OID
290                 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
291                 // and 1.1 because there's no method to get a hash algorithm from an OID. 
292                 // However there's no such limit when using the [De]Formatter class.
293                 public byte[] SignHash (byte[] rgbHash, string str) 
294                 {
295                         if (rgbHash == null)
296                                 throw new ArgumentNullException ("rgbHash");
297                         if (str == null)
298                                 throw new CryptographicException (Locale.GetText ("No OID specified"));
299         
300                         HashAlgorithm hash = HashAlgorithm.Create (GetHashNameFromOID (str));
301                         return PKCS1.Sign_v15 (this, hash, rgbHash);
302                 }
303
304                 // NOTE: this method can work with ANY configured (OID in machine.config) 
305                 // HashAlgorithm descendant
306                 public bool VerifyData (byte[] buffer, object halg, byte[] signature) 
307                 {
308 #if NET_1_1
309                         if (buffer == null)
310                                 throw new ArgumentNullException ("buffer");
311 #endif
312                         if (signature == null)
313                                 throw new ArgumentNullException ("signature");
314
315                         HashAlgorithm hash = GetHash (halg);
316                         byte[] toBeVerified = hash.ComputeHash (buffer);
317                         return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
318                 }
319         
320                 // LAMESPEC: str is not the hash name but an OID
321                 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
322                 // and 1.1 because there's no method to get a hash algorithm from an OID. 
323                 // However there's no such limit when using the [De]Formatter class.
324                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
325                 {
326                         if (rgbHash == null) 
327                                 throw new ArgumentNullException ("rgbHash");
328                         if (rgbSignature == null)
329                                 throw new ArgumentNullException ("rgbSignature");
330         
331                         HashAlgorithm hash = HashAlgorithm.Create (GetHashNameFromOID (str));
332                         return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
333                 }
334         
335                 protected override void Dispose (bool disposing) 
336                 {
337                         if (!m_disposed) {
338                                 // the key is persisted and we do not want it persisted
339                                 if ((persisted) && (!persistKey)) {
340                                         store.Remove ();        // delete the container
341                                 }
342                                 if (rsa != null)
343                                         rsa.Clear ();
344                                 // call base class 
345                                 // no need as they all are abstract before us
346                                 m_disposed = true;
347                         }
348                 }
349
350                 // private stuff
351
352                 private void OnKeyGenerated (object sender, EventArgs e) 
353                 {
354                         // the key isn't persisted and we want it persisted
355                         if ((persistKey) && (!persisted)) {
356                                 // save the current keypair
357                                 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
358                                 store.Save ();
359                                 persisted = true;
360                         }
361                 }
362         }
363 }