Export() public method

public Export ( System contentType ) : byte[]
contentType System
return byte[]
Beispiel #1
0
 public void UpdateCertificate(X509Certificate cert)
 {
     _updateCertificate.UpdateCertificate(cert);
     File.WriteAllBytes(CertPathOnDisk, cert.Export(X509ContentType.Pfx, CertPassword));
     _lastUpdate = DateTime.UtcNow;
     LogInfo("Certificate successfully updated");
 }
		public bool ValidateServerCertficate (object sender, X509Certificate receivedCertificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
		{
			if (originalServerCertificate == null) {
				return false;
			} else {

				if (receivedCertificate.Subject.IndexOf(".xamarin.com", 0, StringComparison.CurrentCultureIgnoreCase) == -1) { //not a call to an Xamarin server so verify certificate

					if (originalServerCertificate.Equals (receivedCertificate)) {
						return true;
					} else {
						//incorrect certificate found so notify user
						CertificateHelper.BytesOfServerCertificate = receivedCertificate.Export (X509ContentType.Cert);

						EventHandler handler = CertificateMismatchFound;
						if (handler != null) {
							handler (this, null);
						}
						return false;
					}
				} else {
					//Call to Xamarin (used for Xamarin.Insights) so accept
					return true;
				}
			}
		}
Beispiel #3
0
        private static bool ValidateCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors != SslPolicyErrors.None)
            {
                return false;
            }

            var cert2 = new X509Certificate2(certificate);
            var time = System.DateTime.Now;

            if (time > cert2.NotAfter || time < cert2.NotBefore)
            {
                // expiry
                return false;
            }

            var der_encoded = certificate.Export(X509ContentType.Cert);
            var hash = SHA256.Create().ComputeHash(der_encoded);
            var received_fingerprint = BitConverter.ToString(hash).Replace('-', ':');

            foreach (String fingerprint in Sha256Fingerprints)
            {
                if (fingerprint == received_fingerprint) { return true; }
            }

            return false;
        }
Beispiel #4
0
       public static string ExportToPEM(X509Certificate cert)
       {
           StringBuilder builder = new StringBuilder();

           builder.AppendLine("-----BEGIN CERTIFICATE-----");
           builder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
           builder.AppendLine("-----END CERTIFICATE-----");

           return builder.ToString();
       }
Beispiel #5
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(System.Security.Cryptography.X509Certificates.X509Certificate cert)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("-----BEGIN CERTIFICATE-----");
            builder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
            builder.AppendLine("-----END CERTIFICATE-----");

            return(builder.ToString());
        }
        public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            var providedCert = new X509Certificate2(certificate.Export(X509ContentType.Cert));
            var providedThumbprint = providedCert.Thumbprint;

            if (providedThumbprint == endPoint.RemoteThumbprint)
            {
                return true;
            }

            throw new UnexpectedCertificateException(providedCert, endPoint);
        }
