Merge pull request #1218 from AndreyAkinshin/master
[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-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.Runtime.InteropServices;
34
35 using Mono.Security.Cryptography;
36
37 namespace System.Security.Cryptography {
38
39         [ComVisible (true)]
40         public sealed class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm {
41                 private const int PROV_RSA_FULL = 1;    // from WinCrypt.h
42                 private const int AT_KEYEXCHANGE = 1;
43                 private const int AT_SIGNATURE = 2;
44
45                 private KeyPairPersistence store;
46                 private bool persistKey;
47                 private bool persisted;
48         
49                 private bool privateKeyExportable = true; 
50                 private bool m_disposed;
51
52                 private RSAManaged rsa;
53         
54                 public RSACryptoServiceProvider ()
55                         : this (1024)
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                 }
66         
67                 public RSACryptoServiceProvider (CspParameters parameters) 
68                         : this (1024, parameters)
69                 {
70                         // no keypair generation done at this stage
71                 }
72         
73                 public RSACryptoServiceProvider (int dwKeySize) 
74                 {
75                         // Here it's clear that we need to generate a new keypair
76                         Common (dwKeySize, false);
77                         // no keypair generation done at this stage
78                 }
79         
80                 public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters) 
81                 {
82                         bool has_parameters = parameters != null;
83                         Common (dwKeySize, has_parameters);
84                         if (has_parameters)
85                                 Common (parameters);
86                         // no keypair generation done at this stage
87                 }
88         
89                 void Common (int dwKeySize, bool parameters) 
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 = parameters;
100                         if (parameters)
101                                 return;
102
103                         // no need to load - it cannot exists
104                         var p = new CspParameters (PROV_RSA_FULL);
105                         if (useMachineKeyStore)
106                                 p.Flags |= CspProviderFlags.UseMachineKeyStore;
107                         store = new KeyPairPersistence (p);
108                 }
109
110                 void Common (CspParameters p)
111                 {
112                         store = new KeyPairPersistence (p);
113                         bool exists = store.Load ();
114                         bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0;
115
116                         if (required && !exists)
117                                 throw new CryptographicException ("Keyset does not exist");
118
119                         if (store.KeyValue != null) {
120                                 persisted = true;
121                                 FromXmlString (store.KeyValue);
122                         }
123                 }
124
125                 private static bool useMachineKeyStore;
126
127                 public static bool UseMachineKeyStore {
128                         get { return useMachineKeyStore; }
129                         set { useMachineKeyStore = value; }
130                 }
131         
132                 ~RSACryptoServiceProvider () 
133                 {
134                         // Zeroize private key
135                         Dispose (false);
136                 }
137         
138                 public override string KeyExchangeAlgorithm {
139                         get { return "RSA-PKCS1-KeyEx"; }
140                 }
141         
142                 public override int KeySize {
143                         get { 
144                                 if (rsa == null)
145                                       return KeySizeValue; 
146                                 else
147                                       return rsa.KeySize;
148                         }
149                 }
150
151                 public bool PersistKeyInCsp {
152                         get { return persistKey; }
153                         set {
154                                 persistKey = value;
155                                 if (persistKey)
156                                         OnKeyGenerated (rsa, null);
157                         }
158                 }
159
160                 [ComVisible (false)]
161                 public 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 (rgb == null)
172                                 throw new ArgumentNullException("rgb");
173
174                         // size check -- must be at most the modulus size
175                         if (rgb.Length > (KeySize / 8))
176                                 throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8));
177                         
178                         if (m_disposed)
179                                 throw new ObjectDisposedException ("rsa");
180                         // choose between OAEP or PKCS#1 v.1.5 padding
181                         AsymmetricKeyExchangeDeformatter def = null;
182                         if (fOAEP)
183                                 def = new RSAOAEPKeyExchangeDeformatter (rsa);
184                         else
185                                 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
186
187                         return def.DecryptKeyExchange (rgb);
188                 }
189         
190                 // NOTE: Unlike MS we need this method
191                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
192                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
193                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
194                 // Using this method to decrypt data IS dangerous (and very slow).
195                 public override byte[] DecryptValue (byte[] rgb) 
196                 {
197                         if (!rsa.IsCrtPossible)
198                                 throw new CryptographicException ("Incomplete private key - missing CRT.");
199
200                         return rsa.DecryptValue (rgb);
201                 }
202         
203                 public byte[] Encrypt (byte[] rgb, bool fOAEP) 
204                 {
205                         // choose between OAEP or PKCS#1 v.1.5 padding
206                         AsymmetricKeyExchangeFormatter fmt = null;
207                         if (fOAEP)
208                                 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
209                         else
210                                 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
211
212                         return fmt.CreateKeyExchange (rgb);
213                 }
214         
215                 // NOTE: Unlike MS we need this method
216                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
217                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
218                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
219                 // Using this method to encrypt data IS dangerous (and very slow).
220                 public override byte[] EncryptValue (byte[] rgb) 
221                 {
222                         return rsa.EncryptValue (rgb);
223                 }
224         
225                 public override RSAParameters ExportParameters (bool includePrivateParameters) 
226                 {
227                         if ((includePrivateParameters) && (!privateKeyExportable))
228                                 throw new CryptographicException ("cannot export private key");
229
230                         var rsaParams = rsa.ExportParameters (includePrivateParameters);
231                         if (includePrivateParameters) {
232                                 // we want an ArgumentNullException is only the D is missing, but a
233                                 // CryptographicException if other parameters (CRT) are missings
234                                 if (rsaParams.D == null) {
235                                         throw new ArgumentNullException ("Missing D parameter for the private key.");
236                                 } else if ((rsaParams.P == null) || (rsaParams.Q == null) || (rsaParams.DP == null) ||
237                                         (rsaParams.DQ == null) || (rsaParams.InverseQ == null)) {
238                                         // note: we can import a private key, using FromXmlString,
239                                         // without the CRT parameters but we export it using ToXmlString!
240                                         throw new CryptographicException ("Missing some CRT parameters for the private key.");
241                                 }
242                         }
243
244                         return rsaParams;
245                 }
246         
247                 public override void ImportParameters (RSAParameters parameters) 
248                 {
249                         rsa.ImportParameters (parameters);
250                 }
251         
252                 private HashAlgorithm GetHash (object halg) 
253                 {
254                         if (halg == null)
255                                 throw new ArgumentNullException ("halg");
256
257                         HashAlgorithm hash = null;
258                         if (halg is String)
259                                 hash = GetHashFromString ((string) halg);
260                         else if (halg is HashAlgorithm)
261                                 hash = (HashAlgorithm) halg;
262                         else if (halg is Type)
263                                 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
264                         else
265                                 throw new ArgumentException ("halg");
266
267                         if (hash == null)
268                                 throw new ArgumentException (
269                                                 "Could not find provider for halg='" + halg + "'.",
270                                                 "halg");
271
272                         return hash;
273                 }
274
275                 private HashAlgorithm GetHashFromString (string name)
276                 {
277                         HashAlgorithm hash = HashAlgorithm.Create (name);
278                         if (hash != null)
279                                 return hash;
280                         try {
281                                 return HashAlgorithm.Create (GetHashNameFromOID (name));
282                         } catch (CryptographicException e) {
283                                 throw new ArgumentException (e.Message, "halg", e);
284                         }
285                 }
286         
287                 // NOTE: this method can work with ANY configured (OID in machine.config) 
288                 // HashAlgorithm descendant
289                 public byte[] SignData (byte[] buffer, object halg) 
290                 {
291                         if (buffer == null)
292                                 throw new ArgumentNullException ("buffer");
293                         return SignData (buffer, 0, buffer.Length, halg);
294                 }
295         
296                 // NOTE: this method can work with ANY configured (OID in machine.config) 
297                 // HashAlgorithm descendant
298                 public byte[] SignData (Stream inputStream, object halg) 
299                 {
300                         HashAlgorithm hash = GetHash (halg);
301                         byte[] toBeSigned = hash.ComputeHash (inputStream);
302                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
303                 }
304         
305                 // NOTE: this method can work with ANY configured (OID in machine.config) 
306                 // HashAlgorithm descendant
307                 public byte[] SignData (byte[] buffer, int offset, int count, object halg) 
308                 {
309                         HashAlgorithm hash = GetHash (halg);
310                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
311                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
312                 }
313         
314                 private string GetHashNameFromOID (string oid) 
315                 {
316                         switch (oid) {
317                         case "1.3.14.3.2.26":
318                                 return "SHA1";
319                         case "1.2.840.113549.2.5":
320                                 return "MD5";
321                         case "2.16.840.1.101.3.4.2.1":
322                                 return "SHA256";
323                         case "2.16.840.1.101.3.4.2.2":
324                                 return "SHA384";
325                         case "2.16.840.1.101.3.4.2.3":
326                                 return "SHA512";
327                         default:
328                                 throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
329                         }
330                 }
331
332                 public byte[] SignHash (byte[] rgbHash, string str) 
333                 {
334                         if (rgbHash == null)
335                                 throw new ArgumentNullException ("rgbHash");
336                         // Fx 2.0 defaults to the SHA-1
337                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
338                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
339                         return PKCS1.Sign_v15 (this, hash, rgbHash);
340                 }
341
342                 // NOTE: this method can work with ANY configured (OID in machine.config) 
343                 // HashAlgorithm descendant
344                 public bool VerifyData (byte[] buffer, object halg, byte[] signature) 
345                 {
346                         if (buffer == null)
347                                 throw new ArgumentNullException ("buffer");
348                         if (signature == null)
349                                 throw new ArgumentNullException ("signature");
350
351                         HashAlgorithm hash = GetHash (halg);
352                         byte[] toBeVerified = hash.ComputeHash (buffer);
353                         return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
354                 }
355         
356                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
357                 {
358                         if (rgbHash == null) 
359                                 throw new ArgumentNullException ("rgbHash");
360                         if (rgbSignature == null)
361                                 throw new ArgumentNullException ("rgbSignature");
362                         // Fx 2.0 defaults to the SHA-1
363                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
364                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
365                         return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
366                 }
367         
368                 protected override void Dispose (bool disposing) 
369                 {
370                         if (!m_disposed) {
371                                 // the key is persisted and we do not want it persisted
372                                 if ((persisted) && (!persistKey)) {
373                                         store.Remove ();        // delete the container
374                                 }
375                                 if (rsa != null)
376                                         rsa.Clear ();
377                                 // call base class 
378                                 // no need as they all are abstract before us
379                                 m_disposed = true;
380                         }
381                 }
382
383                 // private stuff
384
385                 private void OnKeyGenerated (object sender, EventArgs e) 
386                 {
387                         // the key isn't persisted and we want it persisted
388                         if ((persistKey) && (!persisted)) {
389                                 // save the current keypair
390                                 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
391                                 store.Save ();
392                                 persisted = true;
393                         }
394                 }
395                 // ICspAsymmetricAlgorithm
396
397                 [ComVisible (false)]
398                 public CspKeyContainerInfo CspKeyContainerInfo {
399                         get {
400                                 return new CspKeyContainerInfo(store.Parameters);
401                         }
402                 }
403
404                 [ComVisible (false)]
405                 public byte[] ExportCspBlob (bool includePrivateParameters)
406                 {
407                         byte[] blob = null;
408                         if (includePrivateParameters)
409                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
410                         else
411                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
412
413                         // ALGID (bytes 4-7) - default is KEYX
414                         // 00 24 00 00 (for CALG_RSA_SIGN)
415                         // 00 A4 00 00 (for CALG_RSA_KEYX)
416                         blob [5] = (byte) (((store != null) && (store.Parameters.KeyNumber == AT_SIGNATURE)) ? 0x24 : 0xA4);
417                         return blob;
418                 }
419
420                 [ComVisible (false)]
421                 public void ImportCspBlob (byte[] keyBlob)
422                 {
423                         if (keyBlob == null)
424                                 throw new ArgumentNullException ("keyBlob");
425
426                         RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
427                         if (rsa is RSACryptoServiceProvider) {
428                                 // default (if no change are present in machine.config)
429                                 RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
430                                 ImportParameters (rsap);
431                         } else {
432                                 // we can't know from RSA if the private key is available
433                                 try {
434                                         // so we try it...
435                                         RSAParameters rsap = rsa.ExportParameters (true);
436                                         ImportParameters (rsap);
437                                 }
438                                 catch {
439                                         // and fall back
440                                         RSAParameters rsap = rsa.ExportParameters (false);
441                                         ImportParameters (rsap);
442                                 }
443                         }
444
445                         var p = new CspParameters (PROV_RSA_FULL);
446                         p.KeyNumber = keyBlob [5] == 0x24 ? AT_SIGNATURE : AT_KEYEXCHANGE;
447                         if (useMachineKeyStore)
448                                 p.Flags |= CspProviderFlags.UseMachineKeyStore;
449                         store = new KeyPairPersistence (p);
450                 }
451         }
452 }