Merge pull request #588 from Daniel15/bug-10872
[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                 {
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 (useMachineKeyStore)
100                                         p.Flags |= CspProviderFlags.UseMachineKeyStore;
101                                 store = new KeyPairPersistence (p);
102                                 // no need to load - it cannot exists
103                         }
104                         else {
105                                 store = new KeyPairPersistence (p);
106                                 bool exists = store.Load ();
107                                 bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0;
108
109                                 if (required && !exists)
110                                         throw new CryptographicException ("Keyset does not exist");
111
112                                 if (store.KeyValue != null) {
113                                         persisted = true;
114                                         this.FromXmlString (store.KeyValue);
115                                 }
116                         }
117                 }
118
119                 private static bool useMachineKeyStore;
120
121                 public static bool UseMachineKeyStore {
122                         get { return useMachineKeyStore; }
123                         set { useMachineKeyStore = value; }
124                 }
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                 [ComVisible (false)]
155                 public bool PublicOnly {
156                         get { return rsa.PublicOnly; }
157                 }
158         
159                 public override string SignatureAlgorithm {
160                         get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
161                 }
162         
163                 public byte[] Decrypt (byte[] rgb, bool fOAEP) 
164                 {
165                         if (m_disposed)
166                                 throw new ObjectDisposedException ("rsa");
167                         // choose between OAEP or PKCS#1 v.1.5 padding
168                         AsymmetricKeyExchangeDeformatter def = null;
169                         if (fOAEP)
170                                 def = new RSAOAEPKeyExchangeDeformatter (rsa);
171                         else
172                                 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
173
174                         return def.DecryptKeyExchange (rgb);
175                 }
176         
177                 // NOTE: Unlike MS we need this method
178                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
179                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
180                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
181                 // Using this method to decrypt data IS dangerous (and very slow).
182                 public override byte[] DecryptValue (byte[] rgb) 
183                 {
184                         if (!rsa.IsCrtPossible)
185                                 throw new CryptographicException ("Incomplete private key - missing CRT.");
186
187                         return rsa.DecryptValue (rgb);
188                 }
189         
190                 public byte[] Encrypt (byte[] rgb, bool fOAEP) 
191                 {
192                         // choose between OAEP or PKCS#1 v.1.5 padding
193                         AsymmetricKeyExchangeFormatter fmt = null;
194                         if (fOAEP)
195                                 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
196                         else
197                                 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
198
199                         return fmt.CreateKeyExchange (rgb);
200                 }
201         
202                 // NOTE: Unlike MS we need this method
203                 // LAMESPEC: Not available from MS .NET framework but MS don't tell
204                 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
205                 // only encrypt/decrypt session (secret) key using asymmetric keys. 
206                 // Using this method to encrypt data IS dangerous (and very slow).
207                 public override byte[] EncryptValue (byte[] rgb) 
208                 {
209                         return rsa.EncryptValue (rgb);
210                 }
211         
212                 public override RSAParameters ExportParameters (bool includePrivateParameters) 
213                 {
214                         if ((includePrivateParameters) && (!privateKeyExportable))
215                                 throw new CryptographicException ("cannot export private key");
216
217                         return rsa.ExportParameters (includePrivateParameters);
218                 }
219         
220                 public override void ImportParameters (RSAParameters parameters) 
221                 {
222                         rsa.ImportParameters (parameters);
223                 }
224         
225                 private HashAlgorithm GetHash (object halg) 
226                 {
227                         if (halg == null)
228                                 throw new ArgumentNullException ("halg");
229
230                         HashAlgorithm hash = null;
231                         if (halg is String)
232                                 hash = HashAlgorithm.Create ((String)halg);
233                         else if (halg is HashAlgorithm)
234                                 hash = (HashAlgorithm) halg;
235                         else if (halg is Type)
236                                 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
237                         else
238                                 throw new ArgumentException ("halg");
239
240                         return hash;
241                 }
242         
243                 // NOTE: this method can work with ANY configured (OID in machine.config) 
244                 // HashAlgorithm descendant
245                 public byte[] SignData (byte[] buffer, object halg) 
246                 {
247                         if (buffer == null)
248                                 throw new ArgumentNullException ("buffer");
249                         return SignData (buffer, 0, buffer.Length, halg);
250                 }
251         
252                 // NOTE: this method can work with ANY configured (OID in machine.config) 
253                 // HashAlgorithm descendant
254                 public byte[] SignData (Stream inputStream, object halg) 
255                 {
256                         HashAlgorithm hash = GetHash (halg);
257                         byte[] toBeSigned = hash.ComputeHash (inputStream);
258                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
259                 }
260         
261                 // NOTE: this method can work with ANY configured (OID in machine.config) 
262                 // HashAlgorithm descendant
263                 public byte[] SignData (byte[] buffer, int offset, int count, object halg) 
264                 {
265                         HashAlgorithm hash = GetHash (halg);
266                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
267                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
268                 }
269         
270                 private string GetHashNameFromOID (string oid) 
271                 {
272                         switch (oid) {
273                         case "1.3.14.3.2.26":
274                                 return "SHA1";
275                         case "1.2.840.113549.2.5":
276                                 return "MD5";
277                         case "2.16.840.1.101.3.4.2.1":
278                                 return "SHA256";
279                         case "2.16.840.1.101.3.4.2.2":
280                                 return "SHA384";
281                         case "2.16.840.1.101.3.4.2.3":
282                                 return "SHA512";
283                         default:
284                                 throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
285                         }
286                 }
287
288                 public byte[] SignHash (byte[] rgbHash, string str) 
289                 {
290                         if (rgbHash == null)
291                                 throw new ArgumentNullException ("rgbHash");
292                         // Fx 2.0 defaults to the SHA-1
293                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
294                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
295                         return PKCS1.Sign_v15 (this, hash, rgbHash);
296                 }
297
298                 // NOTE: this method can work with ANY configured (OID in machine.config) 
299                 // HashAlgorithm descendant
300                 public bool VerifyData (byte[] buffer, object halg, byte[] signature) 
301                 {
302                         if (buffer == null)
303                                 throw new ArgumentNullException ("buffer");
304                         if (signature == null)
305                                 throw new ArgumentNullException ("signature");
306
307                         HashAlgorithm hash = GetHash (halg);
308                         byte[] toBeVerified = hash.ComputeHash (buffer);
309                         return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
310                 }
311         
312                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
313                 {
314                         if (rgbHash == null) 
315                                 throw new ArgumentNullException ("rgbHash");
316                         if (rgbSignature == null)
317                                 throw new ArgumentNullException ("rgbSignature");
318                         // Fx 2.0 defaults to the SHA-1
319                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
320                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
321                         return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
322                 }
323         
324                 protected override void Dispose (bool disposing) 
325                 {
326                         if (!m_disposed) {
327                                 // the key is persisted and we do not want it persisted
328                                 if ((persisted) && (!persistKey)) {
329                                         store.Remove ();        // delete the container
330                                 }
331                                 if (rsa != null)
332                                         rsa.Clear ();
333                                 // call base class 
334                                 // no need as they all are abstract before us
335                                 m_disposed = true;
336                         }
337                 }
338
339                 // private stuff
340
341                 private void OnKeyGenerated (object sender, EventArgs e) 
342                 {
343                         // the key isn't persisted and we want it persisted
344                         if ((persistKey) && (!persisted)) {
345                                 // save the current keypair
346                                 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
347                                 store.Save ();
348                                 persisted = true;
349                         }
350                 }
351                 // ICspAsymmetricAlgorithm
352
353                 [ComVisible (false)]
354                 public CspKeyContainerInfo CspKeyContainerInfo {
355                         get {
356                                 return new CspKeyContainerInfo(store.Parameters);
357                         }
358                 }
359
360                 [ComVisible (false)]
361                 public byte[] ExportCspBlob (bool includePrivateParameters)
362                 {
363                         byte[] blob = null;
364                         if (includePrivateParameters)
365                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
366                         else
367                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
368
369                         // ALGID (bytes 4-7) - default is KEYX
370                         // 00 24 00 00 (for CALG_RSA_SIGN)
371                         // 00 A4 00 00 (for CALG_RSA_KEYX)
372                         blob [5] = (byte) (((store != null) && (store.Parameters.KeyNumber == AT_SIGNATURE)) ? 0x24 : 0xA4);
373                         return blob;
374                 }
375
376                 [ComVisible (false)]
377                 public void ImportCspBlob (byte[] keyBlob)
378                 {
379                         if (keyBlob == null)
380                                 throw new ArgumentNullException ("keyBlob");
381
382                         RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
383                         if (rsa is RSACryptoServiceProvider) {
384                                 // default (if no change are present in machine.config)
385                                 RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
386                                 ImportParameters (rsap);
387                         } else {
388                                 // we can't know from RSA if the private key is available
389                                 try {
390                                         // so we try it...
391                                         RSAParameters rsap = rsa.ExportParameters (true);
392                                         ImportParameters (rsap);
393                                 }
394                                 catch {
395                                         // and fall back
396                                         RSAParameters rsap = rsa.ExportParameters (false);
397                                         ImportParameters (rsap);
398                                 }
399                         }
400
401                         var p = new CspParameters (PROV_RSA_FULL);
402                         p.KeyNumber = keyBlob [5] == 0x24 ? AT_SIGNATURE : AT_KEYEXCHANGE;
403                         if (useMachineKeyStore)
404                                 p.Flags |= CspProviderFlags.UseMachineKeyStore;
405                         store = new KeyPairPersistence (p);
406                 }
407         }
408 }