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