コード例 #1
2
 public static string GetCertData(string pfxPath, string password)
 {
     if (!string.IsNullOrEmpty(pfxPath))
     {                
         var cert = new X509Certificate2();
         cert.Import(pfxPath, password, X509KeyStorageFlags.Exportable);
         return cert.HasPrivateKey
             ? Convert.ToBase64String(cert.Export(X509ContentType.Pfx, password))
             : Convert.ToBase64String(cert.Export(X509ContentType.Pkcs12));
     }
     return null;
 }
コード例 #2
0
ファイル: CertHelper.cs プロジェクト: jDolba/dol0039-bp
        /// <summary>
        /// Create .cer or .pfx file from an X509Certificate2 object
        /// </summary>
        /// <param name="cert">an X509Certificate2 object</param>
        /// <param name="NewCerFile">name of generated .cer file</param>
        /// <returns>full path of newly generated .cer file</returns>
        public static string CreateCertFile(X509Certificate2 cert, string NewCertFile, CertFileType certFileType)
        {
            byte[] CerContents;

            // Write the content to a local .cer file so that users can upload it into Azure
            if (certFileType == CertFileType.Cer)
            {
                CerContents = cert.Export(X509ContentType.Cert);
            }
            else
            {
                CerContents = cert.Export(X509ContentType.Pfx, PasswordForCert);
            }

            using (FileStream fileStream = new FileStream(NewCertFile, FileMode.Create))
            {

                for (int i = 0; i < CerContents.Length; i++)
                {
                    fileStream.WriteByte(CerContents[i]);
                }

                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Close();
            }

            return System.IO.Path.GetFullPath(NewCertFile);
        }
コード例 #3
0
ファイル: CertUtils.cs プロジェクト: johnkors/azure-sdk-tools
 public static byte[] GetCertificateData(X509Certificate2 cert, string password)
 {
     try
     {
         return cert.HasPrivateKey ? cert.Export(X509ContentType.Pfx, password) : cert.Export(X509ContentType.Pkcs12, password);
     }
     catch (CryptographicException)
     {
         return cert.HasPrivateKey ? cert.RawData : cert.Export(X509ContentType.Pkcs12, password);
     }
 }
コード例 #4
0
ファイル: TestHost.cs プロジェクト: sveinfid-prospa/wcf
        public Stream PeerCert(bool asPem)
        {
            X509Certificate2 peerCert = CertificateFromFriendlyName(StoreName.TrustedPeople, StoreLocation.LocalMachine, "WCF Bridge - UserPeerTrustCertificateResource");

            byte[] response;

            if (peerCert == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                response = Encoding.UTF8.GetBytes("Peer certificate not found on system");
            }
            else
            {
                if (asPem)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-peer-cert.crt\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pem-file";
                    response = Encoding.ASCII.GetBytes(GetCertificateAsPem(peerCert));
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-peer-cert.pfx\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pkcs12";
                    response = peerCert.Export(X509ContentType.Pfx, "test");
                }
            }

            return(new MemoryStream(response));
        }
コード例 #5
0
ファイル: TestHost.cs プロジェクト: sveinfid-prospa/wcf
        public Stream ClientCert(bool asPem)
        {
            X509Certificate2 clientCert = CertificateFromSubject(StoreName.My, StoreLocation.LocalMachine, "WCF Client Certificate");

            byte[] response;

            if (clientCert == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                response = Encoding.UTF8.GetBytes("Client certificate not found on system");
            }
            else
            {
                if (asPem)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-client-cert.crt\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pem-file";
                    response = Encoding.ASCII.GetBytes(GetCertificateAsPem(clientCert));
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-client-cert.pfx\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pkcs12";
                    response = clientCert.Export(X509ContentType.Pfx, "test");
                }
            }

            return(new MemoryStream(response));
        }
コード例 #6
0
 public static byte[] GetPrivateKey(string dir)
 {
     var fileName = CloudBackedStore.RootDir + "\\" + dir + "\\" + CertDir + "\\oidcertificate.cer";
     var cert = new X509Certificate2(fileName);
     var priv = cert.Export(X509ContentType.Pfx, "password");
     return priv;
 }
コード例 #7
0
ファイル: Client.cs プロジェクト: ridhouan/teamlab.v6.5
        public Client()
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            var storeCertificates = store.Certificates.Cast<X509Certificate2>()
                .Where(x => CertSubject.Parse(x.Subject).Get(CertSubject.KnownField.CanonicalName) == "www.teamlab.com")
                .Where(x => x.HasPrivateKey)
                .Where(x => x.NotAfter > DateTime.UtcNow)
                .Where(x => x.NotBefore < DateTime.UtcNow)
                .OrderByDescending(x=>x.NotBefore)
                .ThenByDescending(x=>x.NotAfter);

            _clientCertificate = storeCertificates.FirstOrDefault(x=>x.Verify());
            if (_clientCertificate == null)
                throw new LicenseCertificateException("Can't find valid TM cert");


            if (!_clientCertificate.HasPrivateKey)
                throw new LicenseCertificateException("Client certificate should conaint PK");

            _export = _clientCertificate.Export(X509ContentType.Cert);
            //Check
            var test = new X509Certificate2(_export);
            if (test.HasPrivateKey)
                throw new LicenseCertificateException("Exported certificate shouldn't conaint PK");

            _clientId = _clientCertificate.GetSerialNumber();
        }
