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