New tests.
[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                                 store.Load ();
109                                 if (store.KeyValue != null) {
110                                         persisted = true;
111                                         this.FromXmlString (store.KeyValue);
112                                 }
113                         }
114                 }
115
116 #if NET_1_1
117                 private static bool useMachineKeyStore = false;
118
119                 public static bool UseMachineKeyStore {
120                         get { return useMachineKeyStore; }
121                         set { useMachineKeyStore = value; }
122                 }
123 #endif
124         
125                 ~RSACryptoServiceProvider () 
126                 {
127                         // Zeroize private key
128                         Dispose (false);
129                 }
130         
131                 public override string KeyExchangeAlgorithm {
132                         get { return "RSA-PKCS1-KeyEx"; }
133                 }
134         
135                 public override int KeySize {
136                         get { 
137                                 if (rsa == null)
138                                       return KeySizeValue; 
139                                 else
140                                       return rsa.KeySize;
141                         }
142                 }
143
144                 public bool PersistKeyInCsp {
145                         get { return persistKey; }
146                         set {
147                                 persistKey = value;
148                                 if (persistKey)
149                                         OnKeyGenerated (rsa, null);
150                         }
151                 }
152
153                 [ComVisible (false)]
154                 public bool PublicOnly {
155                         get { return rsa.PublicOnly; }
156                 }
157         
158                 public override string SignatureAlgorithm {
159                         get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
160                 }
161         
162                 public byte[] Decrypt (byte[] rgb, bool fOAEP) 
163                 {
164 #if NET_1_1
165                         if (m_disposed)
166                                 throw new ObjectDisposedException ("rsa");
167 #endif
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                         return rsa.ExportParameters (includePrivateParameters);
219                 }
220         
221                 public override void ImportParameters (RSAParameters parameters) 
222                 {
223                         rsa.ImportParameters (parameters);
224                 }
225         
226                 private HashAlgorithm GetHash (object halg) 
227                 {
228                         if (halg == null)
229                                 throw new ArgumentNullException ("halg");
230
231                         HashAlgorithm hash = null;
232                         if (halg is String)
233                                 hash = HashAlgorithm.Create ((String)halg);
234                         else if (halg is HashAlgorithm)
235                                 hash = (HashAlgorithm) halg;
236                         else if (halg is Type)
237                                 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
238                         else
239                                 throw new ArgumentException ("halg");
240
241                         return hash;
242                 }
243         
244                 // NOTE: this method can work with ANY configured (OID in machine.config) 
245                 // HashAlgorithm descendant
246                 public byte[] SignData (byte[] buffer, object halg) 
247                 {
248 #if NET_1_1
249                         if (buffer == null)
250                                 throw new ArgumentNullException ("buffer");
251 #endif
252                         return SignData (buffer, 0, buffer.Length, halg);
253                 }
254         
255                 // NOTE: this method can work with ANY configured (OID in machine.config) 
256                 // HashAlgorithm descendant
257                 public byte[] SignData (Stream inputStream, object halg) 
258                 {
259                         HashAlgorithm hash = GetHash (halg);
260                         byte[] toBeSigned = hash.ComputeHash (inputStream);
261                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
262                 }
263         
264                 // NOTE: this method can work with ANY configured (OID in machine.config) 
265                 // HashAlgorithm descendant
266                 public byte[] SignData (byte[] buffer, int offset, int count, object halg) 
267                 {
268                         HashAlgorithm hash = GetHash (halg);
269                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
270                         return PKCS1.Sign_v15 (this, hash, toBeSigned);
271                 }
272         
273                 private string GetHashNameFromOID (string oid) 
274                 {
275                         switch (oid) {
276                                 case "1.3.14.3.2.26":
277                                         return "SHA1";
278                                 case "1.2.840.113549.2.5":
279                                         return "MD5";
280                                 default:
281                                         throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
282                         }
283                 }
284
285                 // LAMESPEC: str is not the hash name but an OID
286                 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
287                 // and 1.1 because there's no method to get a hash algorithm from an OID. 
288                 // However there's no such limit when using the [De]Formatter class.
289                 public byte[] SignHash (byte[] rgbHash, string str) 
290                 {
291                         if (rgbHash == null)
292                                 throw new ArgumentNullException ("rgbHash");
293                         // Fx 2.0 defaults to the SHA-1
294                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
295                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
296                         return PKCS1.Sign_v15 (this, hash, rgbHash);
297                 }
298
299                 // NOTE: this method can work with ANY configured (OID in machine.config) 
300                 // HashAlgorithm descendant
301                 public bool VerifyData (byte[] buffer, object halg, byte[] signature) 
302                 {
303                         if (buffer == null)
304                                 throw new ArgumentNullException ("buffer");
305                         if (signature == null)
306                                 throw new ArgumentNullException ("signature");
307
308                         HashAlgorithm hash = GetHash (halg);
309                         byte[] toBeVerified = hash.ComputeHash (buffer);
310                         return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
311                 }
312         
313                 // LAMESPEC: str is not the hash name but an OID
314                 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
315                 // and 1.1 because there's no method to get a hash algorithm from an OID. 
316                 // However there's no such limit when using the [De]Formatter class.
317                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
318                 {
319                         if (rgbHash == null) 
320                                 throw new ArgumentNullException ("rgbHash");
321                         if (rgbSignature == null)
322                                 throw new ArgumentNullException ("rgbSignature");
323                         // Fx 2.0 defaults to the SHA-1
324                         string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
325                         HashAlgorithm hash = HashAlgorithm.Create (hashName);
326                         return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
327                 }
328         
329                 protected override void Dispose (bool disposing) 
330                 {
331                         if (!m_disposed) {
332                                 // the key is persisted and we do not want it persisted
333                                 if ((persisted) && (!persistKey)) {
334                                         store.Remove ();        // delete the container
335                                 }
336                                 if (rsa != null)
337                                         rsa.Clear ();
338                                 // call base class 
339                                 // no need as they all are abstract before us
340                                 m_disposed = true;
341                         }
342                 }
343
344                 // private stuff
345
346                 private void OnKeyGenerated (object sender, EventArgs e) 
347                 {
348                         // the key isn't persisted and we want it persisted
349                         if ((persistKey) && (!persisted)) {
350                                 // save the current keypair
351                                 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
352                                 store.Save ();
353                                 persisted = true;
354                         }
355                 }
356                 // ICspAsymmetricAlgorithm
357
358                 [MonoTODO ("Always return null")]
359                 // FIXME: call into KeyPairPersistence to get details
360                 [ComVisible (false)]
361                 public CspKeyContainerInfo CspKeyContainerInfo {
362                         get { return null; }
363                 }
364
365                 [ComVisible (false)]
366                 public byte[] ExportCspBlob (bool includePrivateParameters)
367                 {
368                         byte[] blob = null;
369                         if (includePrivateParameters)
370                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
371                         else
372                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
373
374                         // ALGID (bytes 4-7) - default is KEYX
375                         // 00 24 00 00 (for CALG_RSA_SIGN)
376                         // 00 A4 00 00 (for CALG_RSA_KEYX)
377                         blob [5] = 0xA4;
378                         return blob;
379                 }
380
381                 [ComVisible (false)]
382                 public void ImportCspBlob (byte[] keyBlob)
383                 {
384                         if (keyBlob == null)
385                                 throw new ArgumentNullException ("keyBlob");
386
387                         RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
388                         if (rsa is RSACryptoServiceProvider) {
389                                 // default (if no change are present in machine.config)
390                                 RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
391                                 ImportParameters (rsap);
392                         } else {
393                                 // we can't know from RSA if the private key is available
394                                 try {
395                                         // so we try it...
396                                         RSAParameters rsap = rsa.ExportParameters (true);
397                                         ImportParameters (rsap);
398                                 }
399                                 catch {
400                                         // and fall back
401                                         RSAParameters rsap = rsa.ExportParameters (false);
402                                         ImportParameters (rsap);
403                                 }
404                         }
405                 }
406         }
407 }
408
409 #endif
410