New test.
[mono.git] / mcs / class / Mono.Security / Mono.Security.Cryptography / RSAManaged.cs
1 //
2 // RSAManaged.cs - Implements the RSA algorithm.
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,2006 Novell, Inc (http://www.novell.com)
11 //
12 // Key generation translated from Bouncy Castle JCE (http://www.bouncycastle.org/)
13 // See bouncycastle.txt for license.
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using System;
36 using System.Security.Cryptography;
37 using System.Text;
38
39 using Mono.Math;
40
41 // Big chunks of code are coming from the original RSACryptoServiceProvider class.
42 // The class was refactored to :
43 // a.   ease integration of new hash algorithm (like MD2, RIPEMD160, ...);
44 // b.   provide better support for the coming SSL implementation (requires 
45 //      EncryptValue/DecryptValue) with, or without, Mono runtime/corlib;
46 // c.   provide an alternative RSA implementation for all Windows (like using 
47 //      OAEP without Windows XP).
48
49 namespace Mono.Security.Cryptography {
50
51 #if INSIDE_CORLIB
52         internal
53 #else
54         public
55 #endif
56         class RSAManaged : RSA {
57
58                 private const int defaultKeySize = 1024;
59
60                 private bool isCRTpossible = false;
61                 private bool keyBlinding = true;
62                 private bool keypairGenerated = false;
63                 private bool m_disposed = false;
64
65                 private BigInteger d;
66                 private BigInteger p;
67                 private BigInteger q;
68                 private BigInteger dp;
69                 private BigInteger dq;
70                 private BigInteger qInv;
71                 private BigInteger n;           // modulus
72                 private BigInteger e;
73
74                 public RSAManaged () : this (defaultKeySize)
75                 {
76                 }
77
78                 public RSAManaged (int keySize) 
79                 {
80                         LegalKeySizesValue = new KeySizes [1];
81                         LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
82                         base.KeySize = keySize;
83                 }
84
85                 ~RSAManaged () 
86                 {
87                         // Zeroize private key
88                         Dispose (false);
89                 }
90
91                 private void GenerateKeyPair () 
92                 {
93                         // p and q values should have a length of half the strength in bits
94                         int pbitlength = ((KeySize + 1) >> 1);
95                         int qbitlength = (KeySize - pbitlength);
96                         const uint uint_e = 17;
97                         e = uint_e; // fixed
98         
99                         // generate p, prime and (p-1) relatively prime to e
100                         for (;;) {
101                                 p = BigInteger.GeneratePseudoPrime (pbitlength);
102                                 if (p % uint_e != 1)
103                                         break;
104                         }
105                         // generate a modulus of the required length
106                         for (;;) {
107                                 // generate q, prime and (q-1) relatively prime to e,
108                                 // and not equal to p
109                                 for (;;) {
110                                         q = BigInteger.GeneratePseudoPrime (qbitlength);
111                                         if ((q % uint_e != 1) && (p != q))
112                                                 break;
113                                 }
114         
115                                 // calculate the modulus
116                                 n = p * q;
117                                 if (n.BitCount () == KeySize)
118                                         break;
119         
120                                 // if we get here our primes aren't big enough, make the largest
121                                 // of the two p and try again
122                                 if (p < q)
123                                         p = q;
124                         }
125         
126                         BigInteger pSub1 = (p - 1);
127                         BigInteger qSub1 = (q - 1);
128                         BigInteger phi = pSub1 * qSub1;
129         
130                         // calculate the private exponent
131                         d = e.ModInverse (phi);
132         
133                         // calculate the CRT factors
134                         dp = d % pSub1;
135                         dq = d % qSub1;
136                         qInv = q.ModInverse (p);
137         
138                         keypairGenerated = true;
139                         isCRTpossible = true;
140
141                         if (KeyGenerated != null)
142                                 KeyGenerated (this, null);
143                 }
144                 
145                 // overrides from RSA class
146
147                 public override int KeySize {
148                         get { 
149                                 // in case keypair hasn't been (yet) generated
150                                 if (keypairGenerated) {
151                                         int ks = n.BitCount ();
152                                         if ((ks & 7) != 0)
153                                                 ks = ks + (8 - (ks & 7));
154                                         return ks;
155                                 }
156                                 else
157                                         return base.KeySize;
158                         }
159                 }
160                 public override string KeyExchangeAlgorithm {
161                         get { return "RSA-PKCS1-KeyEx"; }
162                 }
163
164                 // note: when (if) we generate a keypair then it will have both
165                 // the public and private keys
166                 public bool PublicOnly {
167                         get { return (keypairGenerated && ((d == null) || (n == null))); }
168                 }
169
170                 public override string SignatureAlgorithm {
171                         get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
172                 }
173
174                 public override byte[] DecryptValue (byte[] rgb) 
175                 {
176                         if (m_disposed)
177                                 throw new ObjectDisposedException ("private key");
178
179                         // decrypt operation is used for signature
180                         if (!keypairGenerated)
181                                 GenerateKeyPair ();
182
183                         BigInteger input = new BigInteger (rgb);
184                         BigInteger r = null;
185
186                         // we use key blinding (by default) against timing attacks
187                         if (keyBlinding) {
188                                 // x = (r^e * g) mod n 
189                                 // *new* random number (so it's timing is also random)
190                                 r = BigInteger.GenerateRandom (n.BitCount ());
191                                 input = r.ModPow (e, n) * input % n;
192                         }
193
194                         BigInteger output;
195                         // decrypt (which uses the private key) can be 
196                         // optimized by using CRT (Chinese Remainder Theorem)
197                         if (isCRTpossible) {
198                                 // m1 = c^dp mod p
199                                 BigInteger m1 = input.ModPow (dp, p);
200                                 // m2 = c^dq mod q
201                                 BigInteger m2 = input.ModPow (dq, q);
202                                 BigInteger h;
203                                 if (m2 > m1) {
204                                         // thanks to benm!
205                                         h = p - ((m2 - m1) * qInv % p);
206                                         output = m2 + q * h;
207                                 } else {
208                                         // h = (m1 - m2) * qInv mod p
209                                         h = (m1 - m2) * qInv % p;
210                                         // m = m2 + q * h;
211                                         output = m2 + q * h;
212                                 }
213                         } else if (!PublicOnly) {
214                                 // m = c^d mod n
215                                 output = input.ModPow (d, n);
216                         } else {
217                                 throw new CryptographicException (Locale.GetText ("Missing private key to decrypt value."));
218                         }
219
220                         if (keyBlinding) {
221                                 // Complete blinding
222                                 // x^e / r mod n
223                                 output = output * r.ModInverse (n) % n;
224                                 r.Clear ();
225                         }
226
227                         // it's sometimes possible for the results to be a byte short
228                         // and this can break some software (see #79502) so we 0x00 pad the result
229                         byte[] result = GetPaddedValue (output);
230                         // zeroize values
231                         input.Clear (); 
232                         output.Clear ();
233                         return result;
234                 }
235
236                 public override byte[] EncryptValue (byte[] rgb) 
237                 {
238                         if (m_disposed)
239                                 throw new ObjectDisposedException ("public key");
240
241                         if (!keypairGenerated)
242                                 GenerateKeyPair ();
243
244                         BigInteger input = new BigInteger (rgb);
245                         BigInteger output = input.ModPow (e, n);
246                         // it's sometimes possible for the results to be a byte short
247                         // and this can break some software (see #79502) so we 0x00 pad the result
248                         byte[] result = GetPaddedValue (output);
249                         // zeroize value
250                         input.Clear (); 
251                         output.Clear ();
252                         return result;
253                 }
254
255                 public override RSAParameters ExportParameters (bool includePrivateParameters) 
256                 {
257                         if (m_disposed)
258                                 throw new ObjectDisposedException ("");
259
260                         if (!keypairGenerated)
261                                 GenerateKeyPair ();
262         
263                         RSAParameters param = new RSAParameters ();
264                         param.Exponent = e.GetBytes ();
265                         param.Modulus = n.GetBytes ();
266                         if (includePrivateParameters) {
267                                 // some parameters are required for exporting the private key
268                                 if (d == null)
269                                         throw new CryptographicException ("Missing private key");
270                                 param.D = d.GetBytes ();
271                                 // hack for bugzilla #57941 where D wasn't provided
272                                 if (param.D.Length != param.Modulus.Length) {
273                                         byte[] normalizedD = new byte [param.Modulus.Length];
274                                         Buffer.BlockCopy (param.D, 0, normalizedD, (normalizedD.Length - param.D.Length), param.D.Length);
275                                         param.D = normalizedD;
276                                 }
277                                 // but CRT parameters are optionals
278                                 if ((p != null) && (q != null) && (dp != null) && (dq != null) && (qInv != null)) {
279                                         // and we include them only if we have them all
280                                         param.P = p.GetBytes ();
281                                         param.Q = q.GetBytes ();
282                                         param.DP = dp.GetBytes ();
283                                         param.DQ = dq.GetBytes ();
284                                         param.InverseQ = qInv.GetBytes ();
285                                 }
286                         }
287                         return param;
288                 }
289
290                 public override void ImportParameters (RSAParameters parameters) 
291                 {
292                         if (m_disposed)
293                                 throw new ObjectDisposedException ("");
294
295                         // if missing "mandatory" parameters
296                         if (parameters.Exponent == null) 
297                                 throw new CryptographicException ("Missing Exponent");
298                         if (parameters.Modulus == null)
299                                 throw new CryptographicException ("Missing Modulus");
300         
301                         e = new BigInteger (parameters.Exponent);
302                         n = new BigInteger (parameters.Modulus);
303                         // only if the private key is present
304                         if (parameters.D != null)
305                                 d = new BigInteger (parameters.D);
306                         if (parameters.DP != null)
307                                 dp = new BigInteger (parameters.DP);
308                         if (parameters.DQ != null)
309                                 dq = new BigInteger (parameters.DQ);
310                         if (parameters.InverseQ != null)
311                                 qInv = new BigInteger (parameters.InverseQ);
312                         if (parameters.P != null)
313                                 p = new BigInteger (parameters.P);
314                         if (parameters.Q != null)
315                                 q = new BigInteger (parameters.Q);
316                         
317                         // we now have a keypair
318                         keypairGenerated = true;
319                         isCRTpossible = ((p != null) && (q != null) && (dp != null) && (dq != null) && (qInv != null));
320                 }
321
322                 protected override void Dispose (bool disposing) 
323                 {
324                         if (!m_disposed) {
325                                 // Always zeroize private key
326                                 if (d != null) {
327                                         d.Clear (); 
328                                         d = null;
329                                 }
330                                 if (p != null) {
331                                         p.Clear (); 
332                                         p = null;
333                                 }
334                                 if (q != null) {
335                                         q.Clear (); 
336                                         q = null;
337                                 }
338                                 if (dp != null) {
339                                         dp.Clear (); 
340                                         dp = null;
341                                 }
342                                 if (dq != null) {
343                                         dq.Clear (); 
344                                         dq = null;
345                                 }
346                                 if (qInv != null) {
347                                         qInv.Clear (); 
348                                         qInv = null;
349                                 }
350
351                                 if (disposing) {
352                                         // clear public key
353                                         if (e != null) {
354                                                 e.Clear (); 
355                                                 e = null;
356                                         }
357                                         if (n != null) {
358                                                 n.Clear (); 
359                                                 n = null;
360                                         }
361                                 }
362                         }
363                         // call base class 
364                         // no need as they all are abstract before us
365                         m_disposed = true;
366                 }
367
368                 public delegate void KeyGeneratedEventHandler (object sender, EventArgs e);
369
370                 public event KeyGeneratedEventHandler KeyGenerated;
371
372                 public override string ToXmlString (bool includePrivateParameters) 
373                 {
374                         StringBuilder sb = new StringBuilder ();
375                         RSAParameters rsaParams = ExportParameters (includePrivateParameters);
376                         try {
377                                 sb.Append ("<RSAKeyValue>");
378                                 
379                                 sb.Append ("<Modulus>");
380                                 sb.Append (Convert.ToBase64String (rsaParams.Modulus));
381                                 sb.Append ("</Modulus>");
382
383                                 sb.Append ("<Exponent>");
384                                 sb.Append (Convert.ToBase64String (rsaParams.Exponent));
385                                 sb.Append ("</Exponent>");
386
387                                 if (includePrivateParameters) {
388                                         if (rsaParams.P != null) {
389                                                 sb.Append ("<P>");
390                                                 sb.Append (Convert.ToBase64String (rsaParams.P));
391                                                 sb.Append ("</P>");
392                                         }
393                                         if (rsaParams.Q != null) {
394                                                 sb.Append ("<Q>");
395                                                 sb.Append (Convert.ToBase64String (rsaParams.Q));
396                                                 sb.Append ("</Q>");
397                                         }
398                                         if (rsaParams.DP != null) {
399                                                 sb.Append ("<DP>");
400                                                 sb.Append (Convert.ToBase64String (rsaParams.DP));
401                                                 sb.Append ("</DP>");
402                                         }
403                                         if (rsaParams.DQ != null) {
404                                                 sb.Append ("<DQ>");
405                                                 sb.Append (Convert.ToBase64String (rsaParams.DQ));
406                                                 sb.Append ("</DQ>");
407                                         }
408                                         if (rsaParams.InverseQ != null) {
409                                                 sb.Append ("<InverseQ>");
410                                                 sb.Append (Convert.ToBase64String (rsaParams.InverseQ));
411                                                 sb.Append ("</InverseQ>");
412                                         }
413                                         sb.Append ("<D>");
414                                         sb.Append (Convert.ToBase64String (rsaParams.D));
415                                         sb.Append ("</D>");
416                                 }
417                                 
418                                 sb.Append ("</RSAKeyValue>");
419                         }
420                         catch {
421                                 if (rsaParams.P != null)
422                                         Array.Clear (rsaParams.P, 0, rsaParams.P.Length);
423                                 if (rsaParams.Q != null)
424                                         Array.Clear (rsaParams.Q, 0, rsaParams.Q.Length);
425                                 if (rsaParams.DP != null)
426                                         Array.Clear (rsaParams.DP, 0, rsaParams.DP.Length);
427                                 if (rsaParams.DQ != null)
428                                         Array.Clear (rsaParams.DQ, 0, rsaParams.DQ.Length);
429                                 if (rsaParams.InverseQ != null)
430                                         Array.Clear (rsaParams.InverseQ, 0, rsaParams.InverseQ.Length);
431                                 if (rsaParams.D != null)
432                                         Array.Clear (rsaParams.D, 0, rsaParams.D.Length);
433                                 throw;
434                         }
435                         
436                         return sb.ToString ();
437                 }
438
439                 // internal for Mono 1.0.x in order to preserve public contract
440                 // they are public for Mono 1.1.x (for 1.2) as the API isn't froze ATM
441
442 #if NET_2_0
443                 public
444 #else
445                 internal
446 #endif
447                 bool UseKeyBlinding {
448                         get { return keyBlinding; }
449                         // you REALLY shoudn't touch this (true is fine ;-)
450                         set { keyBlinding = value; }
451                 }
452
453 #if NET_2_0
454                 public
455 #else
456                 internal
457 #endif
458                 bool IsCrtPossible {
459                         // either the key pair isn't generated (and will be 
460                         // generated with CRT parameters) or CRT is (or isn't)
461                         // possible (in case the key was imported)
462                         get { return (!keypairGenerated || isCRTpossible); }
463                 }
464
465                 private byte[] GetPaddedValue (BigInteger value)
466                 {
467                         byte[] result = value.GetBytes ();
468                         int length = (KeySize >> 3);
469                         if (result.Length >= length)
470                                 return result;
471
472                         // left-pad 0x00 value on the result (same integer, correct length)
473                         byte[] padded = new byte[length];
474                         Buffer.BlockCopy (result, 0, padded, (length - result.Length), result.Length);
475                         // temporary result may contain decrypted (plaintext) data, clear it
476                         Array.Clear (result, 0, result.Length);
477                         return padded;
478                 }
479         }
480 }