当前位置: 首页>>代码示例>>C#>>正文


C# X509Certificate2Collection.Import方法代码示例

本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2Collection.Import方法的具体用法?C# X509Certificate2Collection.Import怎么用?C# X509Certificate2Collection.Import使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Cryptography.X509Certificates.X509Certificate2Collection的用法示例。


在下文中一共展示了X509Certificate2Collection.Import方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            if (args.Length == 0)
              {
            Console.WriteLine("ERROR! Missing parameter");
            Console.WriteLine("syntax: certlimit.exe <cert-file.pfx> <password>");
            Environment.Exit(1);
              }

              int day_threshold = 30;
              string password = args[1]; // System.Environment.GetEnvironmentVariable("signtoolpassword");
              string certfile = args[0];
              X509Certificate2Collection coll = new X509Certificate2Collection();
              coll.Import(certfile, password, X509KeyStorageFlags.PersistKeySet);
              foreach (X509Certificate2 cert in coll)
              {
            Console.WriteLine("Subject: {0}", cert.Subject);
            Console.WriteLine("Issuer: {0}", cert.Issuer);
            if (cert.Subject.ToString().Contains("Rackspace"))
            {
              Console.WriteLine("Effective: {0}", cert.GetEffectiveDateString());
              Console.WriteLine("Expiration: {0}", cert.GetExpirationDateString());
              Console.WriteLine("Serial #: {0}", cert.SerialNumber.ToLower());
              int days_to_expiration = (int)((Convert.ToDateTime(cert.GetExpirationDateString()) - DateTime.Now).TotalDays);
              Console.WriteLine("Days to expiration: {0}", days_to_expiration);
              if (days_to_expiration < day_threshold)
              {
            Console.WriteLine("ERROR! Code signing cert expires in fewer than {0} days", day_threshold);
            Environment.Exit(1);
              }
            }
              }
        }
开发者ID:brett-johnson,项目名称:prototypes,代码行数:33,代码来源:Program.cs

示例2: Execute

        public void Execute(object parameter)
        {
            var pfx = CertificateManager.GeneratePfx(CertificateName, CertificatePassword);
            var certificate = CertificateManager.GetCertificateForBytes(pfx.GetBytes(), CertificatePassword);

            File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), pfx.GetBytes());
            File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.cer"), certificate);

            var collection = new X509Certificate2Collection();
            collection.Import(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), CertificatePassword, X509KeyStorageFlags.PersistKeySet);

            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);

            // Store the certificate
            foreach (var cert in collection)
                store.Add(cert);

            store.Close();

            // Delete the certificate that contains the private key - this is already imported into the cert store
            File.Delete(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"));

            MessageBox.Show("The certificate has been generated. Please refresh the certificates list.", "Certificate", MessageBoxButton.OK);

            // Open the folder containing the certificate
            Process.Start("explorer.exe", AppHelper.CachePath);
        }
开发者ID:peterschen,项目名称:SMAStudio,代码行数:28,代码来源:GenerateCertificateCommand.cs

示例3: Main

        static int Main(string[] args) {
            try {
                string title = string.Empty;

                // Parse the command line.
                ParseCommandLine(args);

                X509Certificate2Collection certificates = new X509Certificate2Collection();
                switch (command)
                {
                    case Command.Sign:
                        // For view, source can come from either store or cert file.
                        if (null == pfxFile) {
                            // Open the source (store and/or pfx file).
                            Console.WriteLine( storeLocation ) ; 
                            X509Store store = new X509Store("MY", storeLocation);

                            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                            certificates = store.Certificates;
                            title = "Viewing " + storeLocation.ToString() + " " + "MY" + " store";
                        } 
                        else {
                            certificates.Import(pfxFile, password, X509KeyStorageFlags.DefaultKeySet);
                            title = "Viewing " + pfxFile;
                        }
                        break;
                    case Command.Verify:
                        break;
                    default:
                        break;
                }

                // Carry out the command.
                switch (command)
                {
                    case Command.Sign:
                        // Perform filter(s) requested.
                        X509Certificate2 certificate = FilterCertificates(certificates);
                        DoSignCommand(title, certificate);
                        break;
                    case Command.Verify:
                        DoVerifyCommand(title);
                        break;
                }
            }
            catch (UsageException) {
                DisplayUsage();
            }
            catch (InternalException e) {
                Console.WriteLine(e.Message);
            }
            catch( Exception e )
            	{
            	Console.WriteLine(e);
            	}

            return Result ? 100 : 101 ;
        }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:58,代码来源:xmlsign.cs

示例4: GetCertificateCollection

        private static X509Certificate2Collection GetCertificateCollection(string certificateFileName)
        {
            var certCollection = new X509Certificate2Collection();
            certCollection.Import(
                Path.Combine(TestDataFolder, certificateFileName),
                CertificatePassword,
                X509KeyStorageFlags.DefaultKeySet);

            return certCollection;
        }
