Import() 공개 메소드

public Import ( byte rawData ) : void
rawData byte
리턴 void
        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);
        }
예제 #2
0
        public void testSignSimpleECDsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";
            string storePass    = "******";
            string storeAlias   = "ECDSAkey";

            SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection();
            pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet);
            SystemCertificates.X509Certificate2 certificate = null;
            foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12)
            {
                if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase))
                {
                    certificate = aCertificate;
                    break;
                }
            }
            Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias);

            X509Certificate bcCertificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate.RawData));

            X509Certificate[] chain = { bcCertificate };

            X509Certificate2Signature signature = new X509Certificate2Signature(certificate, "SHA512");

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-ECDSA-signed-simple.pdf"))
                {
                    PdfSigner  pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());
                    ITSAClient tsaClient = null;

                    pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS);
                }
        }
예제 #3
0
        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);
              }
            }
              }
        }
예제 #4
0
        public void testSignSimpleContainerECDsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";
            string storePath    = @"..\..\..\..\simple\keystore\test1234.p12";
            string storePass    = "******";
            string storeAlias   = "ECDSAkey";

            SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection();
            pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet);
            SystemCertificates.X509Certificate2 certificate = null;
            foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12)
            {
                if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase))
                {
                    certificate = aCertificate;
                    break;
                }
            }
            Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias);

            X509Certificate2SignatureContainer signature = new X509Certificate2SignatureContainer(certificate, signer => {
                signer.DigestAlgorithm = Oid.FromFriendlyName("SHA512", OidGroup.HashAlgorithm);
            });

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-ECDSA-signed-simple-container.pdf"))
                {
                    PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());

                    pdfSigner.SignExternalContainer(signature, 8192);
                }
        }
예제 #5
0
        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 ;
        }
예제 #6
0
        private static X509Certificate2Collection GetCertificateCollection(string certificateFileName)
        {
            var certCollection = new X509Certificate2Collection();
            certCollection.Import(
                Path.Combine(TestDataFolder, certificateFileName),
                CertificatePassword,
                X509KeyStorageFlags.DefaultKeySet);

            return certCollection;
        }
예제 #7
0
        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();
        }
예제 #8
0
        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;
        }
예제 #9
0
        /// <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 ();
        }
예제 #10
0
 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];
 }
        /// <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;
        }
예제 #12
0
 /// <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);
     }
 }
 private X509Certificate2 LoadFromFile(string path)
 {
     X509Certificate2Collection store = new X509Certificate2Collection();
     store.Import(path);
     return store[0];
 }
 /// <summary>
 /// Used to extract a pfk from a file
 /// </summary>
 public X509Certificate2 ExtractPfxObject(string password)
 {
     var collection = new X509Certificate2Collection();
     collection.Import(_publishSettingsFile, password, X509KeyStorageFlags.PersistKeySet);
     return collection[0];
 }
예제 #15
0
 /// <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);
 }
예제 #16
0
        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());
            }
        }
        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;
        }
예제 #18
0
            private static X509Certificate2Collection PEM(string pem)
            {
                // TODO: Test

                const string beginCert = "-----BEGIN CERTIFICATE-----";
                const string endCert = "-----END CERTIFICATE-----";

                var certificates = new X509Certificate2Collection();

                int end;
                for (int start = pem.IndexOf(beginCert); start >= 0; start = pem.IndexOf(beginCert, end))
                {
                    start += beginCert.Length;

                    end = pem.IndexOf(endCert, start);
                    if (end == -1)
                        throw new Exception(string.Format("'{0}' not found after index {1}", endCert, start));

                    byte[] rawData = Convert.FromBase64String(pem.Substring(start, end - start));
                    certificates.Import(rawData);
                }

                if (certificates.Count == 0)
                {
                    throw new Exception("no certificates found");
                }

                return certificates;
            }
