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