コード例 #8
0
        private void InstallLinux(MS509.X509Certificate2 cert)
        {
            var myStore = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".dotnet/corefx/cryptography/x509stores/my");

            Directory.CreateDirectory(myStore);
            File.WriteAllBytes(Path.Combine(myStore, $"{cert.Thumbprint}.pfx"), cert.Export(MS509.X509ContentType.Pfx));
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: hendryluk/twitterbigdata
        /// <summary>
        /// Adds the client and service certificate that the provisioning call returned to the local machine's certificate store.
        /// Also, the certificates will be saved as files in the executable's folder, so that they can be installed
        /// on other machines that need to connect to the newly provisioned Austin instance.
        /// </summary>
        /// <param name="response">Provisioning response including the certificates.</param>
        private static void AddServiceAndClientCertsToStore(CreateResponse response)
        {
            // Remove existing certificates from store
            string serviceName = ConfigurationManager.AppSettings["HostedServiceName"];
            string clientCertName = string.Format("StreamInsight Client ({0})", serviceName);
            string serviceCertName = string.Format("{0}.cloudapp.net", serviceName);

            Console.WriteLine("Removing old certificates from local store...");
            CertificateHelper.RemoveCertificate(clientCertName, StoreName.My, StoreLocation.CurrentUser);
            CertificateHelper.RemoveCertificate(serviceCertName, StoreName.TrustedPeople, StoreLocation.CurrentUser);

            // Add new certificates
            Console.WriteLine("Adding certificates to local store...");
            byte[] clientRawCert = Convert.FromBase64String(response.ClientCertificate);
            byte[] serviceRawCert = Convert.FromBase64String(response.ServiceCertificate);
            X509Certificate2 clientCert = new X509Certificate2(clientRawCert, response.ClientCertificatePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            X509Certificate2 serviceCert = new X509Certificate2(serviceRawCert);
            CertificateHelper.AddCertificate(clientCert, StoreName.My, StoreLocation.CurrentUser);
            CertificateHelper.AddCertificate(serviceCert, StoreName.TrustedPeople, StoreLocation.CurrentUser);

            // Save certificates to file
            string clientCertFileName = serviceName + "_client.pfx";
            string serviceCertFileName = serviceName + "_service.cer";
            File.WriteAllBytes(clientCertFileName, clientCert.Export(X509ContentType.Pfx, ConfigurationManager.AppSettings["ClientCertificatePassword"]));
            File.WriteAllBytes(serviceCertFileName, serviceCert.Export(X509ContentType.Cert));
            Console.WriteLine("Client Certificate also saved as {0}.", clientCertFileName);
            Console.WriteLine("Service Certificate also saved as {0}.", serviceCertFileName);
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: mind0n/hive
		static public X509Certificate GetCert(string cn, TimeSpan expirationLength, string pwd = "", string filename = null)
		{
			// http://stackoverflow.com/questions/18339706/how-to-create-self-signed-certificate-programmatically-for-wcf-service
			// http://stackoverflow.com/questions/21629395/http-listener-with-https-support-coded-in-c-sharp
			// https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.storename(v=vs.110).aspx
			// create DN for subject and issuer
			System.Security.Cryptography.X509Certificates.X509Certificate cert = null;
            if (filename != null && File.Exists(filename))
            {
				cert = new X509Certificate2(filename, pwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
			}
			else
            {
				var base64encoded = string.Empty;
				base64encoded = CreateCertContent(cn, expirationLength, pwd);
				cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(
					System.Convert.FromBase64String(base64encoded), pwd,
					// mark the private key as exportable (this is usually what you want to do)
					// mark private key to go into the Machine store instead of the current users store
					X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
					);
				File.WriteAllBytes(filename, cert.Export(X509ContentType.Pfx, pwd));
			}
			// instantiate the target class with the PKCS#12 data (and the empty password)

			return cert;
		}
コード例 #11
0
        public void TesttMethod1()
        {
            var certificate = ConfigurationManager.AppSettings["SubscriptionCertificate"];
            X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(certificate), "", X509KeyStorageFlags.Exportable);

            File.WriteAllBytes(@"c:\users\skp\documents\cert.pfx", cert.Export(X509ContentType.Pfx));
        }
コード例 #12
0
ファイル: certmgr.cs プロジェクト: SickheadGames/BRUTE.mono
        static void Put(ObjectType type, X509Store store, string file, bool machine, bool pem, bool verbose)
        {
            if (String.IsNullOrEmpty(file))
            {
                Console.Error.WriteLine("error: no filename provided to put the certificate.");
                Help();
                return;
            }

            switch (type)
            {
            case ObjectType.Certificate:
                for (int i = 0; i < store.Certificates.Count; i++)
                {
                    Console.WriteLine("==============Certificate # {0} ==========", i + 1);
                    DisplayCertificate(store.Certificates[i], machine, verbose);
                }
                int selection;
                Console.Write("Enter cert # from the above list to put-->");
                if (!int.TryParse(Console.ReadLine(), out selection) || selection > store.Certificates.Count)
                {
                    Console.Error.WriteLine("error: invalid selection.");
                    return;
                }

                SSCX.X509Certificate2 cert = new SSCX.X509Certificate2(store.Certificates[selection - 1].RawData);
                byte[] data = null;
                if (pem)
                {
                    data = ToPEM("CERTIFICATE", cert.Export(SSCX.X509ContentType.Cert));
                }
                else
                {
                    data = cert.Export(SSCX.X509ContentType.Cert);
                }

                using (FileStream fs = File.Create(file)) {
                    fs.Write(data, 0, data.Length);
                }

                Console.WriteLine("Certificate put to {0}.", file);
                break;

            default:
                throw new NotSupportedException("Put " + type + " not supported yet");
            }
        }
コード例 #13
0
        /// <summary>
        /// Create a new file with the certificate
        /// </summary>
        /// <param name="certificate">The certificate</param>
        /// <param name="outputFileName">The output file name</param>
        private static void WriteCertificate(X509Certificate2 certificate, string outputFileName)
        {
            // This password is the one attached to the PFX file. Use 'null' for no password.
            const string password = "******";
            var          bytes    = certificate.Export(X509ContentType.Pfx, password);

            File.WriteAllBytes(outputFileName, bytes);
        }
コード例 #14
0
        internal static string GeneratePem(X509Certificate2 cert)
        {
            string base64Cert = Convert.ToBase64String(cert.Export(X509ContentType.Cert));
            var    section    = "CERTIFICATE";
            var    header     = String.Format("-----BEGIN {0}-----", section);
            var    footer     = String.Format("-----END {0}-----", section);

            return(header + "\n" + base64Cert + "\n" + footer);
        }
コード例 #15
0
        static void Main(string[] args)
        {
            try
            {
                /*
                 * This program is used to change the csp name in a pfx file.
                 */
                PrintLine("Set correct CSP name in pfx file.");
                PrintLine("\n\nEnter path to PFX file.");
                var pfxPath = Prompt().Trim();
                PrintLine("\n\nEnter password to the PFX file.");
                var pfxPasswords = Prompt();

                var file = new FileInfo(pfxPath);
                if (!file.Exists || file.Directory == null)
                {
                    PrintLine("\nCould not find pfx file.");
                    return;
                }

                var newPfxPath = file.Directory.FullName + "\\correctCsp" + file.Name;
                PrintLine("New pfx file will be: " + newPfxPath);
                var newFile = new FileInfo(newPfxPath);
                if (newFile.Exists)
                {
                    PrintLine("\nFile already exists.");
                    return;
                }

                var oldPfx = new X509Certificate2(pfxPath, pfxPasswords, X509KeyStorageFlags.Exportable);
                var newPfx = new X509Certificate2(oldPfx);

                var csp = (RSACryptoServiceProvider)oldPfx.PrivateKey;

                var cspParams = new CspParameters();
                cspParams.KeyContainerName = "somealias";
                cspParams.ProviderType = 24; //Microsoft Enhanced RSA and AES Cryptographic Provider
                var rsaAlg = new RSACryptoServiceProvider(oldPfx.PrivateKey.KeySize, cspParams);

                rsaAlg.ImportParameters(csp.ExportParameters(true));
                newPfx.PrivateKey = rsaAlg;
                using (var fileStream = new FileStream(newPfxPath, FileMode.CreateNew))
                {
                    using (var writer = new BinaryWriter(fileStream))
                    {
                        writer.Write(newPfx.Export(X509ContentType.Pfx, pfxPasswords));
                    }
                }
            }
            catch (Exception e)
            {
                PrintLine(e.StackTrace);
                Prompt();
            }
        }
コード例 #16
0
        /// <summary>
        /// Initialisiert eine neue Instanz der <see cref="Pkcs7EncryptionHandler"/> Klasse.
        /// </summary>
        /// <param name="senderCertificate">Das X509-Zertifikat des Absenders (PKCS#12)</param>
        /// <param name="receiverCertificate">Das X509-Zertifikat des Empfängers</param>
        /// <param name="oldSenderCertificates">Die abgelaufenen X509-Zertifikate des Absenders</param>
        public Pkcs7EncryptionHandler(X509Certificate2 senderCertificate, X509Certificate2 receiverCertificate, IEnumerable<X509Certificate2> oldSenderCertificates = null)
        {
#if NET45
            _encryptionHandler = new NativePkcs7EncryptionHandler(senderCertificate, receiverCertificate, oldSenderCertificates);
#else
            var senderCert = new Pkcs12Store(new MemoryStream(senderCertificate.Export(X509ContentType.Pkcs12)), new char[0]);
            var receiverCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(receiverCertificate.RawData);
            var oldSenderCerts = oldSenderCertificates?.Select(cert => new Pkcs12Store(new MemoryStream(cert.Export(X509ContentType.Pkcs12)), new char[0]));
            _encryptionHandler = new BouncyCastlePkcs7EncryptionHandler(senderCert, receiverCert, oldSenderCerts);
#endif
        }
コード例 #17
0
        private ApplicationGatewaySslCertificate CreateSslCertificate(string sslCertName, string password)
        {
            X509Certificate2 cert = new X509Certificate2("ApplicationGatewayCertificate\\GW5000.pfx", password, X509KeyStorageFlags.Exportable);
            ApplicationGatewaySslCertificate sslCert = new ApplicationGatewaySslCertificate()
            {
                Name = sslCertName,
                Data = Convert.ToBase64String(cert.Export(X509ContentType.Pfx, password)),
                Password = password
            };

            return sslCert;
        }
コード例 #18
0
        public byte[] GetClientCert(bool exportAsPem)
        {
            X509Certificate2 clientCert = CertificateFromSubject(StoreName.My, StoreLocation.LocalMachine, "WCF Client Certificate");

            if (exportAsPem)
            {
                return(Encoding.ASCII.GetBytes(GetCertificateAsPem(clientCert)));
            }
            else
            {
                return(clientCert.Export(X509ContentType.Pfx, "test"));
            }
        }
コード例 #19
0
        private static void SaveCertToLocalFile(X509Certificate2 cert, string fileName, string filePath)
        {
            var certBuffer = cert.Export(X509ContentType.Pfx, certPassword);

            try
            {
                File.WriteAllBytes(filePath + "/" + fileName, certBuffer);
            }
            catch (Exception ex)
            {
                throw new Exception(null, ex);
            }
        }
コード例 #20
0
        internal static byte[] ExportToP12(CspParameters cspParam, X509Certificate cert, string password)
        {
            Sys.X509Certificate2 sysCert = new Sys.X509Certificate2(cert.GetEncoded());;

            Sys.X509Store store = new Sys.X509Store(Sys.StoreLocation.CurrentUser);
            store.Open(Sys.OpenFlags.ReadWrite);
            store.Add(sysCert);

            sysCert = store.Certificates[0];

            // Export the certificate including the private key.
            return(sysCert.Export(Sys.X509ContentType.Pkcs12, password));
        }
コード例 #21
0
        public void ExportCertificateAsPfx(X509Certificate2 certificate, String outputFileName, String password = null)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            if (String.IsNullOrWhiteSpace(outputFileName))
            {
                throw new ArgumentException($"Argument \"{nameof(outputFileName)}\" cannot be null or empty.", nameof(outputFileName));
            }

            Byte[] bytes = certificate.Export(X509ContentType.Pfx, password);

            File.WriteAllBytes(outputFileName, bytes);
        }
コード例 #22
0
ファイル: Authentication.cs プロジェクト: modulexcite/docs-8
		public void ThirdPartyOAuth()
		{
			dynamic response = new ExpandoObject();

			var userId = "users/ayende";
			var certificate = new X509Certificate2();
			var authorizedDatabases = new[] { "*" };
			var key = certificate.Export(X509ContentType.Pkcs12);

			#region authenticate_3
			var token = AccessToken.Create(key, userId, authorizedDatabases);
			response.Write(token.Serialize());

			#endregion
		}
コード例 #23
0
ファイル: Pkcs12.cs プロジェクト: Xamarui/acme.net
        public void CreatePfxFile(RSAParameters key, string pathToCertificate, string password, string pathToPfx)
        {
#if DNXCORE50
            throw new PlatformNotSupportedException("pfx export is not supported on core clr");            
#else
            var csp = new CspParameters {KeyContainerName = "oocx-acme-temp"};
            var rsa2 = new RSACryptoServiceProvider(csp);
            rsa2.ImportParameters(key);

            var certBytes = File.ReadAllBytes(pathToCertificate);
            var certificate = new X509Certificate2(certBytes,password, X509KeyStorageFlags.Exportable) {PrivateKey = rsa2};            
            var pfxBtes = certificate.Export(X509ContentType.Pkcs12, password);
            File.WriteAllBytes(pathToPfx, pfxBtes);
#endif
        }
        public PSApplicationGatewayAuthenticationCertificate NewObject()
        {
            X509Certificate2 cert = new X509Certificate2(CertificateFile);

            var authCertificate = new PSApplicationGatewayAuthenticationCertificate();

            authCertificate.Name = this.Name;
            authCertificate.Data = Convert.ToBase64String(cert.Export(X509ContentType.Cert));
            authCertificate.Id =
                ApplicationGatewayChildResourceHelper.GetResourceNotSetId(
                    this.NetworkClient.NetworkManagementClient.SubscriptionId,
                    Microsoft.Azure.Commands.Network.Properties.Resources.ApplicationGatewayAuthenticationCertificateName,
                    this.Name);

            return authCertificate;
        }
コード例 #25
0
        protected override async Task OnExecute()
        {
            // Get the certificate
            var secret = await ReadSecret(Key);

            if (secret == null)
            {
                await Console.WriteErrorLine(Strings.Secrets_NoSuchSecret, Key);
                return;
            }

            if (secret.Type != SecretType.Certificate)
            {
                await Console.WriteErrorLine(Strings.Certs_UploadCommand_SecretIsNotACertificate, Key);
                return;
            }

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

            // Write to our own temp file because the X509Certificate2 ctor
            // that takes a byte array writes a temp file and then never cleans it up
            string temp = Path.GetTempFileName();
            try
            {
                File.WriteAllBytes(temp, Convert.FromBase64String(secret.Value));
                var cert = new X509Certificate2(temp, String.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
                if (PublicOnly)
                {
                    // Strip the private key
                    File.WriteAllBytes(temp, cert.Export(X509ContentType.Cert));
                    cert = new X509Certificate2(temp, String.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
                }
                
                await Console.WriteInfoLine(Strings.Certs_ImportCommand_Importing, cert.Thumbprint, StoreName, StoreLocation);
                store.Add(cert);
                store.Close();
            }
            finally
            {
                if (File.Exists(temp))
                {
                    File.Delete(temp);
                }
            }
        }
        public PSApplicationGatewaySslCertificate NewObject()
        {
            X509Certificate2 cert = new X509Certificate2(CertificateFile, Password, X509KeyStorageFlags.Exportable);

            var sslCertificate = new PSApplicationGatewaySslCertificate();

            sslCertificate.Name = this.Name;
            sslCertificate.Data = Convert.ToBase64String(cert.Export(X509ContentType.Pfx, Password));
            sslCertificate.Password = this.Password;
            sslCertificate.Id =
                ApplicationGatewayChildResourceHelper.GetResourceNotSetId(
                    this.NetworkClient.NetworkResourceProviderClient.Credentials.SubscriptionId,
                    Microsoft.Azure.Commands.Network.Properties.Resources.ApplicationGatewaySslCertificateName,
                    this.Name);

            return sslCertificate;
        }
コード例 #27
0
ファイル: CertUtils.cs プロジェクト: ranjitk9/azure-sdk-tools
        public static bool HasExportablePrivateKey(X509Certificate2 cert)
        {
            if (!cert.HasPrivateKey)
            {
                return false;
            }

            try
            {
                cert.Export(X509ContentType.Pfx);
            }
            catch (CryptographicException)
            {
                return false;
            }
            return true;
        }
コード例 #28
0
        //TODO: Password is SecureString?
        internal static AddServiceCertificateInfo Create(X509Certificate2 certificate, string password)
        {
            Validation.NotNull(certificate, "certificate");
            //password might be null...

            if (certificate.HasPrivateKey == false) throw new ArgumentException(Resources.CertificateNoPrivateKey);

            byte[] certData = certificate.Export(X509ContentType.Pfx, password);

            string data = Convert.ToBase64String(certData);

            return new AddServiceCertificateInfo
            {
                Data = data,
                CertificateFormat = certFormat,
                Password = password
            };
        }
コード例 #29
0
        public static List<Byte> GetCertificateBytes(string certificateFilePath)
        {
            List<Byte> certificateBytes = null;

            try
            {
                X509Certificate2 certificate = new X509Certificate2(certificateFilePath);

                certificateBytes = certificate.Export(X509ContentType.Cert).ToList<Byte>();
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Error in GetCertificateBytes(string certificateFilePath)  Error: {0}", ex.Message));

                certificateBytes = null;
            }

            return certificateBytes;
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: yonglehou/Bermuda
        static List<Byte> GetCertificateBytes(string certificateFilePath)
        {
            List<Byte> certificateBytes = null;

            try
            {
                X509Certificate2 certificate = new X509Certificate2(certificateFilePath);

                certificateBytes = certificate.Export(X509ContentType.Cert).ToList<Byte>();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error in GetCertificateBytes(string certificateFilePath)  Error: {0}\n{1}", ex.Message,
                                  ex.InnerException != null ? ex.InnerException.Message : string.Empty));

                certificateBytes = null;
            }

            return certificateBytes;
        }
コード例 #31
0
        /// <summary>
        /// Encodes the specified email.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="certificateFilePath">The certificate file path.</param>
        /// <returns></returns>
        public static string Encode(string email, string certificateFilePath)
        {
            var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var issueTime = DateTime.Now;

            var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
            var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds; // Expiration time is up to 1 hour, but lets play on safe side

            var payload = new JwtPayload
            {
                iss = email,
                scope = "https://www.googleapis.com/auth/gan.readonly",
                aud = "https://accounts.google.com/o/oauth2/token",
                exp = exp,
                iat = iat
            };

            var certificate = new X509Certificate2(certificateFilePath, "notasecret");
            var privateKey = certificate.Export(X509ContentType.Cert);
            return JsonWebToken<JwtPayload>.Encode(payload, privateKey, JwtHashAlgorithm.RS256);
        }
コード例 #32
0
        public static void NewCertificate(byte[] certificateData)
        {
            //var cert = (Org.BouncyCastle.X509.X509Certificate)new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(Encoding.UTF8.GetString(certificateData))).ReadObject();


            var store = new Pkcs12Store(new MemoryStream(certificateData), "".ToCharArray());
            //var certificateEntry = new X509CertificateEntry(cert);
            string friendlyName       = store.Aliases.Cast <string>().First();
            X509CertificateEntry cert = store.GetCertificate(friendlyName);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { cert });

            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            Certificate = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.Exportable);
            byte[] data = Certificate.Export(X509ContentType.Pfx, password);
            File.WriteAllBytes(Config.AppSettings["CertFile"].Value, data);

            Certificate = new X509Certificate2(Config.AppSettings["CertFile"].Value, password);
        }