Beispiel #7
0
        internal void ExtractValues(string appParam, byte[] originalChallenge)
        {
            DataContractJsonSerializer jsonSerializerResponse = new DataContractJsonSerializer(typeof(ClientData));
            object objResponse = jsonSerializerResponse.ReadObject(new MemoryStream(Helpers.Base64UrlDecode(clientData)));
            ClientData clientDataObject = objResponse as ClientData;

            if (clientDataObject == null
                || !clientDataObject.origin.Equals(appParam)
                || !clientDataObject.typ.Equals("navigator.id.finishEnrollment")
                || !clientDataObject.challenge.Equals(Helpers.Base64UrlEncode(originalChallenge))
                )
                throw new Exception("clientData does not contain necessary fields");

            byte[] data = Helpers.Base64UrlDecode(registrationData);
            if (data[0] != 0x05)
                throw new Exception("Invalid registration data");

            var keyLen = 65;
            byte[] keyBytes = new byte[keyLen];
            Array.Copy(data, 1, keyBytes, 0, keyLen);
            publicKey = Helpers.Base64UrlEncode(keyBytes);

            int keyHandleLen = data[66];
            byte[] keyHandleBytes = new byte[keyHandleLen];
            Array.Copy(data, 1 + 1 + keyLen, keyHandleBytes, 0, keyHandleLen);
            keyHandle = Helpers.Base64UrlEncode(keyHandleBytes);

            int certLen = data.Length - 1 - 1 - keyLen - keyHandleLen; // temporary!
            byte[] certBytes = new byte[certLen];
            Array.Copy(data, 1 + 1 + keyLen + keyHandleLen, certBytes, 0, certLen);
            X509Certificate certObject = new X509Certificate(certBytes);
            certBytes = certObject.Export(X509ContentType.Cert);
            certLen = certBytes.Length;

            int sigLen = data.Length - 1 - 1 - keyLen - keyHandleLen - certLen;
            byte[] signatureBytes = new byte[sigLen];
            Array.Copy(data, data.Length - sigLen, signatureBytes, 0, sigLen);

            var bytesToVerify = new byte[] { 0x00 }
                .Concat(SHA256.Create().ComputeHash(new UTF8Encoding().GetBytes(appParam)))
                .Concat(SHA256.Create().ComputeHash(Helpers.Base64UrlDecode(clientData)))
                .Concat(keyHandleBytes)
                .Concat(keyBytes)
                .ToArray();

            var ecdsa = new ECDsaCng(CngKey.Import(FixKeyBytes(certObject.GetPublicKey()), CngKeyBlobFormat.EccPublicBlob))
            {
                HashAlgorithm = CngAlgorithm.Sha256
            };
            if (!ecdsa.VerifyData(bytesToVerify, FixSignatureBytes(signatureBytes)))
                throw new Exception("Signature is not valid");
        }
        public static void SaveRemoteCertificate(Guid remoteGuid, X509Certificate certificate)
        {
            var remoteCertificateStore = new FileInfo(GetStorePath(remoteGuid));

            if (remoteCertificateStore.Exists)
            {
                remoteCertificateStore.Delete();
            }
            var content = certificate.Export(X509ContentType.Cert);

            using (var file = remoteCertificateStore.OpenWrite())
            {
                file.Write(content, 0, content.Length);
            }
        }
		public void Export_SerializedCert ()
		{
			X509Certificate cert = new X509Certificate (cert1);
			byte[] data = cert.Export (X509ContentType.SerializedCert);
			// usable
			X509Certificate2 c = new X509Certificate2 (data);
			Assert.AreEqual (cert1, c.GetRawCertData (), "Equals");
		}
		public void Export_Cert ()
		{
			X509Certificate cert = new X509Certificate (cert1);
			byte[] data = cert.Export (X509ContentType.Cert);
			Assert.AreEqual (data, cert1, "original");

			data = cert.Export (X509ContentType.Cert, (string)null);
			Assert.AreEqual (data, cert1, "original/string/null");

			data = cert.Export (X509ContentType.Cert, (SecureString) null);
			Assert.AreEqual (data, cert1, "original/SecureString/null");
		}
