private string GetNameFromIdentity(object identity)
        {
            // Note: Default evidences return an XML string with ToString
            byte[] id   = Encoding.UTF8.GetBytes(identity.ToString());
            SHA1   hash = SHA1.Create();

            // this create an unique name for an identity - bad identities like Url
            // results in bad (i.e. changing) names.
            byte[] full = hash.ComputeHash(id, 0, id.Length);
            byte[] half = new byte [10];
            Buffer.BlockCopy(full, 0, half, 0, half.Length);
            return(CryptoConvert.ToHex(half));
        }
        public static byte[] GetMappedPublicKey(byte[] token)
        {
            if (StrongNameManager.mappings == null || token == null)
            {
                return(null);
            }
            string key  = CryptoConvert.ToHex(token);
            string text = (string)StrongNameManager.mappings[key];

            if (text == null)
            {
                return(null);
            }
            return(CryptoConvert.FromHex(text));
        }
Beispiel #3
0
        public void Import(X509Certificate certificate)
        {
            CheckStore(_storePath, true);

            string filename = Path.Combine(_storePath, GetUniqueName(certificate));

            if (!File.Exists(filename))
            {
                filename = Path.Combine(_storePath, GetUniqueNameWithSerial(certificate));
                if (!File.Exists(filename))
                {
                    using (FileStream fs = File.Create(filename)) {
                        byte[] data = certificate.RawData;
                        fs.Write(data, 0, data.Length);
                        fs.Close();
                    }
                    ClearCertificates();                        // We have modified the store on disk.  So forget the old state.
                }
            }
            else
            {
                string newfilename = Path.Combine(_storePath, GetUniqueNameWithSerial(certificate));
                if (GetUniqueNameWithSerial(LoadCertificate(filename)) != GetUniqueNameWithSerial(certificate))
                {
                    using (FileStream fs = File.Create(newfilename)) {
                        byte[] data = certificate.RawData;
                        fs.Write(data, 0, data.Length);
                        fs.Close();
                    }
                    ClearCertificates();                        // We have modified the store on disk.  So forget the old state.
                }
            }
#if !MOBILE
            // Try to save privateKey if available..
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = CryptoConvert.ToHex(certificate.Hash);

            // Right now this seems to be the best way to know if we should use LM store.. ;)
            if (_storePath.StartsWith(X509StoreManager.LocalMachinePath))
            {
                cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            }

            ImportPrivateKey(certificate, cspParams);
#endif
        }
Beispiel #4
0
        static public byte[] GetMappedPublicKey(byte[] token)
        {
            if ((mappings == null) || (token == null))
            {
                return(null);
            }

            string t  = CryptoConvert.ToHex(token);
            string pk = (string)mappings [t];

            if (pk == null)
            {
                return(null);
            }

            return(CryptoConvert.FromHex(pk));
        }
Beispiel #5
0
        public SecurityElement ToXml()
        {
#if DISABLE_SECURITY
            throw new PlatformNotSupportedException();
#else
            SecurityElement se = new SecurityElement("ApplicationTrust");
            se.AddAttribute("version", "1");

            if (_appid != null)
            {
                se.AddAttribute("FullName", _appid.FullName);
            }

            if (_trustrun)
            {
                se.AddAttribute("TrustedToRun", "true");
            }

            if (_persist)
            {
                se.AddAttribute("Persist", "true");
            }

            SecurityElement defaultGrant = new SecurityElement("DefaultGrant");
            defaultGrant.AddChild(DefaultGrantSet.ToXml());
            se.AddChild(defaultGrant);

            if (_xtranfo != null)
            {
                byte[] data = null;
                using (MemoryStream ms = new MemoryStream()) {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, _xtranfo);
                    data = ms.ToArray();
                }
                SecurityElement xtra = new SecurityElement("ExtraInfo");
                xtra.AddAttribute("Data", CryptoConvert.ToHex(data));
                se.AddChild(xtra);
            }

            return(se);
#endif
        }
Beispiel #6
0
 static void DisplayCrl(X509Crl crl, bool machine, bool verbose)
 {
     Console.WriteLine("X.509 v{0} CRL", crl.Version);
     Console.WriteLine("  Issuer Name:   {0}", crl.IssuerName);
     Console.WriteLine("  This Update:   {0}", crl.ThisUpdate);
     Console.WriteLine("  Next Update:   {0} {1}", crl.NextUpdate, crl.IsCurrent ? String.Empty : "update overdue!");
     Console.WriteLine("  Unique Hash:   {0}", CryptoConvert.ToHex(crl.Hash));
     if (verbose)
     {
         Console.WriteLine("  Signature Algorithm:  {0}", crl.SignatureAlgorithm);
         Console.WriteLine("  Signature:            {0}", CryptoConvert.ToHex(crl.Signature));
         int n = 0;
         foreach (X509Crl.X509CrlEntry entry in crl.Entries)
         {
             Console.WriteLine("    #{0}: Serial: {1} revoked on {2}",
                               ++n, CryptoConvert.ToHex(entry.SerialNumber), entry.RevocationDate);
         }
     }
 }