コード例 #33
0
        protected override async Task OnExecute()
        {
            // Open the store
            var store = await OpenSecretStore();

            // Load the cert file
            var cert = new X509Certificate2(File, String.Empty, X509KeyStorageFlags.Exportable);
            if (!cert.HasPrivateKey)
            {
                await Console.WriteErrorLine(Strings.Secrets_StoreCertCommand_CertificateHasNoPrivateKey);
                return;
            }

            // Save to a string
            string data = Convert.ToBase64String(cert.Export(X509ContentType.Pkcs12, String.Empty));

            // Determine expiry
            var expiresAt = cert.NotAfter;

            // Save the certificate secret
            // Cert thumbprints are universal, no datacenter-scope needed
            var certKey = new SecretName("cert:" + cert.Thumbprint, null);
            await Console.WriteInfoLine(Strings.Secrets_StoreCertCommand_SavingCertificate, certKey.Name, expiresAt);
            if (!WhatIf)
            {
                var secret = new Secret(certKey, data, DateTime.UtcNow, expiresAt, SecretType.Certificate);
                await store.Write(secret, "nucmd storecert");
            }

            await Console.WriteInfoLine(Strings.Secrets_StoreCertCommand_SavingCertificateReference, Key, expiresAt);
            if (!WhatIf)
            {
                var secret = new Secret(new SecretName(Key, Datacenter), certKey.ToString(), DateTime.UtcNow, expiresAt, SecretType.Link);
                await store.Write(secret, "nucmd storecert");
            }
        }