开发者ID:alux-xu,项目名称:corefx,代码行数:10,代码来源:TestConfiguration.cs

示例5: Main

        private static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                Console.WriteLine("Enter PIN: ");
                string pin = Console.ReadLine();

                WebRequestHandler handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

                using (HttpClient client = new HttpClient(handler, true))
                {
                    client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort));

                    X509Store store = null;

                    try
                    {
                        var response = await client.GetAsync("certs/" + pin);
                        response.EnsureSuccessStatusCode();

                        byte[] rawCert = await response.Content.ReadAsByteArrayAsync();

                        X509Certificate2Collection certs = new X509Certificate2Collection();
                        certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet);

                        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                        store.Open(OpenFlags.ReadWrite);

                        X509Certificate2Collection oldCerts = new X509Certificate2Collection();

                        foreach (var cert in certs)
                        {
                            oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false));
                        }
                        store.RemoveRange(certs);
                        store.AddRange(certs);
                        store.Close();

                        Console.WriteLine("Success");
                    }
                    catch (HttpRequestException e)
                    {
                        Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated.");
                    }
                    finally
                    {
                        if (store != null)
                        {
                            store.Close();
                        }
                    }
                }
            }).Wait();
        }
开发者ID:lsgxeva,项目名称:MIEngine,代码行数:55,代码来源:CertTool.cs

示例6: GetServerCertificate

        public static X509Certificate2 GetServerCertificate()
        {
            X509Certificate2 certificate = null;

            var certCollection = new X509Certificate2Collection();
            certCollection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"));

            foreach (X509Certificate2 c in certCollection)
            {
                if (c.HasPrivateKey)
                {
                    certificate = c;
                    break;
                }
            }

            Assert.NotNull(certificate);
            return certificate;
        }
开发者ID:JonHanna,项目名称:corefx,代码行数:19,代码来源:TestConfiguration.cs

示例7: GetStrongNameKeyPairFromPfx

		/// <summary>Gets the strong name key pair from PFX.</summary>
		/// <param name="pfxFile">The PFX file.</param>
		/// <param name="password">The password.</param>
		/// <returns>Key pair.</returns>
		/// <exception cref="System.ArgumentException">pfxFile</exception>
		public static StrongNameKeyPair GetStrongNameKeyPairFromPfx(string pfxFile, string password)
		{
			// http://stackoverflow.com/questions/7556846/how-to-use-strongnamekeypair-with-a-password-protected-keyfile-pfx

			var certs = new X509Certificate2Collection();
			certs.Import(pfxFile, password, X509KeyStorageFlags.Exportable);
			if (certs.Count == 0)
				throw new ArgumentException(null, "pfxFile");

			var provider = certs[0].PrivateKey as RSACryptoServiceProvider;
			if (provider == null) // not a good pfx file
				throw new ArgumentException(null, "pfxFile");

			return new StrongNameKeyPair(provider.ExportCspBlob(false));
		}
开发者ID:jinjingcai2014,项目名称:LibZ,代码行数:20,代码来源:MsilUtilities.cs

示例8: GetIdentity

        /// <summary>
        /// Gets the identity.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>EndpointIdentity.</returns>
        /// <exception cref="System.InvalidOperationException">UnableToLoadCertificateIdentity</exception>
        private static EndpointIdentity GetIdentity(IdentityElement element)
        {
            var properties = element.ElementInformation.Properties;

            var userPrincipalName = properties["userPrincipalName"];
            if (userPrincipalName != null && userPrincipalName.ValueOrigin != PropertyValueOrigin.Default)
            {
                return EndpointIdentity.CreateUpnIdentity(element.UserPrincipalName.Value);
            }

            var servicePrincipalName = properties["servicePrincipalName"];
            if (servicePrincipalName != null && servicePrincipalName.ValueOrigin != PropertyValueOrigin.Default)
            {
                return EndpointIdentity.CreateSpnIdentity(element.ServicePrincipalName.Value);
            }

            var dns = properties["dns"];
            if (dns != null && dns.ValueOrigin != PropertyValueOrigin.Default)
            {
                return EndpointIdentity.CreateDnsIdentity(element.Dns.Value);
            }

            var rsa = properties["rsa"];
            if (rsa != null && rsa.ValueOrigin != PropertyValueOrigin.Default)
            {
                return EndpointIdentity.CreateRsaIdentity(element.Rsa.Value);
            }

            var certificate = properties["certificate"];
            if (certificate != null && certificate.ValueOrigin != PropertyValueOrigin.Default)
            {
                var supportingCertificates = new X509Certificate2Collection();
                supportingCertificates.Import(Convert.FromBase64String(element.Certificate.EncodedValue));
                if (supportingCertificates.Count == 0)
                {
                    throw new InvalidOperationException("UnableToLoadCertificateIdentity");
                }

                var primaryCertificate = supportingCertificates[0];
                supportingCertificates.RemoveAt(0);
                return EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate, supportingCertificates);
            }

            return null;
        }