Beispiel #11
0
        /// <summary>
        /// Function will create and export certificate to PKCS12 format (PFX) with password (if any)
        /// </summary>
        /// <param name="keyContainerName">Name of the key container.</param>
        /// <param name="cspProvider">The CSP provider.</param>
        /// <param name="keySpec">The key specification</param>
        /// <param name="cspFlags">The CSP flags.</param>
        /// <param name="pfxPassword">The PFX password.</param>
        /// <returns>Certificate exported to PKCS#12 format and converted to bytes</returns>
        internal byte[] ExportCertToPKCS12(String keyContainerName, String cspProvider = MS_DEF_PROV, uint keySpec = AT_KEYEXCHANGE, uint cspFlags = 0, string pfxPassword = "")
        {
            byte[] pfxblob = null;
            IntPtr hCertCntxt = IntPtr.Zero;

            String DN = "CN=Opensslkey Unsigned Certificate";

            hCertCntxt = CreateUnsignedCertCntxt(keyContainerName, DN, cspProvider, keySpec, cspFlags);
            if (hCertCntxt == IntPtr.Zero)
            {
                throw new ApplicationException("Could not create certificate");
            }

            try
            {
                X509Certificate cert = new X509Certificate(hCertCntxt);	//create certificate object from cert context.
                //X509Certificate2UI.DisplayCertificate(new X509Certificate2(cert));	// display it, showing linked private key
                pfxblob = cert.Export(X509ContentType.Pkcs12, pfxPassword);
            }
            catch (Exception exc)
            {
                throw new ApplicationException("Could not create certificate. Message: " + exc.Message, exc);
            }

            if (hCertCntxt != IntPtr.Zero)
            {
                UnsafeNativeMethods.CertFreeCertificateContext(hCertCntxt);
            }

            return pfxblob;
        }
 /// <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(X509Certificate cert)
 {
     var builder = new StringBuilder();
     builder.AppendLine("-----BEGIN CERTIFICATE-----");
     var bytes = cert.Export(X509ContentType.Cert);
     builder.AppendLine(Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks));
     builder.AppendLine("-----END CERTIFICATE-----");
     var output = builder.ToString();
     // just a single newline
     output = output.Replace(Environment.NewLine, "\n");
     return output;
 }
Beispiel #13
0
        public async void StartMQTT(string clientid, string cafile, string clientcertfile, string clientprivate, string clientprivatepassword = "")
        {
            var ca = new X509Certificate(cafile, "");

            var reader     = new PemReader(File.OpenText(clientprivate));
            var privatekey = (AsymmetricCipherKeyPair)reader.ReadObject();
            var pkinfo     = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privatekey.Private;

            var ce1 = new X509Certificate2(File.ReadAllBytes(clientcertfile), clientprivatepassword,
                                           X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            CspParameters parms = new CspParameters();

            parms.Flags            = CspProviderFlags.NoFlags;
            parms.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant();
            parms.ProviderType     = ((Environment.OSVersion.Version.Major > 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) ? 0x18 : 1;

            System.Security.Cryptography.RSACryptoServiceProvider rcsp =
                new System.Security.Cryptography.RSACryptoServiceProvider(parms)
            {
                PersistKeyInCsp = true
            };

            rcsp.ImportParameters(DotNetUtilities.ToRSAParameters(pkinfo));
            ce1.PrivateKey = rcsp;

            //var clientcert = CertificatesToDBandBack.Certificate.GetCertificateFromPEMstring(File.ReadAllText(clientcertfile), File.ReadAllText(clientprivate), clientprivatepassword);

            MQTTClient = new MqttFactory().CreateMqttClient();
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(mqtt_host, mqtt_port).WithClientId(clientid).WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                AllowUntrustedCertificates        = false,
                IgnoreCertificateChainErrors      = false,
                IgnoreCertificateRevocationErrors = false,
                UseTls       = true,
                SslProtocol  = System.Security.Authentication.SslProtocols.Tls12,
                Certificates = new List <byte[]>
                {
                    ca.Export(X509ContentType.SerializedCert),
                    ce1.Export(X509ContentType.SerializedCert)
                },
                CertificateValidationCallback = (X509Certificate x, X509Chain y, SslPolicyErrors z, IMqttClientOptions o) =>
                {
                    return(true);
                }
            }).Build();

            MQTTClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            });
            MQTTClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### CONNECTED WITH SERVER ###");
                await MQTTClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
            });
            MQTTClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
            });

            var connect = await MQTTClient.ConnectAsync(options);

            var sub = MQTTClient.SubscribeAsync(new TopicFilter
            {
                Topic = "test", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
            });
        }