コード例 #34
0
        public static byte[] CreatePKCS12KeyStoreWithPublicPrivateKeyPair(AsymmetricCipherKeyPair keyPair, string passphrase)
        {
            var keyContainerName = new Guid().ToString();
            var x509V3CertificateGenerator = new X509V3CertificateGenerator();

            // The fields that Thali cares about
            x509V3CertificateGenerator.SetSignatureAlgorithm(SignerAlgorithm);
            x509V3CertificateGenerator.SetPublicKey(keyPair.Public);

            // To avoid getting an InvalidOperationExceptoin when calling generate below we have to
            // specify a certain number of mandatory fields as explained in http://blog.differentpla.net/post/53
            // We don't actually care about these fields but Bouncy Castle does
            var serialNumber = BigInteger.ProbablePrime(120, new Random());
            x509V3CertificateGenerator.SetSerialNumber(serialNumber);
            x509V3CertificateGenerator.SetSubjectDN(X500Name);
            x509V3CertificateGenerator.SetIssuerDN(X500Name);
            x509V3CertificateGenerator.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            x509V3CertificateGenerator.SetNotAfter(DateTime.Now.AddDays(ExpirationPeriodForCertsInDays));

            var bouncyCastleX509Cert = x509V3CertificateGenerator.Generate(keyPair.Private);
            try
            {
                var msX509Cert = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCastleX509Cert))
                {
                    PrivateKey = ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private, keyContainerName)
                };
                var pkcs12Store = msX509Cert.Export(X509ContentType.Pkcs12, passphrase);
                return pkcs12Store;
            }
            finally
            {
                var cspParameters = new CspParameters { KeyContainerName = keyContainerName };
                var rsaCryptoServiceProvider = new RSACryptoServiceProvider(cspParameters) { PersistKeyInCsp = false };
                rsaCryptoServiceProvider.Clear();
            }
        }
