2 // RSACryptoServiceProvider.cs: Handles an RSA implementation.
5 // Sebastien Pouliot <sebastien@ximian.com>
6 // Ben Maurer (bmaurer@users.sf.net)
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)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
33 using System.Runtime.InteropServices;
35 using Mono.Security.Cryptography;
37 namespace System.Security.Cryptography {
39 public partial class RSACryptoServiceProvider {
40 private const int PROV_RSA_FULL = 1; // from WinCrypt.h
41 private const int AT_KEYEXCHANGE = 1;
42 private const int AT_SIGNATURE = 2;
44 private KeyPairPersistence store;
45 private bool persistKey;
46 private bool persisted;
48 private bool privateKeyExportable = true;
49 private bool m_disposed;
51 private RSAManaged rsa;
53 public RSACryptoServiceProvider ()
56 // Here it's not clear if we need to generate a keypair
57 // (note: MS implementation generates a keypair in this case).
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).
66 public RSACryptoServiceProvider (CspParameters parameters)
67 : this (1024, parameters)
69 // no keypair generation done at this stage
72 public RSACryptoServiceProvider (int dwKeySize)
74 // Here it's clear that we need to generate a new keypair
75 Common (dwKeySize, false);
76 // no keypair generation done at this stage
79 public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters)
81 bool has_parameters = parameters != null;
82 Common (dwKeySize, has_parameters);
85 // no keypair generation done at this stage
88 void Common (int dwKeySize, bool parameters)
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;
95 rsa = new RSAManaged (KeySize);
96 rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
98 persistKey = parameters;
102 // no need to load - it cannot exists
103 var p = new CspParameters (PROV_RSA_FULL);
104 if (UseMachineKeyStore)
105 p.Flags |= CspProviderFlags.UseMachineKeyStore;
106 store = new KeyPairPersistence (p);
109 void Common (CspParameters p)
111 store = new KeyPairPersistence (p);
112 bool exists = store.Load ();
113 bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0;
115 if (required && !exists)
116 throw new CryptographicException ("Keyset does not exist");
118 if (store.KeyValue != null) {
120 FromXmlString (store.KeyValue);
124 ~RSACryptoServiceProvider ()
126 // Zeroize private key
130 public override string KeyExchangeAlgorithm {
131 get { return "RSA-PKCS1-KeyEx"; }
134 public override int KeySize {
143 public bool PersistKeyInCsp {
144 get { return persistKey; }
148 OnKeyGenerated (rsa, null);
153 public bool PublicOnly {
154 get { return rsa.PublicOnly; }
157 public byte[] Decrypt (byte[] rgb, bool fOAEP)
160 throw new ArgumentNullException("rgb");
162 // size check -- must be at most the modulus size
163 if (rgb.Length > (KeySize / 8))
164 throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8));
167 throw new ObjectDisposedException ("rsa");
168 // choose between OAEP or PKCS#1 v.1.5 padding
169 AsymmetricKeyExchangeDeformatter def = null;
171 def = new RSAOAEPKeyExchangeDeformatter (rsa);
173 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
175 return def.DecryptKeyExchange (rgb);
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)
185 if (!rsa.IsCrtPossible)
186 throw new CryptographicException ("Incomplete private key - missing CRT.");
188 return rsa.DecryptValue (rgb);
191 public byte[] Encrypt (byte[] rgb, bool fOAEP)
193 // choose between OAEP or PKCS#1 v.1.5 padding
194 AsymmetricKeyExchangeFormatter fmt = null;
196 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
198 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
200 return fmt.CreateKeyExchange (rgb);
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)
210 return rsa.EncryptValue (rgb);
213 public override RSAParameters ExportParameters (bool includePrivateParameters)
215 if ((includePrivateParameters) && (!privateKeyExportable))
216 throw new CryptographicException ("cannot export private key");
218 var rsaParams = rsa.ExportParameters (includePrivateParameters);
219 if (includePrivateParameters) {
220 // we want an ArgumentNullException is only the D is missing, but a
221 // CryptographicException if other parameters (CRT) are missings
222 if (rsaParams.D == null) {
223 throw new ArgumentNullException ("Missing D parameter for the private key.");
224 } else if ((rsaParams.P == null) || (rsaParams.Q == null) || (rsaParams.DP == null) ||
225 (rsaParams.DQ == null) || (rsaParams.InverseQ == null)) {
226 // note: we can import a private key, using FromXmlString,
227 // without the CRT parameters but we export it using ToXmlString!
228 throw new CryptographicException ("Missing some CRT parameters for the private key.");
235 public override void ImportParameters (RSAParameters parameters)
237 rsa.ImportParameters (parameters);
240 private HashAlgorithm GetHash (object halg)
243 throw new ArgumentNullException ("halg");
245 HashAlgorithm hash = null;
247 hash = GetHashFromString ((string) halg);
248 else if (halg is HashAlgorithm)
249 hash = (HashAlgorithm) halg;
250 else if (halg is Type)
251 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
253 throw new ArgumentException ("halg");
256 throw new ArgumentException (
257 "Could not find provider for halg='" + halg + "'.",
263 private HashAlgorithm GetHashFromString (string name)
265 HashAlgorithm hash = HashAlgorithm.Create (name);
269 return HashAlgorithm.Create (GetHashNameFromOID (name));
270 } catch (CryptographicException e) {
271 throw new ArgumentException (e.Message, "halg", e);
275 // NOTE: this method can work with ANY configured (OID in machine.config)
276 // HashAlgorithm descendant
277 public byte[] SignData (byte[] buffer, object halg)
280 throw new ArgumentNullException ("buffer");
281 return SignData (buffer, 0, buffer.Length, halg);
284 // NOTE: this method can work with ANY configured (OID in machine.config)
285 // HashAlgorithm descendant
286 public byte[] SignData (Stream inputStream, object halg)
288 HashAlgorithm hash = GetHash (halg);
289 byte[] toBeSigned = hash.ComputeHash (inputStream);
290 return PKCS1.Sign_v15 (this, hash, toBeSigned);
293 // NOTE: this method can work with ANY configured (OID in machine.config)
294 // HashAlgorithm descendant
295 public byte[] SignData (byte[] buffer, int offset, int count, object halg)
297 HashAlgorithm hash = GetHash (halg);
298 byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
299 return PKCS1.Sign_v15 (this, hash, toBeSigned);
302 private string GetHashNameFromOID (string oid)
305 case "1.3.14.3.2.26":
307 case "1.2.840.113549.2.5":
309 case "2.16.840.1.101.3.4.2.1":
311 case "2.16.840.1.101.3.4.2.2":
313 case "2.16.840.1.101.3.4.2.3":
316 throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
320 public byte[] SignHash (byte[] rgbHash, string str)
323 throw new ArgumentNullException ("rgbHash");
324 // Fx 2.0 defaults to the SHA-1
325 string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
326 HashAlgorithm hash = HashAlgorithm.Create (hashName);
327 return PKCS1.Sign_v15 (this, hash, rgbHash);
330 byte[] SignHash(byte[] rgbHash, int calgHash)
332 return PKCS1.Sign_v15 (this, InternalHashToHashAlgorithm (calgHash), rgbHash);
335 static HashAlgorithm InternalHashToHashAlgorithm (int calgHash)
338 case Constants.CALG_MD5:
339 return MD5.Create ();
340 case Constants.CALG_SHA1:
341 return SHA1.Create ();
342 case Constants.CALG_SHA_256:
343 return SHA256.Create ();
344 case Constants.CALG_SHA_384:
345 return SHA384.Create ();
346 case Constants.CALG_SHA_512:
347 return SHA512.Create ();
350 throw new NotImplementedException (calgHash.ToString ());
353 // NOTE: this method can work with ANY configured (OID in machine.config)
354 // HashAlgorithm descendant
355 public bool VerifyData (byte[] buffer, object halg, byte[] signature)
358 throw new ArgumentNullException ("buffer");
359 if (signature == null)
360 throw new ArgumentNullException ("signature");
362 HashAlgorithm hash = GetHash (halg);
363 byte[] toBeVerified = hash.ComputeHash (buffer);
364 return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
367 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
370 throw new ArgumentNullException ("rgbHash");
371 if (rgbSignature == null)
372 throw new ArgumentNullException ("rgbSignature");
373 // Fx 2.0 defaults to the SHA-1
374 string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
375 HashAlgorithm hash = HashAlgorithm.Create (hashName);
376 return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
379 bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature)
381 return PKCS1.Verify_v15 (this, InternalHashToHashAlgorithm (calgHash), rgbHash, rgbSignature);
384 protected override void Dispose (bool disposing)
387 // the key is persisted and we do not want it persisted
388 if ((persisted) && (!persistKey)) {
389 store.Remove (); // delete the container
394 // no need as they all are abstract before us
401 private void OnKeyGenerated (object sender, EventArgs e)
403 // the key isn't persisted and we want it persisted
404 if ((persistKey) && (!persisted)) {
405 // save the current keypair
406 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
411 // ICspAsymmetricAlgorithm
414 public CspKeyContainerInfo CspKeyContainerInfo {
416 return new CspKeyContainerInfo(store.Parameters);
421 public byte[] ExportCspBlob (bool includePrivateParameters)
424 if (includePrivateParameters)
425 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
427 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
429 // ALGID (bytes 4-7) - default is KEYX
430 // 00 24 00 00 (for CALG_RSA_SIGN)
431 // 00 A4 00 00 (for CALG_RSA_KEYX)
432 blob [5] = (byte) (((store != null) && (store.Parameters.KeyNumber == AT_SIGNATURE)) ? 0x24 : 0xA4);
437 public void ImportCspBlob (byte[] keyBlob)
440 throw new ArgumentNullException ("keyBlob");
442 RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
443 if (rsa is RSACryptoServiceProvider) {
444 // default (if no change are present in machine.config)
445 RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
446 ImportParameters (rsap);
448 // we can't know from RSA if the private key is available
451 RSAParameters rsap = rsa.ExportParameters (true);
452 ImportParameters (rsap);
456 RSAParameters rsap = rsa.ExportParameters (false);
457 ImportParameters (rsap);
461 var p = new CspParameters (PROV_RSA_FULL);
462 p.KeyNumber = keyBlob [5] == 0x24 ? AT_SIGNATURE : AT_KEYEXCHANGE;
463 if (UseMachineKeyStore)
464 p.Flags |= CspProviderFlags.UseMachineKeyStore;
465 store = new KeyPairPersistence (p);