开发者ID:mparsin,项目名称:Elements,代码行数:51,代码来源:ServiceConfigurationImporter.cs

示例9: Import

        /// <summary>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </summary>
        /// <param name="stream">The raw certificate and key data.</param>
        /// <param name="password">The password to unlock the stream.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// Importing keys is not supported by this cryptography context.
        /// </exception>
        public override void Import(Stream stream, string password)
        {
            if (stream == null)
                throw new ArgumentNullException ("stream");

            if (password == null)
                throw new ArgumentNullException ("password");

            byte[] rawData;

            if (stream is MemoryBlockStream) {
                rawData = ((MemoryBlockStream) stream).ToArray ();
            } else if (stream is MemoryStream) {
                rawData = ((MemoryStream) stream).ToArray ();
            } else {
                using (var memory = new MemoryStream ()) {
                    stream.CopyTo (memory, 4096);
                    rawData = memory.ToArray ();
                }
            }
            var store = new X509Store (StoreName.My, StoreLocation);
            var certs = new X509Certificate2Collection ();

            store.Open (OpenFlags.ReadWrite);
            certs.Import (rawData, password, X509KeyStorageFlags.UserKeySet);
            store.AddRange (certs);
            store.Close ();
        }
开发者ID:vdaron,项目名称:MimeKit,代码行数:41,代码来源:WindowsSecureMimeContext.cs

示例10: LoadFromFile

 private X509Certificate2 LoadFromFile(string path)
 {
     X509Certificate2Collection store = new X509Certificate2Collection();
     store.Import(path);
     return store[0];
 }
开发者ID:jechtom,项目名称:DevUpdater,代码行数:6,代码来源:ClientCertificateResolver.cs

示例11: LoadPfxUsingCollectionImport

 private static X509Certificate2 LoadPfxUsingCollectionImport(this CertLoader certLoader)
 {
     byte[] pfxData = certLoader.PfxData;
     string password = certLoader.Password;
     X509Certificate2Collection collection = new X509Certificate2Collection();
     collection.Import(pfxData, password, X509KeyStorageFlags.DefaultKeySet);
     Assert.Equal(1, collection.Count);
     return collection[0];
 }
开发者ID:dotnet,项目名称:corefx,代码行数:9,代码来源:EdgeCasesTests.cs

示例12: ImportKeyFile

 /// <summary>
 /// Adds certificates to this store from a keyfile.
 /// </summary>
 /// <param name="filePath">The path to the keyfile</param>
 /// <param name="password">The keyfile password</param>
 /// <param name="flags">The <see cref="X509KeyStorageFlags"/> for the keyfile</param>
 public void ImportKeyFile(string filePath, string password, X509KeyStorageFlags flags)
 {
     X509Certificate2Collection certs = new X509Certificate2Collection();
     certs.Import(filePath, password, flags);
     this.Add(certs);
 }
开发者ID:DM-TOR,项目名称:nhin-d,代码行数:12,代码来源:CertificateStore.cs

示例13: ImportFolder

 /// <summary>
 /// Adds certificates to this store from a folder.
 /// </summary>
 /// <param name="folderPath">The path to a folder containing certificate files</param>
 /// <param name="flags">The <see cref="X509KeyStorageFlags"/> for the keyfile</param>
 public void ImportFolder(string folderPath, X509KeyStorageFlags flags)
 {
     string[] files = System.IO.Directory.GetFiles(folderPath);
     if (files.IsNullOrEmpty())
     {
         return;
     }
     
     X509Certificate2Collection certs = new X509Certificate2Collection();
     foreach(string filePath in files)
     {
         certs.Clear();
         certs.Import(filePath, null, flags);
         this.Add(certs);
     }
 }
开发者ID:DM-TOR,项目名称:nhin-d,代码行数:21,代码来源:CertificateStore.cs