コード例 #35
0
        /// <summary>
        /// Uploads a certificate given a valid service certificate and password
        /// </summary>
        /// <param name="certificate">The certificate being uploaded</param>
        /// <param name="password">The .pfx password for the certificate</param>
        /// <param name="includePrivateKey">The .pfx password for the certificate</param>
        public void UploadServiceCertificate(X509Certificate2 certificate, string password = "", bool includePrivateKey = false)
        {
            var certBytes = includePrivateKey
                                ? certificate.Export(X509ContentType.Pkcs12, password)
                                : certificate.Export(X509ContentType.Cert);

            var cert = new AddServiceCertificateCommand(certBytes, password, Name)
            {
                SubscriptionId = SubscriptionId,
                Certificate = ManagementCertificate
            };
            cert.Execute();
        }
コード例 #36
0
        /// <summary cref="ICertificateStore.Add(X509Certificate2)" />
        public Task Add(X509Certificate2 certificate)
        {
            if (certificate == null) throw new ArgumentNullException("certificate");
         
            lock (m_lock)
            {
                byte[] data = null;

                // check for certificate file.
                Entry entry = Find(certificate.Thumbprint);

                if (entry != null)
                {
                    throw new ArgumentException("A certificate with the same thumbprint is already in the store.");
                }

                if (certificate.HasPrivateKey)
                {
                    data = certificate.Export(X509ContentType.Pkcs12, String.Empty);
                }
                else
                {
                    data = certificate.RawData;
                }

                // build file name.
                string fileName = GetFileName(certificate);

                // write the private and public key.
                WriteFile(data, fileName, certificate.HasPrivateKey);

                if (certificate.HasPrivateKey)
                {
                    WriteFile(certificate.RawData, fileName, false);
                }

                m_lastDirectoryCheck = DateTime.MinValue;
            }
            return Task.CompletedTask;
        }