Beispiel #14
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>
        private string exportToPEM(X509Certificate cert)
        {
            string certToBase64String = Convert.ToBase64String(cert.Export(X509ContentType.Cert));
            //certToBase64String = certToBase64String.Replace("/", @"\/");
            //certToBase64String = certToBase64String.Substring(0, certToBase64String.Length - 1);

            StringBuilder builder = new StringBuilder();

            //builder.Append("-----BEGIN CERTIFICATE-----");
            builder.Append(certToBase64String); //Convert.ToBase64String(cert.Export(X509ContentType.Cert))); //, Base64FormattingOptions.InsertLineBreaks));
            //builder.Append("-----END CERTIFICATE-----");

            return builder.ToString();
        }
Beispiel #15
0
        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            bool certOk = true;

            // Validate only the first time or if the certificate changes
            if (this.sslServerCert == null || !sslServerCert.Equals(certificate))
            {
                if (userValidateServerCertificate != null)
                    certOk = userValidateServerCertificate(this, certificate, chain, sslPolicyErrors);
                else if (sslPolicyErrors != SslPolicyErrors.None)
                    certOk = false;

                if(certOk)
                    this.sslServerCert = new X509Certificate(certificate.Export(X509ContentType.Cert));
            }

            return certOk;
        }
        //------   Since we are using an RSA with nonpersisted keycontainer, must pass it in to ensure it isn't colledted  -----
        private static byte[] GetPkcs12(RSA rsa, String keycontainer, String cspprovider, uint KEYSPEC, uint cspflags)
        {
            byte[] pfxblob	= null;
              IntPtr hCertCntxt	= IntPtr.Zero;

              String DN = "CN=Opensslkey Unsigned Certificate";

            hCertCntxt =  CreateUnsignedCertCntxt(keycontainer, cspprovider, KEYSPEC, cspflags, DN) ;
            if(hCertCntxt == IntPtr.Zero){
            Console.WriteLine("Couldn't create an unsigned-cert\n") ;
            return null;
            }
             try{
            X509Certificate cert = new X509Certificate(hCertCntxt) ;	//create certificate object from cert context.
            X509Certificate2UI.DisplayCertificate(new X509Certificate2(cert)) ;	// display it, showing linked private key
            SecureString pswd = GetSecPswd("Set PFX Password ==>") ;
            pfxblob = cert.Export(X509ContentType.Pkcs12, pswd);
              }

             catch(Exception exc)
             {
            Console.WriteLine( "BAD RESULT" + exc.Message);
            pfxblob = null;
             }

            rsa.Clear() ;
            if(hCertCntxt != IntPtr.Zero)
            Win32.CertFreeCertificateContext(hCertCntxt) ;
              return pfxblob;
        }
 public string CertificateBase64Value(X509Certificate certificate)
 {
     byte[] export = certificate.Export(X509ContentType.Cert);
     return Convert.ToBase64String(export);
 }
Beispiel #18
0
        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            bool certOk = true;

            // Validate only the first time
            if (this.sslServerCert == null)
            {
                if (userValidateServerCertificate != null)
                    certOk = userValidateServerCertificate(this, certificate, chain, sslPolicyErrors);
                else if (sslPolicyErrors != SslPolicyErrors.None)
                    certOk = false;
               
                if(certOk)
                    this.sslServerCert = new X509Certificate(certificate.Export(X509ContentType.Cert));
            }
            else if (!sslServerCert.Equals(certificate))
                throw new FTPSslException("X509 certificate changes between validation requests. This is not allowed");

            return certOk;
        }
Beispiel #19
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(X509Certificate cert)
        {
            StringWriter swriter = new StringWriter();
            PemWriter writer = new PemWriter(swriter);

            writer.WriteObject(new X509.X509CertificateParser().ReadCertificate(cert.Export(X509ContentType.Cert)));

            return swriter.ToString();
        }