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 // (C) 2004 Novell (http://www.novell.com)
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 using Mono.Security.Cryptography;
42 namespace System.Security.Cryptography {
44 public sealed class RSACryptoServiceProvider : RSA {
46 private const int PROV_RSA_FULL = 1; // from WinCrypt.h
48 private KeyPairPersistence store;
49 private bool persistKey;
50 private bool persisted;
52 private bool privateKeyExportable = true;
53 private bool m_disposed;
55 private RSAManaged rsa;
57 public RSACryptoServiceProvider ()
59 // Here it's not clear if we need to generate a keypair
60 // (note: MS implementation generates a keypair in this case).
62 // (a) often use this constructor to import an existing keypair.
63 // (b) take a LOT of time to generate the RSA keypair
64 // So we'll generate the keypair only when (and if) it's being
65 // used (or exported). This should save us a lot of time (at
66 // least in the unit tests).
70 public RSACryptoServiceProvider (CspParameters parameters)
72 Common (1024, parameters);
73 // no keypair generation done at this stage
76 public RSACryptoServiceProvider (int dwKeySize)
78 // Here it's clear that we need to generate a new keypair
79 Common (dwKeySize, null);
80 // no keypair generation done at this stage
83 public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters)
85 Common (dwKeySize, parameters);
86 // no keypair generation done at this stage
89 private void Common (int dwKeySize, CspParameters p)
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 = (p != null);
101 p = new CspParameters (PROV_RSA_FULL);
103 if (useMachineKeyStore)
104 p.Flags |= CspProviderFlags.UseMachineKeyStore;
106 store = new KeyPairPersistence (p);
107 // no need to load - it cannot exists
110 store = new KeyPairPersistence (p);
112 if (store.KeyValue != null) {
114 this.FromXmlString (store.KeyValue);
120 private static bool useMachineKeyStore = false;
122 public static bool UseMachineKeyStore {
123 get { return useMachineKeyStore; }
124 set { useMachineKeyStore = value; }
128 ~RSACryptoServiceProvider ()
130 // Zeroize private key
134 public override string KeyExchangeAlgorithm {
135 get { return "RSA-PKCS1-KeyEx"; }
138 public override int KeySize {
147 public bool PersistKeyInCsp {
148 get { return persistKey; }
152 OnKeyGenerated (rsa, null);
156 #if (NET_1_0 || NET_1_1)
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)
173 throw new ObjectDisposedException ("rsa");
175 // choose between OAEP or PKCS#1 v.1.5 padding
176 AsymmetricKeyExchangeDeformatter def = null;
178 def = new RSAOAEPKeyExchangeDeformatter (rsa);
180 def = new RSAPKCS1KeyExchangeDeformatter (rsa);
182 return def.DecryptKeyExchange (rgb);
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)
192 return rsa.DecryptValue (rgb);
195 public byte[] Encrypt (byte[] rgb, bool fOAEP)
197 // choose between OAEP or PKCS#1 v.1.5 padding
198 AsymmetricKeyExchangeFormatter fmt = null;
200 fmt = new RSAOAEPKeyExchangeFormatter (rsa);
202 fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
204 return fmt.CreateKeyExchange (rgb);
207 // NOTE: Unlike MS we need this method
208 // LAMESPEC: Not available from MS .NET framework but MS don't tell
209 // why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
210 // only encrypt/decrypt session (secret) key using asymmetric keys.
211 // Using this method to encrypt data IS dangerous (and very slow).
212 public override byte[] EncryptValue (byte[] rgb)
214 return rsa.EncryptValue (rgb);
217 public override RSAParameters ExportParameters (bool includePrivateParameters)
219 if ((includePrivateParameters) && (!privateKeyExportable))
220 throw new CryptographicException ("cannot export private key");
222 return rsa.ExportParameters (includePrivateParameters);
225 public override void ImportParameters (RSAParameters parameters)
227 rsa.ImportParameters (parameters);
230 private HashAlgorithm GetHash (object halg)
233 throw new ArgumentNullException ("halg");
235 HashAlgorithm hash = null;
237 hash = HashAlgorithm.Create ((String)halg);
238 else if (halg is HashAlgorithm)
239 hash = (HashAlgorithm) halg;
240 else if (halg is Type)
241 hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
243 throw new ArgumentException ("halg");
248 // NOTE: this method can work with ANY configured (OID in machine.config)
249 // HashAlgorithm descendant
250 public byte[] SignData (byte[] buffer, object halg)
254 throw new ArgumentNullException ("buffer");
256 return SignData (buffer, 0, buffer.Length, halg);
259 // NOTE: this method can work with ANY configured (OID in machine.config)
260 // HashAlgorithm descendant
261 public byte[] SignData (Stream inputStream, object halg)
263 HashAlgorithm hash = GetHash (halg);
264 byte[] toBeSigned = hash.ComputeHash (inputStream);
265 return PKCS1.Sign_v15 (this, hash, toBeSigned);
268 // NOTE: this method can work with ANY configured (OID in machine.config)
269 // HashAlgorithm descendant
270 public byte[] SignData (byte[] buffer, int offset, int count, object halg)
272 HashAlgorithm hash = GetHash (halg);
273 byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
274 return PKCS1.Sign_v15 (this, hash, toBeSigned);
277 private string GetHashNameFromOID (string oid)
280 case "1.3.14.3.2.26":
282 case "1.2.840.113549.2.5":
285 throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
289 // LAMESPEC: str is not the hash name but an OID
290 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0
291 // and 1.1 because there's no method to get a hash algorithm from an OID.
292 // However there's no such limit when using the [De]Formatter class.
293 public byte[] SignHash (byte[] rgbHash, string str)
296 throw new ArgumentNullException ("rgbHash");
298 throw new CryptographicException (Locale.GetText ("No OID specified"));
300 HashAlgorithm hash = HashAlgorithm.Create (GetHashNameFromOID (str));
301 return PKCS1.Sign_v15 (this, hash, rgbHash);
304 // NOTE: this method can work with ANY configured (OID in machine.config)
305 // HashAlgorithm descendant
306 public bool VerifyData (byte[] buffer, object halg, byte[] signature)
310 throw new ArgumentNullException ("buffer");
312 if (signature == null)
313 throw new ArgumentNullException ("signature");
315 HashAlgorithm hash = GetHash (halg);
316 byte[] toBeVerified = hash.ComputeHash (buffer);
317 return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
320 // LAMESPEC: str is not the hash name but an OID
321 // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0
322 // and 1.1 because there's no method to get a hash algorithm from an OID.
323 // However there's no such limit when using the [De]Formatter class.
324 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
327 throw new ArgumentNullException ("rgbHash");
328 if (rgbSignature == null)
329 throw new ArgumentNullException ("rgbSignature");
331 HashAlgorithm hash = HashAlgorithm.Create (GetHashNameFromOID (str));
332 return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
335 protected override void Dispose (bool disposing)
338 // the key is persisted and we do not want it persisted
339 if ((persisted) && (!persistKey)) {
340 store.Remove (); // delete the container
345 // no need as they all are abstract before us
352 private void OnKeyGenerated (object sender, EventArgs e)
354 // the key isn't persisted and we want it persisted
355 if ((persistKey) && (!persisted)) {
356 // save the current keypair
357 store.KeyValue = this.ToXmlString (!rsa.PublicOnly);