示例14: AzureCertificateTest

        public void AzureCertificateTest()
        {
            StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
            vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName);
            Console.WriteLine("Service Name: {0} is created.  VM: {1} is created.", serviceName, vmName);

            // Certificate files to test
            string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]);
            string pfxFileName = Convert.ToString(TestContext.DataRow["pfxFileName"]);
            string psswrd = Convert.ToString(TestContext.DataRow["password"]);
            string thumbprintAlgorithm = Convert.ToString(TestContext.DataRow["algorithm"]);

            // Create a certificate
            X509Certificate2 certCreated = Utilities.CreateCertificate(psswrd);
            byte[] certData = certCreated.Export(X509ContentType.Pfx, psswrd);
            File.WriteAllBytes(pfxFileName, certData);
            byte[] certData2 = certCreated.Export(X509ContentType.Cert);
            File.WriteAllBytes(cerFileName, certData2);

            // Install the .cer file to local machine.
            StoreLocation certStoreLocation = StoreLocation.CurrentUser;
            StoreName certStoreName = StoreName.My;
            X509Certificate2 installedCert = Utilities.InstallCert(cerFileName, certStoreLocation, certStoreName);

            // Certificate1: get it from the installed certificate.
            PSObject cert1 = vmPowershellCmdlets.RunPSScript(
                String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0];
            string cert1data = Convert.ToBase64String(((X509Certificate2)cert1.BaseObject).RawData);

            // Certificate2: get it from .pfx file.
            X509Certificate2Collection cert2 = new X509Certificate2Collection();
            cert2.Import(pfxFileName, psswrd, X509KeyStorageFlags.PersistKeySet);
            string cert2data = Convert.ToBase64String(cert2[0].RawData);

            // Certificate3: get it from .cer file.
            X509Certificate2Collection cert3 = new X509Certificate2Collection();
            cert3.Import(cerFileName);
            string cert3data = Convert.ToBase64String(cert3[0].RawData);

            try
            {
                // Add a cert item
                vmPowershellCmdlets.AddAzureCertificate(serviceName, cert1);
                CertificateContext getCert1 = vmPowershellCmdlets.GetAzureCertificate(serviceName).FirstOrDefault(a => a.Thumbprint.Equals(installedCert.Thumbprint));
                Console.WriteLine("Cert is added: {0}", getCert1.Thumbprint);
                Assert.AreEqual(getCert1.Data, cert1data, "Cert is different!!");

                Thread.Sleep(TimeSpan.FromMinutes(2));
                vmPowershellCmdlets.RemoveAzureCertificate(serviceName, getCert1.Thumbprint, thumbprintAlgorithm);
                pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, serviceName, getCert1.Thumbprint, thumbprintAlgorithm);

                // Add .pfx file
                vmPowershellCmdlets.AddAzureCertificate(serviceName, pfxFileName, psswrd);
                CertificateContext getCert2 = vmPowershellCmdlets.GetAzureCertificate(serviceName, cert2[0].Thumbprint, thumbprintAlgorithm)[0];
                Console.WriteLine("Cert is added: {0}", cert2[0].Thumbprint);
                Assert.AreEqual(getCert2.Data, cert2data, "Cert is different!!");
                Thread.Sleep(TimeSpan.FromMinutes(2));
                vmPowershellCmdlets.RemoveAzureCertificate(serviceName, cert2[0].Thumbprint, thumbprintAlgorithm);
                pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, serviceName, cert2[0].Thumbprint, thumbprintAlgorithm);

                // Add .cer file
                vmPowershellCmdlets.AddAzureCertificate(serviceName, cerFileName);
                CertificateContext getCert3 = vmPowershellCmdlets.GetAzureCertificate(serviceName, cert3[0].Thumbprint, thumbprintAlgorithm)[0];
                Console.WriteLine("Cert is added: {0}", cert3[0].Thumbprint);
                Assert.AreEqual(getCert3.Data, cert3data, "Cert is different!!");
                Thread.Sleep(TimeSpan.FromMinutes(2));
                vmPowershellCmdlets.RemoveAzureCertificate(serviceName, cert3[0].Thumbprint, thumbprintAlgorithm);
                pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, serviceName, cert3[0].Thumbprint, thumbprintAlgorithm);

                var certs = vmPowershellCmdlets.GetAzureCertificate(serviceName);
                Console.WriteLine("number of certs: {0}", certs.Count);
                Utilities.PrintContext(certs);
            }
            catch (Exception e)
            {
                pass = false;
                Assert.Fail(e.ToString());
            }
        }
开发者ID:ldattilo,项目名称:azure-powershell,代码行数:79,代码来源:FunctionalTest.cs

示例15: InitializeCertificateCollection

        internal X509Certificate2Collection InitializeCertificateCollection()
        {
            FileInfo certFile = new FileInfo(this.GetUnresolvedProviderPathFromPSPath(this.FilePath));
            if (!certFile.Exists)
            {
                throw new FileNotFoundException(string.Format(KeyVaultProperties.Resources.CertificateFileNotFound, this.FilePath));
            }

            X509Certificate2Collection certificateCollection = new X509Certificate2Collection();

            if (null == this.Password)
            {
                certificateCollection.Import(certFile.FullName);
            }
            else
            {
                certificateCollection.Import(certFile.FullName, this.Password.ConvertToString(), X509KeyStorageFlags.Exportable);
            }

            return certificateCollection;
        }
开发者ID:Azure,项目名称:azure-powershell,代码行数:21,代码来源:ImportAzureKeyVaultCertificate.cs


注:本文中的System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。