예제 #19
0
        public X509Certificate2 FindCert(out X509Certificate2Collection includedCerts)
        {
            includedCerts = null;

            X509Store store = null;
            try
            {
                // Get the pool of certificates to search
                X509Certificate2Collection pool;
                if (!string.IsNullOrEmpty(CertificateFile))
                {
                    // If there is a file, load that
                    pool = new X509Certificate2Collection();
                    pool.Import(CertificateFile, Password, X509KeyStorageFlags.DefaultKeySet);
                    includedCerts = pool;
                }
                else
                {
                    // Otherwise, open the specified store
                    store = new X509Store(StoreName ?? "My", MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser);
                    store.Open(OpenFlags.ReadOnly);

                    // Code Signing EKU = 1.3.6.1.5.5.7.3.3
                    pool = store.Certificates
                        .Find(X509FindType.FindByTimeValid, DateTime.Now, validOnly: false)
                        .Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", validOnly: false);
                }

                // Search!
                var query = pool;
                if (!string.IsNullOrEmpty(IssuerName))
                {
                    query = query.Find(X509FindType.FindByIssuerName, IssuerName, validOnly: false);
                }
                if (!string.IsNullOrEmpty(SubjectName))
                {
                    query = query.Find(X509FindType.FindBySubjectName, SubjectName, validOnly: false);
                }
                // Can't do RootName with the certificate collection
                if (!string.IsNullOrEmpty(Thumbprint))
                {
                    query = query.Find(X509FindType.FindByThumbprint, Thumbprint, validOnly: false);
                }

                if (AutoSelect)
                {
                    // Find the one with the longest validity and use it as the signing cert
                    var now = DateTime.Now;
                    return query
                        .Cast<X509Certificate2>()
                        .OrderByDescending(c => c.HasEKU(Constants.CodeSigningOid))
                        .OrderByDescending(c => c.NotAfter - now)
                        .FirstOrDefault();
                }
                else
                {
                    if (query.Count > 1)
                    {
                        AnsiConsole.Error.WriteLine(@"Multiple certificates were found that meet all the given
            criteria. Use the -a option to choose the best
            certificate automatically or use the -sha1 option with the hash of the
            desired certificate.");
                        AnsiConsole.Error.WriteLine("The following certificates meet all given criteria:");
                        foreach (var cert in query)
                        {
                            AnsiConsole.Error.WriteLine("    Issued to: " + cert.SubjectName.CommonName());
                            AnsiConsole.Error.WriteLine("    Issued by: " + cert.IssuerName.CommonName());
                            AnsiConsole.Error.WriteLine("    Expires:   " + cert.NotAfter.ToString("ddd MMM dd HH:mm:ss yyyy"));
                            AnsiConsole.Error.WriteLine("    SHA1 hash: " + cert.Thumbprint);
                            AnsiConsole.Error.WriteLine("");
                        }
                        return null;
                    }
                    else if (query.Count == 0)
                    {
                        return null;
                    }
                    return query[0];
                }
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
        }
        public void AzureCertificateTest()
        {
            StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);

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

            // Create a certificate
            X509Certificate2 certCreated = Utilities.CreateCertificate(password);
            byte[] certData = certCreated.Export(X509ContentType.Pfx, password);
            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, password, 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
            {
                RemoveAllExistingCerts(defaultService);

                // Add a cert item
                vmPowershellCmdlets.AddAzureCertificate(defaultService, cert1);
                CertificateContext getCert1 = vmPowershellCmdlets.GetAzureCertificate(defaultService)[0];
                Console.WriteLine("Cert is added: {0}", getCert1.Thumbprint);
                Assert.AreEqual(getCert1.Data, cert1data, "Cert is different!!");
                vmPowershellCmdlets.RemoveAzureCertificate(defaultService, getCert1.Thumbprint, thumbprintAlgorithm);
                pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, getCert1.Thumbprint, thumbprintAlgorithm);

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


                // Add .cer file
                vmPowershellCmdlets.AddAzureCertificate(defaultService, cerFileName);
                CertificateContext getCert3 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm)[0];
                Console.WriteLine("Cert is added: {0}", cert3[0].Thumbprint);
                Assert.AreEqual(getCert3.Data, cert3data, "Cert is different!!");
                vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm);
                pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert3[0].Thumbprint, thumbprintAlgorithm);
            }
            catch (Exception e)
            {
                pass = false;
                Assert.Fail(e.ToString());
            }
            finally
            {
                Utilities.UninstallCert(installedCert, certStoreLocation, certStoreName);
                RemoveAllExistingCerts(defaultService);
            }
        }