コード例 #37
0
        public AsymmetricKeyParameter GenerateCACertificate(string subjectName, string privateKeyFilePassword, string rootsigningCertFileName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            KeyUsage keyUsage = new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            #region Private Key

            // correcponding private key
            PrivateKeyInfo pinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(pinfo.ParsePrivateKey().GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            #endregion

            // Add CA certificate to Root store
            AddCertToStore(x509, System.Security.Cryptography.X509Certificates.StoreName.Root, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

            File.WriteAllBytes(rootsigningCertFileName.Replace(".pfx", ".cer"), x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert));

            // Export Certificate with private key
            File.WriteAllBytes(rootsigningCertFileName, x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, privateKeyFilePassword));

            return(issuerKeyPair.Private);
        }
コード例 #38
0
        public System.Security.Cryptography.X509Certificates.X509Certificate2 GenerateSelfSignedCertificate(string certificateName, List <string> subjectAlternateNames, string certificateFileName, string privateKeyFilePassword, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength)
        {
            string subjectName = string.Format("CN={0}", certificateName);

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);

            // original code var issuerDN = issuerName;
            var issuerDN = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            KeyUsage keyUsage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            // Add the “Extended Key Usage” attribute, specifying “server authentication”.
            var usages = new[] { KeyPurposeID.IdKPServerAuth };

            certificateGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(usages));

            /* DNS Name=*.fullyqualified.domainname.com */
            if (subjectAlternateNames.Count <= 1)
            {
                /* the <=1 is for the simple reason of showing an alternate syntax .. */
                foreach (string subjectAlternateName in subjectAlternateNames)
                {
                    GeneralName  altName        = new GeneralName(GeneralName.DnsName, subjectAlternateName);
                    GeneralNames subjectAltName = new GeneralNames(altName);
                    certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
                }
            }
            else
            {
                //Asn1Encodable[] ansiEncodeSubjectAlternativeNames = new Asn1Encodable[]
                // {
                // //new GeneralName(GeneralName.DnsName, “*.fullyqualified.domainname.com”),
                // new GeneralName(GeneralName.DnsName, “*.fullyqualified.domainname.com”)
                // };

                List <Asn1Encodable> asn1EncodableList = new List <Asn1Encodable>();
                foreach (string subjectAlternateName in subjectAlternateNames)
                {
                    asn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternateName));
                }

                DerSequence subjectAlternativeNamesExtension = new DerSequence(asn1EncodableList.ToArray());
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            PrivateKeyInfo pinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(pinfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);

            File.WriteAllBytes(certificateFileName.Replace(".pfx", ".cer"), x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert));

            // Export Certificate with private key
            File.WriteAllBytes(certificateFileName, x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, privateKeyFilePassword));

            return(x509);
        }
