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