예제 #21
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="request">XmlDocument object containing the request.</param>
        /// <param name="config">Configuration object to use.</param>
        /// <returns>XmlDocument object containing the reply.</returns>
        public static XmlDocument RunTransaction(
            Configuration config, XmlDocument request)
        {

            Logger logger = null;
            string nspace = null;
            try
            {

                nspace = GetRequestNamespace(request);
                DetermineEffectiveMerchantID(ref config, request, nspace);
                SetVersionInformation(request, nspace);
                logger = PrepareLog(config);
                
                if (string.IsNullOrEmpty(nspace))
                {
                    throw new ApplicationException(
                        REQUEST_MESSAGE + " is missing in the XML document.");
                }

                
                SetConnectionLimit(config);

                if (logger != null)
                {
                    logger.LogRequest(request, config.Demo);
                }

                // obtain a copy of the request document enclosed in a SOAP envelope
                XmlDocument doc = SoapWrap(request, nspace);

                //Get the X509 cert and sign the SOAP Body    
                string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);

                X509Certificate2 cert = null;

                X509Certificate2Collection collection = new X509Certificate2Collection();
                collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                foreach (X509Certificate2 cert1 in collection)
                {
                    if (cert1.Subject.Contains(config.MerchantID))
                    {
                        cert = cert1;
                        break;
                    }
                }
                
                SignDocument(cert, doc);

                // convert the document into an array of bytes using the
                // encoding specified in the XML declaration line.
                Encoding enc = GetEncoding(doc);
                byte[] requestBytes = enc.GetBytes(doc.OuterXml);


                // create an HttpWebRequest object and set its properties
                HttpWebRequest httpRequest
                    = (HttpWebRequest)WebRequest.Create(
                        config.EffectiveServerURL);
                httpRequest.Method = "POST";
                httpRequest.ContentLength = requestBytes.Length;
                httpRequest.UserAgent = ".NET XML";

                // set the timeout
                httpRequest.Timeout = config.Timeout * 1000;

                if (mProxy != null)
                {
                    // assign our pre-created WebProxy object to the 
                    // HttpWebRequest object's Proxy property.
                    httpRequest.Proxy = mProxy;
                }

                // obtain the request stream and write the byte array to it.
                Stream stream = httpRequest.GetRequestStream();
                stream.Write(requestBytes, 0, requestBytes.Length);
                stream.Close();

                // send request and get response.
                WebResponse webResponse = httpRequest.GetResponse();

                // read returned XML document.
                XmlDocument reply = ReadXml(webResponse);

                XmlDocument unwrapped = SoapUnwrap(reply, nspace);

                if (logger != null)
                {
                    logger.LogReply(unwrapped, config.Demo);
                }

                // return the XML document without the SOAP envelope.
                return (unwrapped);
            }
            catch (WebException we)
            {
                // if we got HTTP status 500 (Internal Server Error), it could
                // mean, the server threw a fault, in which case, we load the
                // xml document from the HTTP body and throw a FaultException.

                // The status would be ProtocolError if we did get HTTP 500
                // and Response should not be null but we check for null just
                // in case.
                if (we.Status == WebExceptionStatus.ProtocolError &&
                    we.Response != null)
                {
                    HttpWebResponse response = (HttpWebResponse)we.Response;

                    // InternalServerError corresponds to HTTP 500.  And we
                    // proceed only if there's anything in the response body.
                    // That is, the contentLength is greater than zero.
                    if (response.StatusCode
                        == HttpStatusCode.InternalServerError &&
                        response.ContentLength > 0)
                    {
                        try
                        {
                            // read the fault document and throw a
                            // FaultException.
                            FaultException fe
                                = new FaultException(
                                    ReadXml(response), nspace);
                            if (logger != null)
                            {
                                logger.LogFault(fe.LogString);
                            }
                            throw;
                        }
                        catch (XmlException)
                        {
                            if (logger != null)
                            {
                                logger.LogException(we);
                            }

                            // the response body is not a valid xml document.
                            // It is therefore not a fault.  Rethrow the
                            // WebException object.
                            throw;
                        }

                    }
                }

                if (logger != null)
                {
                    logger.LogException(we);
                }

                // the server did not throw a fault.  Rethrow the WebException
                // object.
                throw;
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                throw;
            }
        }
예제 #22
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="request">Hashtable containing the request fields and their values.</param>
        /// <returns>Hashtable containing the reply fields and their values.</returns>
        public static Hashtable RunTransaction(
            Configuration config, Hashtable request)
        {
            Logger logger=null;
            NVPTransactionProcessorClient proc=null;
            try
            {
                DetermineEffectiveMerchantID(ref config, request);
                SetVersionInformation(request);
                logger = PrepareLog(config);
                SetConnectionLimit(config);

                //Setup custom binding with HTTPS + Body Signing 
                CustomBinding currentBinding = getWCFCustomBinding();

                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers = new AddressHeaderCollection();
                EndpointAddress endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new NVPTransactionProcessorClient(currentBinding, endpointAddress))
                {

                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;


                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    if (logger != null)
                    {
                        logger.LogRequest(request, config.Demo);
                    }

                    // send request now, converting the hashtable request into
                    // a string, and the string reply back into a hashtable.

                    string resp = proc.runTransaction(Hash2String(request));


                    Hashtable reply = String2Hash(resp);

                    if (logger != null)
                    {
                        logger.LogReply(reply, config.Demo);
                    }

                    return (reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
예제 #23
0
		/// <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));
		}
예제 #24
0
 private bool TryPassword(string password)
 {
     try
     {
         var collection = new X509Certificate2Collection();
         collection.Import(certificatePath.Text, password, X509KeyStorageFlags.PersistKeySet);
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
		/// <summary>
		/// Imports certificates and keys from a pkcs12-encoded stream.
		/// </summary>
		/// <remarks>
		/// Imports certificates and keys from a pkcs12-encoded stream.
		/// </remarks>
		/// <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");

			var rawData = ReadAllBytes (stream);
			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 ();
		}
        internal X509Certificate2Collection LoadCertificateFromFile()
        {
            FileInfo certFile = new FileInfo(this.GetUnresolvedProviderPathFromPSPath(this.FilePath));
            if (!certFile.Exists)
            {
                throw new FileNotFoundException(string.Format(KeyVaultProperties.Resources.CertificateFileNotFound, this.FilePath));
            }

            var certificates = new X509Certificate2Collection();
            certificates.Import(certFile.FullName);
            return certificates;
        }