コード例 #39
0
        /// <summary>
        /// Static method used to create a certificate and return as a .net object
        /// </summary>
        public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false, string exportDirectory = null)
        {
            // generate a key pair using RSA
            var generator = new RsaKeyPairGenerator();
            // keys have to be a minimum of 2048 bits for Azure
            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair();
            // get a copy of the private key
            AsymmetricKeyParameter privateKey = cerKp.Private;

            // create the CN using the name passed in and create a unique serial number for the cert
            var certName = new X509Name("CN=" + name);
            BigInteger serialNo = BigInteger.ProbablePrime(120, new Random());

            // start the generator and set CN/DN and serial number and valid period
            var x509Generator = new X509V3CertificateGenerator();
            x509Generator.SetSerialNumber(serialNo);
            x509Generator.SetSubjectDN(certName);
            x509Generator.SetIssuerDN(certName);
            x509Generator.SetNotBefore(start);
            x509Generator.SetNotAfter(end);
            // add the server authentication key usage
            var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);
            x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
            var extendedKeyUsage = new ExtendedKeyUsage(new[] {KeyPurposeID.IdKPServerAuth});
            x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());
            // algorithm can only be SHA1 ??
            x509Generator.SetSignatureAlgorithm("sha1WithRSA");

            // Set the key pair
            x509Generator.SetPublicKey(cerKp.Public);
            X509Certificate certificate = x509Generator.Generate(cerKp.Private);

            // export the certificate bytes
            byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword);

            // build the key parameter and the certificate entry
            var keyEntry = new AsymmetricKeyEntry(privateKey);
            var entry = new X509CertificateEntry(certificate);
            // build the PKCS#12 store to encapsulate the certificate
            var builder = new Pkcs12StoreBuilder();
            builder.SetUseDerEncoding(true);
            builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.Build();
            // create a memorystream to hold the output
            var stream = new MemoryStream(10000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();
            store.SetCertificateEntry("Created by Fluent Management", entry);
            store.SetKeyEntry("Created by Fluent Management", keyEntry, new[] { entry });
            store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

             // Create the equivalent C# representation
            var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable);
            // set up the PEM writer too
            if (exportDirectory != null)
            {
                var textWriter = new StringWriter();
                var pemWriter = new PemWriter(textWriter);
                pemWriter.WriteObject(cerKp.Private, "DESEDE", userPassword.ToCharArray(), new SecureRandom());
                pemWriter.Writer.Flush();
                string privateKeyPem = textWriter.ToString();
                using (var writer = new StreamWriter(Path.Combine(exportDirectory, cert.Thumbprint + ".pem")))
                    {
                        writer.WriteLine(privateKeyPem);
                    }
                // also export the certs - first the .pfx
                byte[] privateKeyBytes = cert.Export(X509ContentType.Pfx, userPassword);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".pfx"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(privateKeyBytes, 0, privateKeyBytes.Length);
                }
                // also export the certs - then the .cer
                byte[] publicKeyBytes = cert.Export(X509ContentType.Cert);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".cer"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(publicKeyBytes, 0, publicKeyBytes.Length);
                }
            }

            // if specified then this add this certificate to the store
            if (addtoStore)
                AddToMyStore(cert);

            return cert;
        }
コード例 #40
0
        public void Add(ICertificatePal certPal)
        {
            if (_readOnly)
            {
                // Windows compatibility: Remove only throws when it needs to do work, add throws always.
                throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly);
            }

            // This may well be the first time that we've added something to this store.
            Directory.CreateDirectory(_storePath);

            uint userId = Interop.Sys.GetEUid();
            EnsureDirectoryPermissions(_storePath, userId);

            OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal;

            using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles()))
            {
                string thumbprint = copy.Thumbprint;
                bool findOpenSlot;

                // The odds are low that we'd have a thumbprint collision, but check anyways.
                string existingFilename = FindExistingFilename(copy, _storePath, out findOpenSlot);

                if (existingFilename != null)
                {
                    if (!copy.HasPrivateKey)
                    {
                        return;
                    }

                    try
                    {
                        using (X509Certificate2 fromFile = new X509Certificate2(existingFilename))
                        {
                            if (fromFile.HasPrivateKey)
                            {
                                // We have a private key, the file has a private key, we're done here.
                                return;
                            }
                        }
                    }
                    catch (CryptographicException)
                    {
                        // We can't read this file anymore, but a moment ago it was this certificate,
                        // so go ahead and overwrite it.
                    }
                }

                string destinationFilename;
                FileMode mode = FileMode.CreateNew;

                if (existingFilename != null)
                {
                    destinationFilename = existingFilename;
                    mode = FileMode.Create;
                }
                else if (findOpenSlot)
                {
                    destinationFilename = FindOpenSlot(thumbprint);
                }
                else
                {
                    destinationFilename = Path.Combine(_storePath, thumbprint + PfxExtension);
                }

                using (FileStream stream = new FileStream(destinationFilename, mode))
                {
                    EnsureFilePermissions(stream, userId);
                    byte[] pkcs12 = copy.Export(X509ContentType.Pkcs12);
                    stream.Write(pkcs12, 0, pkcs12.Length);
                }
            }
        }
コード例 #41
0
        public static byte[] ExportPublicKeyCertificate(this X509Certificate x509Certificate)
        {
            var x509Certificate2 = new SystemX509Certificates.X509Certificate2(x509Certificate.GetEncoded());

            return(x509Certificate2.Export(SystemX509Certificates.X509ContentType.Cert));
        }
コード例 #42
0
ファイル: CertUtils.cs プロジェクト: johnkors/azure-sdk-tools
 public static byte[] GetCertificateData(string certPath, string password)
 {
     var cert = new X509Certificate2();
     cert.Import(certPath, password, X509KeyStorageFlags.Exportable);
     return cert.HasPrivateKey ? cert.Export(X509ContentType.Pfx, password) : cert.Export(X509ContentType.Pkcs12);
 }
コード例 #43
0
ファイル: CertUtils.cs プロジェクト: johnkors/azure-sdk-tools
 public static X509Certificate2 DropPrivateKey(X509Certificate2 cert)
 {
     // export and reimport without private key.
     var noPrivateKey = cert.Export(X509ContentType.Cert);
     return new X509Certificate2(noPrivateKey);
 }
