2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[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 // Copyright (C) 2004 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.Runtime.InteropServices;
34
35 using Mono.Security.Cryptography;
36
37 namespace System.Security.Cryptography {
38
39 #if (NET_2_0)
40         public sealed class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm {
41 #else
42         public sealed class RSACryptoServiceProvider : RSA {
43 #endif
44                 private const int PROV_RSA_FULL = 1;    // from WinCrypt.h
45
46                 private KeyPairPersistence store;
47                 private bool persistKey;
48                 private bool persisted;
49         
50                 private bool privateKeyExportable = true; 
51                 private bool m_disposed;
52
53                 private RSAManaged rsa;
54         
55                 public RSACryptoServiceProvider ()
56                 {
57                         // Here it's not clear if we need to generate a keypair
58                         // (note: MS implementation generates a keypair in this case).
59                         // However we:
60                         // (a) often use this constructor to import an existing keypair.
61                         // (b) take a LOT of time to generate the RSA keypair
62                         // So we'll generate the keypair only when (and if) it's being
63                         // used (or exported). This should save us a lot of time (at 
64                         // least in the unit tests).
65                         Common (1024, null);
66                 }
67         
68                 public RSACryptoServiceProvider (CspParameters parameters) 
69                 {
70                         Common (1024, parameters);
71                         // no keypair generation done at this stage
72                 }
73         
74                 public RSACryptoServiceProvider (int dwKeySize) 
75                 {
76                         // Here it's clear that we need to generate a new keypair
77                         Common (dwKeySize, null);
78                         // no keypair generation done at this stage
79                 }
80         
81                 public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters) 
82                 {
83                         Common (dwKeySize, parameters);
84                         // no keypair generation done at this stage
85                 }
86         
87                 private void Common (int dwKeySize, CspParameters p) 
88                 {
89                         // Microsoft RSA CSP can do between 384 and 16384 bits keypair
90                         LegalKeySizesValue = new KeySizes [1];
91                         LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
92                         base.KeySize = dwKeySize;
93
94                         rsa = new RSAManaged (KeySize);
95                         rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
96
97                         persistKey = (p != null);
98                         if (p == null) {
99                                 p = new CspParameters (PROV_RSA_FULL);
100 #if NET_1_1
101                                 if (useMachineKeyStore)
102                                         p.Flags |= CspProviderFlags.UseMachineKeyStore;
103 #endif
104                                 store = new KeyPairPersistence (p);
105                                 // no need to load - it cannot exists
106                         }
107                         else {
108                                 store = new KeyPairPersistence (p);
109                                 store.Load ();
110                                 if (store.KeyValue != null) {
111                                         persisted = true;
112                                         this.FromXmlString (store.KeyValue);
113                                 }
114                         }
115                 }
116
117 #if NET_1_1
118                 private static bool useMachineKeyStore = false;
119
120                 public static bool UseMachineKeyStore {
121                         get { return useMachineKeyStore; }
122                         set { useMachineKeyStore = value; }
123                 }
124 #endif
125         
126                 ~RSACryptoServiceProvider () 
127                 {
128                         // Zeroize private key
129                         Dispose (false);
130                 }
131         
132                 public override string KeyExchangeAlgorithm {
133                         get { return "RSA-PKCS1-KeyEx"; }
134                 }
135         
136                 public override int KeySize {
137                         get { 
138                                 if (rsa == null)
139                                       return KeySizeValue; 
140                                 else
141                                       return rsa.KeySize;
142                         }
143                 }
144
145                 public bool PersistKeyInCsp {
146                         get { return persistKey; }
147                         set {
148                                 persistKey = value;
149                                 if (persistKey)
150                                         OnKeyGenerated (rsa, null);
151                         }
152                 }
153
154 #if (NET_2_0)
155                 [ComVisible (false)]
156                 public 
157 #else
158                 internal
159 #endif
160                 bool PublicOnly {
161                         get { return rsa.PublicOnly; }
162                 }
163         
164                 public override string SignatureAlgorithm {
165                         get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
166                 }
167         
168                 public byte[] Decrypt (byte[] rgb, bool fOAEP) 
169                 {
170 #if NET_1_1
171                         if (m_disposed)
172                                 throw new ObjectDisposedException ("rsa");
173 #endif
174                         // choose between OAEP or PKCS#1 v.1.5 padding
175                         AsymmetricKeyExchangeDeformatter def = null;
176                         if (fOAEP)
177                                 def = new RSAOAEPKeyExchangeDeformatter (rsa);
178                         else
179                                 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
180
181                         return def.DecryptKeyExchange (rgb);
182                 }
183         
184                 // NOTE: Unlike MS we need this method
185                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
186                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
187                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
188                 // Using this method to decrypt data IS dangerous (and very slow).
189                 public override byte[] DecryptValue (byte[] rgb) 
190                 {
191                         if (!rsa.IsCrtPossible)
192                                 throw new CryptographicException ("Incomplete private key - missing CRT.");
193
194                         return rsa.DecryptValue (rgb);
195                 }
196         
197                 public byte[] Encrypt (byte[] rgb, bool fOAEP) 
198                 {
199                         // choose between OAEP or PKCS#1 v.1.5 padding
200                         AsymmetricKeyExchangeFormatter fmt = null;
201                         if (fOAEP)
202                                 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
203                         else
204                                 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
205
206                         return fmt.CreateKeyExchange (rgb);
207                 }
208         
209                 // NOTE: Unlike MS we need this method
210                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
211                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
212                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
213                 // Using this method to encrypt data IS dangerous (and very slow).
214                 public override byte[] EncryptValue (byte[] rgb) 
215                 {
216                         return rsa.EncryptValue (rgb);
217                 }
218         
219                 public override RSAParameters ExportParameters (bool includePrivateParameters) 
220                 {
221                         if ((includePrivateParameters) && (!privateKeyExportable))
222                                 throw new CryptographicException ("cannot export private key");
223
224                         return rsa.ExportParameters (includePrivateParameters);
225                 }
226         
227                 public override void ImportParameters (RSAParameters parameters) 
228                 {
229                         rsa.ImportParameters (parameters);
230                 }
231         
232                 private HashAlgorithm GetHash (object halg) 
233                 {
234                         if (halg == null)
235                                 throw new ArgumentNullException ("halg");
236
237                         HashAlgorithm hash = null;
238                         if (halg is String)
239                                 hash = HashAlgorithm.Create ((String)halg);
240                         else if (halg is HashAlgorithm)
241                                 hash = (HashAlgorithm) halg;
242                         else if (halg is Type)
243                                 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
244                         else
245                                 throw new ArgumentException ("halg");
246
247                         return hash;
248                 }
249         
250                 // NOTE: this method can work with ANY configured (OID in machine.config) 
251                 // HashAlgorithm descendant
252                 public byte[] SignData (byte[] buffer, object halg) 
253                 {
254 #if NET_1_1
255                         if (buffer == null)
256                                 throw new ArgumentNullException ("buffer");
257 #endif
258                         return SignData (buffer, 0, buffer.Length, halg);
259                 }
260         
261                 // NOTE: this method can work with ANY configured (OID in machine.config) 
262                 // HashAlgorithm descendant
263                 public byte[] SignData (Stream inputStream, object halg) 
264                 {
265                         HashAlgorithm hash = GetHash (halg);
266                         byte[] toBeSigned = hash.ComputeHash (inputStream);
267                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
268                 }
269         
270                 // NOTE: this method can work with ANY configured (OID in machine.config) 
271                 // HashAlgorithm descendant
272                 public byte[] SignData (byte[] buffer, int offset, int count, object halg) 
273                 {
274                         HashAlgorithm hash = GetHash (halg);
275                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
276                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
277                 }
278         
279                 private string GetHashNameFromOID (string oid) 
280                 {
281                         switch (oid) {
282                                 case "1.3.14.3.2.26":
283                                         return "SHA1";
284                                 case "1.2.840.113549.2.5":
285                                         return "MD5";
286                                 default:
287                                         throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
288                         }
289                 }
290
291                 // LAMESPEC: str is not the hash name but an OID
292                 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
293                 // and 1.1 because there's no method to get a hash algorithm from an OID. 
294                 // However there's no such limit when using the [De]Formatter class.
295                 public byte[] SignHash (byte[] rgbHash, string str) 
296                 {
297                         if (rgbHash == null)
298                                 throw new ArgumentNullException ("rgbHash");
299 #if NET_2_0
300                         // Fx 2.0 defaults to the SHA-1
301                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
302 #else
303                         if (str == null)
304                                 throw new CryptographicException (Locale.GetText ("No OID specified"));
305                         string hashName = GetHashNameFromOID (str);
306 #endif
307                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
308                         return PKCS1.Sign_v15 (this, hash, rgbHash);
309                 }
310
311                 // NOTE: this method can work with ANY configured (OID in machine.config) 
312                 // HashAlgorithm descendant
313                 public bool VerifyData (byte[] buffer, object halg, byte[] signature) 
314                 {
315 #if NET_1_1
316                         if (buffer == null)
317                                 throw new ArgumentNullException ("buffer");
318 #endif
319                         if (signature == null)
320                                 throw new ArgumentNullException ("signature");
321
322                         HashAlgorithm hash = GetHash (halg);
323                         byte[] toBeVerified = hash.ComputeHash (buffer);
324                         return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
325                 }
326         
327                 // LAMESPEC: str is not the hash name but an OID
328                 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
329                 // and 1.1 because there's no method to get a hash algorithm from an OID. 
330                 // However there's no such limit when using the [De]Formatter class.
331                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
332                 {
333                         if (rgbHash == null) 
334                                 throw new ArgumentNullException ("rgbHash");
335                         if (rgbSignature == null)
336                                 throw new ArgumentNullException ("rgbSignature");
337 #if NET_2_0
338                         // Fx 2.0 defaults to the SHA-1
339                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
340 #else
341                         if (str == null)
342                                 throw new CryptographicException (Locale.GetText ("No OID specified"));
343                         string hashName = GetHashNameFromOID (str);
344 #endif
345                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
346                         return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
347                 }
348         
349                 protected override void Dispose (bool disposing) 
350                 {
351                         if (!m_disposed) {
352                                 // the key is persisted and we do not want it persisted
353                                 if ((persisted) && (!persistKey)) {
354                                         store.Remove ();        // delete the container
355                                 }
356                                 if (rsa != null)
357                                         rsa.Clear ();
358                                 // call base class 
359                                 // no need as they all are abstract before us
360                                 m_disposed = true;
361                         }
362                 }
363
364                 // private stuff
365
366                 private void OnKeyGenerated (object sender, EventArgs e) 
367                 {
368                         // the key isn't persisted and we want it persisted
369                         if ((persistKey) && (!persisted)) {
370                                 // save the current keypair
371                                 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
372                                 store.Save ();
373                                 persisted = true;
374                         }
375                 }
376 #if NET_2_0
377                 // ICspAsymmetricAlgorithm
378
379                 [MonoTODO ("call into KeyPairPersistence to get details")]
380                 [ComVisible (false)]
381                 public CspKeyContainerInfo CspKeyContainerInfo {
382                         get { return null; }
383                 }
384
385                 [MonoTODO ("call into CryptoConvert")]
386                 [ComVisible (false)]
387                 public byte[] ExportCspBlob (bool includePrivateParameters)
388                 {
389                         byte[] blob = null;
390                         if (includePrivateParameters)
391                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
392                         else
393                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
394
395                         // ALGID (bytes 4-7) - default is KEYX
396                         // 00 24 00 00 (for CALG_RSA_SIGN)
397                         // 00 A4 00 00 (for CALG_RSA_KEYX)
398                         blob [5] = 0xA4;
399                         return blob;
400                 }
401
402                 [MonoTODO ("call into CryptoConvert")]
403                 [ComVisible (false)]
404                 public void ImportCspBlob (byte[] rawData)
405                 {
406                         if (rawData == null)
407                                 throw new ArgumentNullException ("rawData");
408
409                         RSA rsa = CryptoConvert.FromCapiKeyBlob (rawData);
410                         if (rsa is RSACryptoServiceProvider) {
411                                 // default (if no change are present in machine.config)
412                                 RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
413                                 ImportParameters (rsap);
414                         } else {
415                                 // we can't know from RSA if the private key is available
416                                 try {
417                                         // so we try it...
418                                         RSAParameters rsap = rsa.ExportParameters (true);
419                                         ImportParameters (rsap);
420                                 }
421                                 catch {
422                                         // and fall back
423                                         RSAParameters rsap = rsa.ExportParameters (false);
424                                         ImportParameters (rsap);
425                                 }
426                         }
427                 }
428 #endif
429         }
430 }