Beispiel #7
0
 static void DisplayCertificate(X509Certificate x509, bool verbose)
 {
     Console.WriteLine("{0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version);
     Console.WriteLine("  Serial Number: {0}", CryptoConvert.ToHex(x509.SerialNumber));
     Console.WriteLine("  Issuer Name:   {0}", x509.IssuerName);
     Console.WriteLine("  Subject Name:  {0}", x509.SubjectName);
     Console.WriteLine("  Valid From:    {0}", x509.ValidFrom);
     Console.WriteLine("  Valid Until:   {0}", x509.ValidUntil);
     Console.WriteLine("  Unique Hash:   {0}", CryptoConvert.ToHex(x509.Hash));
     if (verbose)
     {
         Console.WriteLine("  Key Algorithm:        {0}", x509.KeyAlgorithm);
         Console.WriteLine("  Algorithm Parameters: {0}", (x509.KeyAlgorithmParameters == null) ? "None" :
                           CryptoConvert.ToHex(x509.KeyAlgorithmParameters));
         Console.WriteLine("  Public Key:           {0}", CryptoConvert.ToHex(x509.PublicKey));
         Console.WriteLine("  Signature Algorithm:  {0}", x509.SignatureAlgorithm);
         Console.WriteLine("  Algorithm Parameters: {0}", (x509.SignatureAlgorithmParameters == null) ? "None" :
                           CryptoConvert.ToHex(x509.SignatureAlgorithmParameters));
         Console.WriteLine("  Signature:            {0}", CryptoConvert.ToHex(x509.Signature));
     }
     Console.WriteLine();
 }
Beispiel #8
0
        public void Import(X509Certificate certificate)
        {
            this.CheckStore(this._storePath, true);
            string path = Path.Combine(this._storePath, this.GetUniqueName(certificate));

            if (!File.Exists(path))
            {
                using (FileStream fileStream = File.Create(path))
                {
                    byte[] rawData = certificate.RawData;
                    fileStream.Write(rawData, 0, rawData.Length);
                    fileStream.Close();
                }
            }
            CspParameters cspParams = new CspParameters();

            cspParams.KeyContainerName = CryptoConvert.ToHex(certificate.Hash);
            if (this._storePath.StartsWith(X509StoreManager.LocalMachinePath))
            {
                cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            }
            this.ImportPrivateKey(certificate, cspParams);
        }
        public static bool MustVerify(AssemblyName an)
        {
            if (an == null || StrongNameManager.tokens == null)
            {
                return(true);
            }
            string key = CryptoConvert.ToHex(an.GetPublicKeyToken());

            StrongNameManager.Element element = (StrongNameManager.Element)StrongNameManager.tokens[key];
            if (element != null)
            {
                string users = element.GetUsers(an.Name);
                if (users == null)
                {
                    users = element.GetUsers("*");
                }
                if (users != null)
                {
                    return(!(users == "*") && users.IndexOf(Environment.UserName) < 0);
                }
            }
            return(true);
        }
Beispiel #10
0
        // it is possible to skip verification for assemblies
        // or a strongname public key using the "sn" tool.
        // note: only the runtime checks if the assembly is loaded
        // from the GAC to skip verification
        public static bool MustVerify(AssemblyName an)
        {
            if ((an == null) || (tokens == null))
            {
                return(true);
            }

            var token = CryptoConvert.ToHex(an.GetPublicKeyToken());
            var el    = (Element)tokens[token];

            if (el != null)
            {
                // look for this specific assembly first
                var users = el.GetUsers(an.Name);
                if (users == null)
                {
                    // nothing for the specific assembly
                    // so look for "*" assembly
                    users = el.GetUsers("*");
                }

                if (users != null)
                {
                    // applicable to any user ?
                    if (users == "*")
                    {
                        return(false);
                    }

                    // applicable to the current user ?
                    return(users.IndexOf(Environment.UserName) < 0);
                }
            }

            // we must check verify the strongname on the assembly
            return(true);
        }
        /// <summary>Creates an XML encoding of the <see cref="T:System.Security.Policy.ApplicationTrust" /> object and its current state.</summary>
        /// <returns>An XML encoding of the security object, including any state information.</returns>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*" />
        ///   <IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="MemberAccess" />
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        /// </PermissionSet>
        public SecurityElement ToXml()
        {
            SecurityElement securityElement = new SecurityElement("ApplicationTrust");

            securityElement.AddAttribute("version", "1");
            if (this._appid != null)
            {
                securityElement.AddAttribute("FullName", this._appid.FullName);
            }
            if (this._trustrun)
            {
                securityElement.AddAttribute("TrustedToRun", "true");
            }
            if (this._persist)
            {
                securityElement.AddAttribute("Persist", "true");
            }
            SecurityElement securityElement2 = new SecurityElement("DefaultGrant");

            securityElement2.AddChild(this.DefaultGrantSet.ToXml());
            securityElement.AddChild(securityElement2);
            if (this._xtranfo != null)
            {
                byte[] input = null;
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(memoryStream, this._xtranfo);
                    input = memoryStream.ToArray();
                }
                SecurityElement securityElement3 = new SecurityElement("ExtraInfo");
                securityElement3.AddAttribute("Data", CryptoConvert.ToHex(input));
                securityElement.AddChild(securityElement3);
            }
            return(securityElement);
        }