コード例 #44
0
 /// <summary>
 /// Export a certificate to a PEM format string
 /// </summary>
 /// <param name="cert">The certificate to export</param>
 /// <returns>A PEM encoded string</returns>
 public static string ExportToPEM(this X509Certificate2 cert)
 {
     return(MakePem(cert.Export(X509ContentType.Cert), "CERTIFICATE", insertLineBreaks: true));
 }
        private static void GenerateSigningCertificate(ICertificatePolicy certificatePolicy, out string thumbprint, out string pemPublicCert, out byte[] pkcs12Data, out System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(random, 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            X509Name certName;

            if (certificatePolicy.X509NameDictionary == null || !certificatePolicy.X509NameDictionary.Any())
            {
                certName = new X509Name("CN=" + certificatePolicy.CommonName);
            }
            else
            {
                var list = new Dictionary <string, string>();
                AddSubjectNameItem(list, "CN", certificatePolicy.CommonName);
                foreach (var item in certificatePolicy.X509NameDictionary)
                {
                    AddSubjectNameItem(list, item.Key, item.Value);
                }
                certName = new X509Name(GetSubjectNameItemString(list));
            }

            BigInteger serialNo;

            serialNo = BigInteger.ProbablePrime(120, random);

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotBefore(DateTime.UtcNow.AddHours(-2)); // go back 2 hours just to be safe
            gen.SetNotAfter(DateTime.UtcNow.AddDays(certificatePolicy.ValidForDays));
            gen.SetSignatureAlgorithm("SHA256WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

            gen.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(false));

            gen.AddExtension(X509Extensions.KeyUsage.Id,
                             true,
                             new KeyUsage(KeyUsage.DigitalSignature));

            // handle our key purposes
            if (!certificatePolicy.AllPurposes)
            {
                var purposes = new List <KeyPurposeID>();
                if (certificatePolicy.ServerAuthentication)
                {
                    purposes.Add(KeyPurposeID.IdKPServerAuth);
                }
                if (certificatePolicy.ClientAuthentication)
                {
                    purposes.Add(KeyPurposeID.IdKPClientAuth);
                }
                if (certificatePolicy.CodeSigning)
                {
                    purposes.Add(KeyPurposeID.IdKPCodeSigning);
                }
                if (purposes.Any())
                {
                    gen.AddExtension(
                        X509Extensions.ExtendedKeyUsage.Id,
                        true,
                        new ExtendedKeyUsage(purposes.ToArray()));
                }
            }

            var certificate = gen.Generate(subjectKeyPair.Private, random);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            // this is exportable to get the bytes of the key to our file system in an encrypted manner
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();

            cspParameters.KeyContainerName = Guid.NewGuid().ToString();
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);

            rsaKey.PersistKeyInCsp = false; // do not persist
            rsaKey.ImportParameters(rsaParameters);

            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            x509.PrivateKey = rsaKey;

            // this is non-exportable
            CspParameters cspParametersNoExport = new CspParameters();

            cspParametersNoExport.KeyContainerName = Guid.NewGuid().ToString();
            cspParametersNoExport.Flags            = CspProviderFlags.UseNonExportableKey;
            RSACryptoServiceProvider rsaKey2 = new RSACryptoServiceProvider(2048, cspParametersNoExport);

            rsaKey2.PersistKeyInCsp = false; // do not persist
            rsaKey2.ImportParameters(rsaParameters);

            x509Certificate2            = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            x509Certificate2.PrivateKey = rsaKey2;

            //// Generating Random Numbers
            //var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            //var rnd = new Random();

            //password = new string(
            //    Enumerable.Repeat(chars, 15)
            //              .Select(s => s[rnd.Next(s.Length)])
            //              .ToArray());

            thumbprint = x509.Thumbprint.ToLower();

            var publicKeyPem       = new StringBuilder();
            var utf8WithoutBom     = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));

            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx);
        }
コード例 #46
0
        private void AddCertToStore(ICertificatePal certPal)
        {
            // This may well be the first time that we've added something to this store.
            Directory.CreateDirectory(_storePath);

            uint userId = Interop.Sys.GetEUid();

            EnsureDirectoryPermissions(_storePath, userId);

            OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal;

            using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles()))
            {
                string thumbprint = copy.Thumbprint;
                bool   findOpenSlot;

                // The odds are low that we'd have a thumbprint collision, but check anyways.
                string?existingFilename = FindExistingFilename(copy, _storePath, out findOpenSlot);

                if (existingFilename != null)
                {
                    if (!copy.HasPrivateKey)
                    {
                        return;
                    }

                    try
                    {
                        using (X509Certificate2 fromFile = new X509Certificate2(existingFilename))
                        {
                            if (fromFile.HasPrivateKey)
                            {
                                // We have a private key, the file has a private key, we're done here.
                                return;
                            }
                        }
                    }
                    catch (CryptographicException)
                    {
                        // We can't read this file anymore, but a moment ago it was this certificate,
                        // so go ahead and overwrite it.
                    }
                }

                string   destinationFilename;
                FileMode mode = FileMode.CreateNew;

                if (existingFilename != null)
                {
                    destinationFilename = existingFilename;
                    mode = FileMode.Create;
                }
                else if (findOpenSlot)
                {
                    destinationFilename = FindOpenSlot(thumbprint);
                }
                else
                {
                    destinationFilename = Path.Combine(_storePath, thumbprint + PfxExtension);
                }

                using (FileStream stream = new FileStream(destinationFilename, mode))
                {
                    EnsureFilePermissions(stream, userId);
                    byte[] pkcs12 = copy.Export(X509ContentType.Pkcs12) !;
                    stream.Write(pkcs12, 0, pkcs12.Length);
                }
            }
        }
コード例 #47
0
        public static void Save(this X509Certificates.X509Certificate2 certificate, string fileName)
        {
            var bytes = certificate.Export(X509Certificates.X509ContentType.Pfx, "");

            File.WriteAllBytes(fileName, bytes);
        }
コード例 #48
0
        public static CaPack Create(SX.X509Certificate2 certificate2)
        {
            var bytes = certificate2.Export(SX.X509ContentType.Pfx);

            return(CreateCaPack(new SX.X509Certificate2(bytes, string.Empty, SX.X509KeyStorageFlags.Exportable)));
        }
コード例 #49
-1
        // 既存の証明書を使って パスワードを確認してから、バイナリデータを取得します
        static byte[] GetCertificateData(string fileName, System.Security.SecureString seccurePassword)
        {
            try
            {
                // パスワードを確認します
                var x509Cert = new X509Certificate2(fileName, seccurePassword, X509KeyStorageFlags.Exportable);

                // 拡張を確認します
                //foreach (var e in x509Cert.Extensions)
                //{
                //    Console.WriteLine("name={0}    value={1}", e.Oid.FriendlyName, e.Oid.Value);
                //}
                var certData = x509Cert.Export(X509ContentType.Pfx, seccurePassword);
                return certData;
            }
            catch (Exception e)
            {
                throw e;
            }

            throw new Exception("証明書が開けません");
        }