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 {
40 public sealed class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm {
41 private const int PROV_RSA_FULL = 1; // from WinCrypt.h
42 private const int AT_KEYEXCHANGE = 1;
43 private const int AT_SIGNATURE = 2;
45 private KeyPairPersistence store;
46 private bool persistKey;
47 private bool persisted;
49 private bool privateKeyExportable = true;
50 private bool m_disposed;
52 private RSAManaged rsa;
54 public RSACryptoServiceProvider ()
57 // Here it's not clear if we need to generate a keypair
58 // (note: MS implementation generates a keypair in this case).
60 // (a) often use this constructor to import an existing keypair.
61 // (b) take a LOT of time to generate the RSA keypair
62 // So we'll generate the keypair only when (and if) it's being
63 // used (or exported). This should save us a lot of time (at
64 // least in the unit tests).
67 public RSACryptoServiceProvider (CspParameters parameters)
68 : this (1024, parameters)
70 // no keypair generation done at this stage
73 public RSACryptoServiceProvider (int dwKeySize)
75 // Here it's clear that we need to generate a new keypair
76 Common (dwKeySize, false);
77 // no keypair generation done at this stage
80 public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters)
82 bool has_parameters = parameters != null;
83 Common (dwKeySize, has_parameters);
86 // no keypair generation done at this stage
89 void Common (int dwKeySize, bool parameters)
91 // Microsoft RSA CSP can do between 384 and 16384 bits keypair
92 LegalKeySizesValue = new KeySizes [1];
93 LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
94 base.KeySize = dwKeySize;
96 rsa = new RSAManaged (KeySize);
97 rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
99 persistKey = parameters;
103 // no need to load - it cannot exists
104 var p = new CspParameters (PROV_RSA_FULL);
105 if (useMachineKeyStore)
106 p.Flags |= CspProviderFlags.UseMachineKeyStore;
107 store = new KeyPairPersistence (p);
110 void Common (CspParameters p)
112 store = new KeyPairPersistence (p);
113 bool exists = store.Load ();
114 bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0;
116 if (required && !exists)
117 throw new CryptographicException ("Keyset does not exist");
119 if (store.KeyValue != null) {
121 FromXmlString (store.KeyValue);
125 private static bool useMachineKeyStore;
127 public static bool UseMachineKeyStore {
128 get { return useMachineKeyStore; }
129 set { useMachineKeyStore = value; }
132 ~RSACryptoServiceProvider ()
134 // Zeroize private key
138 public override string KeyExchangeAlgorithm {
139 get { return "RSA-PKCS1-KeyEx"; }
142 public override int KeySize {
151 public bool PersistKeyInCsp {
152 get { return persistKey; }
156 OnKeyGenerated (rsa, null);
161 public bool PublicOnly {
162 get { return rsa.PublicOnly; }
165 public override string SignatureAlgorithm {
166 get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
169 public byte[] Decrypt (byte[] rgb, bool fOAEP)
172 throw new ObjectDisposedException ("rsa");
173 // choose between OAEP or PKCS#1 v.1.5 padding
174 AsymmetricKeyExchangeDeformatter def = null;
176 def = new RSAOAEPKeyExchangeDeformatter (rsa);
178 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
180 return def.DecryptKeyExchange (rgb);
183 // NOTE: Unlike MS we need this method
184 // LAMESPEC: Not available from MS .NET framework but MS don't tell
185 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
186 // only encrypt/decrypt session (secret) key using asymmetric keys.
187 // Using this method to decrypt data IS dangerous (and very slow).
188 public override byte[] DecryptValue (byte[] rgb)
190 if (!rsa.IsCrtPossible)
191 throw new CryptographicException ("Incomplete private key - missing CRT.");
193 return rsa.DecryptValue (rgb);
196 public byte[] Encrypt (byte[] rgb, bool fOAEP)
198 // choose between OAEP or PKCS#1 v.1.5 padding
199 AsymmetricKeyExchangeFormatter fmt = null;
201 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
203 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
205 return fmt.CreateKeyExchange (rgb);
208 // NOTE: Unlike MS we need this method
209 // LAMESPEC: Not available from MS .NET framework but MS don't tell
210 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
211 // only encrypt/decrypt session (secret) key using asymmetric keys.
212 // Using this method to encrypt data IS dangerous (and very slow).
213 public override byte[] EncryptValue (byte[] rgb)
215 return rsa.EncryptValue (rgb);
218 public override RSAParameters ExportParameters (bool includePrivateParameters)
220 if ((includePrivateParameters) && (!privateKeyExportable))
221 throw new CryptographicException ("cannot export private key");
223 return rsa.ExportParameters (includePrivateParameters);
226 public override void ImportParameters (RSAParameters parameters)
228 rsa.ImportParameters (parameters);
231 private HashAlgorithm GetHash (object halg)
234 throw new ArgumentNullException ("halg");
236 HashAlgorithm hash = null;
238 hash = GetHashFromString ((string) halg);
239 else if (halg is HashAlgorithm)
240 hash = (HashAlgorithm) halg;
241 else if (halg is Type)
242 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
244 throw new ArgumentException ("halg");
247 throw new ArgumentException (
248 "Could not find provider for halg='" + halg + "'.",
254 private HashAlgorithm GetHashFromString (string name)
256 HashAlgorithm hash = HashAlgorithm.Create (name);
260 return HashAlgorithm.Create (GetHashNameFromOID (name));
261 } catch (CryptographicException e) {
262 throw new ArgumentException (e.Message, "halg", e);
266 // NOTE: this method can work with ANY configured (OID in machine.config)
267 // HashAlgorithm descendant
268 public byte[] SignData (byte[] buffer, object halg)
271 throw new ArgumentNullException ("buffer");
272 return SignData (buffer, 0, buffer.Length, halg);
275 // NOTE: this method can work with ANY configured (OID in machine.config)
276 // HashAlgorithm descendant
277 public byte[] SignData (Stream inputStream, object halg)
279 HashAlgorithm hash = GetHash (halg);
280 byte[] toBeSigned = hash.ComputeHash (inputStream);
281 return PKCS1.Sign_v15 (this, hash, toBeSigned);
284 // NOTE: this method can work with ANY configured (OID in machine.config)
285 // HashAlgorithm descendant
286 public byte[] SignData (byte[] buffer, int offset, int count, object halg)
288 HashAlgorithm hash = GetHash (halg);
289 byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
290 return PKCS1.Sign_v15 (this, hash, toBeSigned);
293 private string GetHashNameFromOID (string oid)
296 case "1.3.14.3.2.26":
298 case "1.2.840.113549.2.5":
300 case "2.16.840.1.101.3.4.2.1":
302 case "2.16.840.1.101.3.4.2.2":
304 case "2.16.840.1.101.3.4.2.3":
307 throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
311 public byte[] SignHash (byte[] rgbHash, string str)
314 throw new ArgumentNullException ("rgbHash");
315 // Fx 2.0 defaults to the SHA-1
316 string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
317 HashAlgorithm hash = HashAlgorithm.Create (hashName);
318 return PKCS1.Sign_v15 (this, hash, rgbHash);
321 // NOTE: this method can work with ANY configured (OID in machine.config)
322 // HashAlgorithm descendant
323 public bool VerifyData (byte[] buffer, object halg, byte[] signature)
326 throw new ArgumentNullException ("buffer");
327 if (signature == null)
328 throw new ArgumentNullException ("signature");
330 HashAlgorithm hash = GetHash (halg);
331 byte[] toBeVerified = hash.ComputeHash (buffer);
332 return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
335 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
338 throw new ArgumentNullException ("rgbHash");
339 if (rgbSignature == null)
340 throw new ArgumentNullException ("rgbSignature");
341 // Fx 2.0 defaults to the SHA-1
342 string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
343 HashAlgorithm hash = HashAlgorithm.Create (hashName);
344 return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
347 protected override void Dispose (bool disposing)
350 // the key is persisted and we do not want it persisted
351 if ((persisted) && (!persistKey)) {
352 store.Remove (); // delete the container
357 // no need as they all are abstract before us
364 private void OnKeyGenerated (object sender, EventArgs e)
366 // the key isn't persisted and we want it persisted
367 if ((persistKey) && (!persisted)) {
368 // save the current keypair
369 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
374 // ICspAsymmetricAlgorithm
377 public CspKeyContainerInfo CspKeyContainerInfo {
379 return new CspKeyContainerInfo(store.Parameters);
384 public byte[] ExportCspBlob (bool includePrivateParameters)
387 if (includePrivateParameters)
388 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
390 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
392 // ALGID (bytes 4-7) - default is KEYX
393 // 00 24 00 00 (for CALG_RSA_SIGN)
394 // 00 A4 00 00 (for CALG_RSA_KEYX)
395 blob [5] = (byte) (((store != null) && (store.Parameters.KeyNumber == AT_SIGNATURE)) ? 0x24 : 0xA4);
400 public void ImportCspBlob (byte[] keyBlob)
403 throw new ArgumentNullException ("keyBlob");
405 RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
406 if (rsa is RSACryptoServiceProvider) {
407 // default (if no change are present in machine.config)
408 RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
409 ImportParameters (rsap);
411 // we can't know from RSA if the private key is available
414 RSAParameters rsap = rsa.ExportParameters (true);
415 ImportParameters (rsap);
419 RSAParameters rsap = rsa.ExportParameters (false);
420 ImportParameters (rsap);
424 var p = new CspParameters (PROV_RSA_FULL);
425 p.KeyNumber = keyBlob [5] == 0x24 ? AT_SIGNATURE : AT_KEYEXCHANGE;
426 if (useMachineKeyStore)
427 p.Flags |= CspProviderFlags.UseMachineKeyStore;
428 store = new KeyPairPersistence (p);