Beispiel #12
0
        private X509Certificate LoadCertificate(string filename)
        {
            X509Certificate x509Certificate = new X509Certificate(this.Load(filename));
            CspParameters   parameters      = new CspParameters();

            parameters.KeyContainerName = CryptoConvert.ToHex(x509Certificate.Hash);
            if (this._storePath.StartsWith(X509StoreManager.LocalMachinePath))
            {
                parameters.Flags = CspProviderFlags.UseMachineKeyStore;
            }
            if (!new KeyPairPersistence(parameters).Load())
            {
                return(x509Certificate);
            }
            if (x509Certificate.RSA != null)
            {
                x509Certificate.RSA = (RSA) new RSACryptoServiceProvider(parameters);
            }
            else if (x509Certificate.DSA != null)
            {
                x509Certificate.DSA = (DSA) new DSACryptoServiceProvider(parameters);
            }
            return(x509Certificate);
        }
Beispiel #13
0
        private X509Certificate LoadCertificate(string filename)
        {
            byte[]          data = Load(filename);
            X509Certificate cert = new X509Certificate(data);

#if !MOBILE
            // If privateKey it's available, load it too..
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = CryptoConvert.ToHex(cert.Hash);
            if (_storePath.StartsWith(X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
            {
                cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            }
            KeyPairPersistence kpp = new KeyPairPersistence(cspParams);

            try {
                if (!kpp.Load())
                {
                    return(cert);
                }
            }
            catch {
                return(cert);
            }

            if (cert.RSA != null)
            {
                cert.RSA = new RSACryptoServiceProvider(cspParams);
            }
            else if (cert.DSA != null)
            {
                cert.DSA = new DSACryptoServiceProvider(cspParams);
            }
#endif
            return(cert);
        }
Beispiel #14
0
        /// <summary>Creates and returns a string representation of the membership condition.</summary>
        /// <returns>A string representation of the state of the membership condition.</returns>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        /// </PermissionSet>
        public override string ToString()
        {
            Type type = this.HashAlgorithm.GetType();

            return(string.Format("Hash - {0} {1} = {2}", type.FullName, type.Assembly, CryptoConvert.ToHex(this.HashValue)));
        }
Beispiel #15
0
 public void ToHex()
 {
     Assert.IsNull(CryptoConvert.FromHex(null), "FromHex(null)");
     byte[] data = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
     Assert.AreEqual("0123456789ABCDEF", CryptoConvert.ToHex(data), "0123456789abcdef");
 }
        private string ServerCertValidate()
        {
            var errorMessage = String.Empty;

            var store = WorkContext.IsMono
                            ? X509StoreManager.CurrentUser.TrustedRoot
                            : X509StoreManager.LocalMachine.TrustedRoot;

            var storage = StorageFactory.GetStorage("-1", "certs");

            try
            {
                CoreContext.TenantManager.SetCurrentTenant(_currentTenantId);

                // Import the details of the certificate from the server.
                lock (RootSync)
                {
                    var certificate = Cache.Get <Syscert.X509Certificate>("ldapCertificate");
                    if (certificate != null)
                    {
                        var data = certificate.GetRawCertData();
                        var x509 = new X509Certificate(data);
                        // Check for ceritficate in store.
                        if (!store.Certificates.Contains(x509))
                        {
                            if (storage.IsFile("ldap/ldap.cer"))
                            {
                                var storageData = GetCertificateFromStorage(storage);
                                var storageX509 = new X509Certificate(storageData);
                                if (CompareHash(storageX509.Hash, x509.Hash))
                                {
                                    // Add the certificate to the store.
                                    store.Import(storageX509);
                                    store.Certificates.Add(storageX509);
                                    return(String.Empty);
                                }
                            }
                            if (_certificateConfirmRequest.Approved)
                            {
                                AddCertificateToStorage(storage, x509);
                                // Add the certificate to the store.
                                store.Import(x509);
                                store.Certificates.Add(x509);
                                return(String.Empty);
                            }
                            if (!_certificateConfirmRequest.Requested)
                            {
                                _certificateConfirmRequest.SerialNumber = CryptoConvert.ToHex(x509.SerialNumber);
                                _certificateConfirmRequest.IssuerName   = x509.IssuerName;
                                _certificateConfirmRequest.SubjectName  = x509.SubjectName;
                                _certificateConfirmRequest.ValidFrom    = x509.ValidFrom;
                                _certificateConfirmRequest.ValidUntil   = x509.ValidUntil;
                                _certificateConfirmRequest.Hash         = CryptoConvert.ToHex(x509.Hash);
                                var certificateErrors = Cache.Get <int[]>("ldapCertificateErrors");
                                _certificateConfirmRequest.CertificateErrors = certificateErrors.ToArray();
                                _certificateConfirmRequest.Requested         = true;
                            }
                        }
                    }
                    else
                    {
                        // for AD
                        if (storage.IsFile("ldap/ldap.cer"))
                        {
                            var storageData = GetCertificateFromStorage(storage);
                            var storageX509 = new X509Certificate(storageData);
                            // Add the certificate to the store.
                            store.Import(storageX509);
                            store.Certificates.Add(storageX509);
                            return(String.Empty);
                        }

                        errorMessage = "LDAP TlsHandler. Certificate not found in certificate store.";

                        _log.Error(errorMessage);

                        return(errorMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = String.Format("LDAP TlsHandler error: {0}. {1}. store path = {2}",
                                             ex, ex.InnerException != null ? ex.InnerException.ToString() : string.Empty,
                                             store.Name);
                _log.ErrorFormat(errorMessage);
            }

            return(errorMessage);
        }
Beispiel #17
0
        public static bool MySSLHandler(Syscert.X509Certificate certificate,
                                        int[] certificateErrors)
        {
            X509Store  store  = null;
            X509Stores stores = X509StoreManager.CurrentUser;
            String     input;

            store = stores.TrustedRoot;


            //Import the details of the certificate from the server.

            X509Certificate           x509 = null;
            X509CertificateCollection coll = new X509CertificateCollection();

            byte[] data = certificate.GetRawCertData();
            if (data != null)
            {
                x509 = new X509Certificate(data);
            }

            //List the details of the Server

            //check for ceritficate in store
            X509CertificateCollection check = store.Certificates;

            if (!check.Contains(x509))
            {
                if (bindCount == 1)
                {
                    Console.WriteLine(" \n\nCERTIFICATE DETAILS: \n");
                    Console.WriteLine(" {0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version);
                    Console.WriteLine("  Serial Number: {0}", CryptoConvert.ToHex(x509.SerialNumber));
                    Console.WriteLine("  Issuer Name:   {0}", x509.IssuerName);
                    Console.WriteLine("  Subject Name:  {0}", x509.SubjectName);
                    Console.WriteLine("  Valid From:    {0}", x509.ValidFrom);
                    Console.WriteLine("  Valid Until:   {0}", x509.ValidUntil);
                    Console.WriteLine("  Unique Hash:   {0}", CryptoConvert.ToHex(x509.Hash));
                    Console.WriteLine();
                }

                //Get the response from the Client
                do
                {
                    Console.WriteLine("\nDo you want to proceed with the connection (y/n)?");
                    input = Console.ReadLine();
                    if (input == "y" || input == "Y")
                    {
                        bHowToProceed = true;
                    }
                    if (input == "n" || input == "N")
                    {
                        bHowToProceed = false;
                    }
                } while (input != "y" && input != "Y" && input != "n" && input != "N");
            }
            else
            {
                if (bHowToProceed == true)
                {
                    //Add the certificate to the store.

                    if (x509 != null)
                    {
                        coll.Add(x509);
                    }
                    store.Import(x509);
                    if (bindCount == 1)
                    {
                        removeFlag = true;
                    }
                }
            }
            if (bHowToProceed == false)
            {
                //Remove the certificate added from the store.

                if (removeFlag == true && bindCount > 1)
                {
                    foreach (X509Certificate xt509 in store.Certificates)
                    {
                        if (CryptoConvert.ToHex(xt509.Hash) == CryptoConvert.ToHex(x509.Hash))
                        {
                            store.Remove(x509);
                        }
                    }
                }
                Console.WriteLine("SSL Bind Failed.");
            }
            return(bHowToProceed);
        }