Merge pull request #216 from ilkerde/master
[mono.git] / mcs / class / corlib / System.Security.Cryptography / RSACryptoServiceProvider.cs
index aeed6e71e94d6e9819f5c80187494c1a8be17bc1..41bc61d907fef382eb0aa732108afbc52f5037ad 100644 (file)
@@ -7,23 +7,43 @@
 //
 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
 // Portions (C) 2003 Ben Maurer
-// (C) 2004 Novell (http://www.novell.com)
+// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
 //
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+#if !MOONLIGHT
 
-using System;
 using System.IO;
+using System.Runtime.InteropServices;
 
-using Mono.Math;
 using Mono.Security.Cryptography;
 
 namespace System.Security.Cryptography {
 
-       public sealed class RSACryptoServiceProvider : RSA {
-       
+       [ComVisible (true)]
+       public sealed class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm {
                private const int PROV_RSA_FULL = 1;    // from WinCrypt.h
 
                private KeyPairPersistence store;
-               private bool persistKey = true;
+               private bool persistKey;
                private bool persisted;
        
                private bool privateKeyExportable = true; 
@@ -65,9 +85,18 @@ namespace System.Security.Cryptography {
        
                private void Common (int dwKeySize, CspParameters p) 
                {
+                       // Microsoft RSA CSP can do between 384 and 16384 bits keypair
+                       LegalKeySizesValue = new KeySizes [1];
+                       LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
+                       base.KeySize = dwKeySize;
+
+                       rsa = new RSAManaged (KeySize);
+                       rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
+
+                       persistKey = (p != null);
                        if (p == null) {
                                p = new CspParameters (PROV_RSA_FULL);
-#if ! NET_1_0
+#if NET_1_1
                                if (useMachineKeyStore)
                                        p.Flags |= CspProviderFlags.UseMachineKeyStore;
 #endif
@@ -76,23 +105,20 @@ namespace System.Security.Cryptography {
                        }
                        else {
                                store = new KeyPairPersistence (p);
-                               store.Load ();
+                               bool exists = store.Load ();
+                               bool required = (p.Flags & CspProviderFlags.UseExistingKey) != 0;
+
+                               if (required && !exists)
+                                       throw new CryptographicException ("Keyset does not exist");
+
                                if (store.KeyValue != null) {
                                        persisted = true;
                                        this.FromXmlString (store.KeyValue);
                                }
                        }
-
-                       // Microsoft RSA CSP can do between 384 and 16384 bits keypair
-                       LegalKeySizesValue = new KeySizes [1];
-                       LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
-                       base.KeySize = dwKeySize;
-
-                       rsa = new RSAManaged (KeySize);
-                       rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
                }
 
-#if ! NET_1_0
+#if NET_1_1
                private static bool useMachineKeyStore = false;
 
                public static bool UseMachineKeyStore {
@@ -123,23 +149,14 @@ namespace System.Security.Cryptography {
                public bool PersistKeyInCsp {
                        get { return persistKey; }
                        set {
-                               if (value) {
-                                       OnKeyGenerated (rsa);
-                               }
-                               else {
-                                       // delete the container
-                                       store.Remove ();
-                               }
                                persistKey = value;
+                               if (persistKey)
+                                       OnKeyGenerated (rsa, null);
                        }
                }
 
-#if (NET_1_0 || NET_1_1)
-               internal
-#else
-               public 
-#endif
-               bool PublicOnly {
+               [ComVisible (false)]
+               public bool PublicOnly {
                        get { return rsa.PublicOnly; }
                }
        
@@ -170,6 +187,9 @@ namespace System.Security.Cryptography {
                // Using this method to decrypt data IS dangerous (and very slow).
                public override byte[] DecryptValue (byte[] rgb) 
                {
+                       if (!rsa.IsCrtPossible)
+                               throw new CryptographicException ("Incomplete private key - missing CRT.");
+
                        return rsa.DecryptValue (rgb);
                }
        
@@ -258,25 +278,28 @@ namespace System.Security.Cryptography {
                private string GetHashNameFromOID (string oid) 
                {
                        switch (oid) {
-                               case "1.3.14.3.2.26":
-                                       return "SHA1";
-                               case "1.2.840.113549.2.5":
-                                       return "MD5";
-                               default:
-                                       throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
+                       case "1.3.14.3.2.26":
+                               return "SHA1";
+                       case "1.2.840.113549.2.5":
+                               return "MD5";
+                       case "2.16.840.1.101.3.4.2.1":
+                               return "SHA256";
+                       case "2.16.840.1.101.3.4.2.2":
+                               return "SHA384";
+                       case "2.16.840.1.101.3.4.2.3":
+                               return "SHA512";
+                       default:
+                               throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
                        }
                }
 
-               // LAMESPEC: str is not the hash name but an OID
-               // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
-               // and 1.1 because there's no mathod to get a hash algorithm from an OID. 
-               // However there's no such limit when using the [De]Formatter class.
                public byte[] SignHash (byte[] rgbHash, string str) 
                {
                        if (rgbHash == null)
                                throw new ArgumentNullException ("rgbHash");
-       
-                       HashAlgorithm hash = HashAlgorithm.Create (GetHashNameFromOID (str));
+                       // Fx 2.0 defaults to the SHA-1
+                       string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
+                       HashAlgorithm hash = HashAlgorithm.Create (hashName);
                        return PKCS1.Sign_v15 (this, hash, rgbHash);
                }
 
@@ -284,10 +307,8 @@ namespace System.Security.Cryptography {
                // HashAlgorithm descendant
                public bool VerifyData (byte[] buffer, object halg, byte[] signature) 
                {
-#if NET_1_1
                        if (buffer == null)
                                throw new ArgumentNullException ("buffer");
-#endif
                        if (signature == null)
                                throw new ArgumentNullException ("signature");
 
@@ -296,24 +317,25 @@ namespace System.Security.Cryptography {
                        return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
                }
        
-               // LAMESPEC: str is not the hash name but an OID
-               // NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0 
-               // and 1.1 because there's no method to get a hash algorithm from an OID. 
-               // However there's no such limit when using the [De]Formatter class.
                public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature) 
                {
                        if (rgbHash == null) 
                                throw new ArgumentNullException ("rgbHash");
                        if (rgbSignature == null)
                                throw new ArgumentNullException ("rgbSignature");
-       
-                       HashAlgorithm hash = HashAlgorithm.Create (GetHashNameFromOID (str));
+                       // Fx 2.0 defaults to the SHA-1
+                       string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
+                       HashAlgorithm hash = HashAlgorithm.Create (hashName);
                        return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
                }
        
                protected override void Dispose (bool disposing) 
                {
                        if (!m_disposed) {
+                               // the key is persisted and we do not want it persisted
+                               if ((persisted) && (!persistKey)) {
+                                       store.Remove ();        // delete the container
+                               }
                                if (rsa != null)
                                        rsa.Clear ();
                                // call base class 
@@ -324,8 +346,9 @@ namespace System.Security.Cryptography {
 
                // private stuff
 
-               private void OnKeyGenerated (object sender) 
+               private void OnKeyGenerated (object sender, EventArgs e
                {
+                       // the key isn't persisted and we want it persisted
                        if ((persistKey) && (!persisted)) {
                                // save the current keypair
                                store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
@@ -333,5 +356,58 @@ namespace System.Security.Cryptography {
                                persisted = true;
                        }
                }
+               // ICspAsymmetricAlgorithm
+
+               [ComVisible (false)]
+               public CspKeyContainerInfo CspKeyContainerInfo {
+                       get {
+                               return new CspKeyContainerInfo(store.Parameters);
+                       }
+               }
+
+               [ComVisible (false)]
+               public byte[] ExportCspBlob (bool includePrivateParameters)
+               {
+                       byte[] blob = null;
+                       if (includePrivateParameters)
+                               blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
+                       else
+                               blob = CryptoConvert.ToCapiPublicKeyBlob (this);
+
+                       // ALGID (bytes 4-7) - default is KEYX
+                       // 00 24 00 00 (for CALG_RSA_SIGN)
+                       // 00 A4 00 00 (for CALG_RSA_KEYX)
+                       blob [5] = 0xA4;
+                       return blob;
+               }
+
+               [ComVisible (false)]
+               public void ImportCspBlob (byte[] keyBlob)
+               {
+                       if (keyBlob == null)
+                               throw new ArgumentNullException ("keyBlob");
+
+                       RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
+                       if (rsa is RSACryptoServiceProvider) {
+                               // default (if no change are present in machine.config)
+                               RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
+                               ImportParameters (rsap);
+                       } else {
+                               // we can't know from RSA if the private key is available
+                               try {
+                                       // so we try it...
+                                       RSAParameters rsap = rsa.ExportParameters (true);
+                                       ImportParameters (rsap);
+                               }
+                               catch {
+                                       // and fall back
+                                       RSAParameters rsap = rsa.ExportParameters (false);
+                                       ImportParameters (rsap);
+                               }
+                       }
+               }
        }
 }
+
+#endif
+