/// <summary>
        /// Gets the CRL URLs from the CRL Distribution Points extension
        /// </summary>
        /// <param name="certificate"><seealso cref="Org.BouncyCastle.X509.X509Certificate"/></param>
        /// <returns>CRL URLs from the CRL Distribution Points extension</returns>
        public static List <Uri> GetCrlDistributionPoints(this Org.BouncyCastle.X509.X509Certificate certificate)
        {
            List <Uri> crlUrls = new List <Uri>();

            if (certificate == null)
            {
                return(crlUrls);
            }

            var cdpExtention = certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints);

            if (cdpExtention == null)
            {
                return(crlUrls);
            }

            byte[] crldpExt = cdpExtention.GetDerEncoded();

            if (crldpExt == null)
            {
                return(crlUrls);
            }

            Asn1InputStream oAsnInStream = new Asn1InputStream(crldpExt);
            var             derObjCrlDP  = oAsnInStream.ReadObject();
            DerOctetString  dosCrlDP     = (DerOctetString)derObjCrlDP;

            byte[]          crldpExtOctets = dosCrlDP.GetOctets();
            Asn1InputStream oAsnInStream2  = new Asn1InputStream(crldpExtOctets);
            var             derObj2        = oAsnInStream2.ReadObject();
            CrlDistPoint    distPoint      = CrlDistPoint.GetInstance(derObj2);

            foreach (DistributionPoint dp in distPoint.GetDistributionPoints())
            {
                DistributionPointName dpn = dp.DistributionPointName;
                // Look for URIs in fullName
                if (dpn != null)
                {
                    if (dpn.GetType() == typeof(Org.BouncyCastle.Asn1.X509.DistributionPointName))
                    {
                        GeneralName[] genNames = GeneralNames.GetInstance(dpn.Name).GetNames();
                        // Look for an URI
                        for (int j = 0; j < genNames.Length; j++)
                        {
                            if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
                            {
                                Uri    uri;
                                String url = DerIA5String.GetInstance(genNames[j].Name).GetString();
                                if (Uri.TryCreate(url, UriKind.Absolute, out uri))
                                {
                                    crlUrls.Add(uri);
                                }
                            }
                        }
                    }
                }
            }

            return(crlUrls);
        }
Example #2
0
		/**
		 * Validate the passed in certificate as being of the correct type to be used
		 * for time stamping. To be valid it must have an ExtendedKeyUsage extension
		 * which has a key purpose identifier of id-kp-timeStamping.
		 *
		 * @param cert the certificate of interest.
		 * @throws TspValidationException if the certicate fails on one of the check points.
		 */
		public static void ValidateCertificate(
			X509Certificate cert)
		{
			if (cert.Version != 3)
				throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension.");

			Asn1OctetString ext = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage);
			if (ext == null)
				throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension.");

			if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id))
				throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");

			try
			{
				ExtendedKeyUsage extKey = ExtendedKeyUsage.GetInstance(
					Asn1Object.FromByteArray(ext.GetOctets()));

				if (!extKey.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || extKey.Count != 1)
					throw new TspValidationException("ExtendedKeyUsage not solely time stamping.");
			}
			catch (IOException)
			{
				throw new TspValidationException("cannot process ExtendedKeyUsage extension");
			}
		}
Example #3
0
        public ValidationResponse ValidateCertificate(X509Certificate2 certificate)
        {
            Org.BouncyCastle.X509.X509Certificate certificateBC = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate);

            try
            {
                Asn1Object   crlDpAsn1            = Asn1Object.FromByteArray(certificateBC.GetExtensionValue(new DerObjectIdentifier("2.5.29.31")).GetOctets());
                CrlDistPoint crlDistributionPoint = CrlDistPoint.GetInstance(crlDpAsn1);
                foreach (DistributionPoint crlDp in crlDistributionPoint.GetDistributionPoints())
                {
                    GeneralNames gns = (GeneralNames)crlDp.DistributionPointName.Name;
                    foreach (GeneralName gn in gns.GetNames())
                    {
                        ValidationResponse validationResponse = ValidateCertificate(certificate, gn.Name.ToString());
                        if ((validationResponse.status == CertificateStatus.VALID) || (validationResponse.status == CertificateStatus.REVOKED))
                        {
                            return(validationResponse);
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
                // No Crl distribution points in the certificate
            }

            return(new ValidationResponse(CertificateStatus.UNKNOWN));
        }
Example #4
0
        public string getSKID(Org.BouncyCastle.X509.X509Certificate cert)
        {
            DerObjectIdentifier identifier = new DerObjectIdentifier("2.5.29.14");

            byte[] skid       = Hex.Encode(cert.GetExtensionValue(identifier).GetOctets());
            string skidstring = new ASCIIEncoding().GetString(skid);

            return(skidstring.Substring(4));
        }
Example #5
0
        public static byte[] GetSubjectKeyIdentifier(this Org.BouncyCastle.X509.X509Certificate cert)
        {
            Asn1OctetString ski = cert.GetExtensionValue(X509Extensions.SubjectKeyIdentifier);

            if (ski != null)
            {
                return(new SubjectKeyIdentifier(ski).GetKeyIdentifier());
            }
            else
            {
                return(new SubjectKeyIdentifierStructure(cert.GetPublicKey()).GetKeyIdentifier());
            }
        }
Example #6
0
        private static Asn1Object GetExtensionValue(X509Certificate cert, string oid)
        {
            if (cert == null)
            {
                return(null);
            }

            byte[] bytes = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();

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

            var aIn = new Asn1InputStream(bytes);

            return(aIn.ReadObject());
        }
Example #7
0
        private Asn1Object GetExtensionValue(Org.BouncyCastle.X509.X509Certificate rootX509Certificate, string oid)
        {
            if (rootX509Certificate == null)
            {
                return(null);
            }

            byte[] bytes = rootX509Certificate.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();

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

            Asn1InputStream aIn = new Asn1InputStream(bytes);

            return(aIn.ReadObject());
        }
Example #8
0
        public void CopyAndAddExtension(DerObjectIdentifier oid, bool critical, X509Certificate cert)
        {
            Asn1OctetString extensionValue = cert.GetExtensionValue(oid);

            if (extensionValue == null)
            {
                throw new CertificateParsingException(string.Concat((object)"extension ", (object)oid, (object)" not present"));
            }
            try
            {
                Asn1Encodable extensionValue2 = X509ExtensionUtilities.FromExtensionValue(extensionValue);
                AddExtension(oid, critical, extensionValue2);
            }
            catch (global::System.Exception ex)
            {
                throw new CertificateParsingException(ex.get_Message(), ex);
            }
        }
Example #9
0
        public void CopyAndAddExtension(DerObjectIdentifier oid, bool critical, X509Certificate cert)
        {
            Asn1OctetString extensionValue = cert.GetExtensionValue(oid);

            if (extensionValue == null)
            {
                throw new CertificateParsingException("extension " + oid + " not present");
            }
            try
            {
                Asn1Encodable extensionValue2 = X509ExtensionUtilities.FromExtensionValue(extensionValue);
                this.AddExtension(oid, critical, extensionValue2);
            }
            catch (Exception ex)
            {
                throw new CertificateParsingException(ex.Message, ex);
            }
        }
        protected static Asn1Object GetExtensionValue(X509Certificate cert,
            string oid)
        {
            if (cert == null)
            {
                return null;
            }

            byte[] bytes = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();

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

            Asn1InputStream aIn = new Asn1InputStream(bytes);

            return aIn.ReadObject();
        }
Example #11
0
        protected static Asn1Object GetExtensionValue(Org.BouncyCastle.X509.X509Certificate cert,
                                                      string oid)
        {
            if (cert == null)
            {
                return(null);
            }

            byte[] bytes = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();

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

            Asn1InputStream aIn = new Asn1InputStream(bytes);

            return(aIn.ReadObject());
        }
Example #12
0
        private List <string> GetCrlDistPoints(BcX509Certificate x509Certificate)
        {
            Asn1OctetString crldpAsn1OctetString = x509Certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints);

            if (crldpAsn1OctetString == null)
            {
                return(new List <string>());
            }

            Asn1InputStream crldpAsn1InputStream = new Asn1InputStream(crldpAsn1OctetString.GetOctets());
            Asn1Object      crldpAsn1Object      = crldpAsn1InputStream.ReadObject();

            return(CrlDistPoint.GetInstance(crldpAsn1Object).GetDistributionPoints()
                   .Select(_ => _.DistributionPointName)
                   .Where(_ => _.PointType == DistributionPointName.FullName)
                   .SelectMany(_ => GeneralNames.GetInstance(_.Name).GetNames())
                   .Where(_ => _.TagNo == GeneralName.UniformResourceIdentifier)
                   .Select(_ => _.Name.ToString())
                   .ToList());
        }
        private List <string> GetOcspEndPoints(BcX509Certificate x509Certificate)
        {
            Asn1OctetString aiaAsn1OctetString = x509Certificate.GetExtensionValue(X509Extensions.AuthorityInfoAccess);

            if (aiaAsn1OctetString == null)
            {
                return(new List <string>());
            }

            Asn1InputStream aiaAsn1InputStream = new Asn1InputStream(aiaAsn1OctetString.GetOctets());
            Asn1Object      aiaAsn1Object      = aiaAsn1InputStream.ReadObject();

            AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.GetInstance(aiaAsn1Object);

            authorityInformationAccess.GetAccessDescriptions();

            //want url not issuing cert
            return(authorityInformationAccess.GetAccessDescriptions()
                   .Where(_ => _.AccessMethod.Id == "1.3.6.1.5.5.7.48.1")
                   .Select(_ => _.AccessLocation.Name.ToString())
                   .ToList());
        }
        // Time Stamp Authority

        /**
         * Gets the URL of the TSA if it's available on the certificate
         * @param certificate   a certificate
         * @return  a TSA URL
         * @throws IOException
         */
        public static String GetTSAURL(X509Certificate certificate) {
            Asn1OctetString octetString = certificate.GetExtensionValue(SecurityIDs.ID_TSA);
            if (octetString == null)
                return null;
            byte[] der = octetString.GetOctets();
            if (der == null)
                return null;
            Asn1Object asn1obj;
            try {
                asn1obj = Asn1Object.FromByteArray(der);
                if (asn1obj is DerOctetString) {
                    DerOctetString octets = (DerOctetString) asn1obj;
                    asn1obj = Asn1Object.FromByteArray(octets.GetOctets());
                }
                Asn1Sequence asn1seq = Asn1Sequence.GetInstance(asn1obj);
                return GetStringFromGeneralName(asn1seq[1].ToAsn1Object());
            } catch (IOException) {
                return null;
            }
        }
		/**
		 * add a given extension field for the standard extensions tag (tag 3)
		 * copying the extension value from another certificate.
		 * @throws CertificateParsingException if the extension cannot be extracted.
		 */
		public void CopyAndAddExtension(
			DerObjectIdentifier	oid,
			bool				critical,
			X509Certificate		cert)
		{
			Asn1OctetString extValue = cert.GetExtensionValue(oid);

			if (extValue == null)
			{
				throw new CertificateParsingException("extension " + oid + " not present");
			}

			try
			{
				Asn1Encodable value = X509ExtensionUtilities.FromExtensionValue(extValue);

				this.AddExtension(oid, critical, value);
			}
			catch (Exception e)
			{
				throw new CertificateParsingException(e.Message, e);
			}
		}
Example #16
0
        public static CertificateInfo GetCertificateInfo(byte[] certificate, TCertificateFormat certificateFormat)
        {
            CertificateInfo result = null;
            X509CertificateStructure cert = null;
            switch (certificateFormat)
            {
                case TCertificateFormat.NotSet:
                    break;
                case TCertificateFormat.PEM:
                    Org.BouncyCastle.Utilities.IO.Pem.PemReader reader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(new StreamReader(new MemoryStream(certificate)));
                    Org.BouncyCastle.Utilities.IO.Pem.PemObject pem = reader.ReadPemObject();
                    while (pem != null)
                    {
                        if (pem.Type.EndsWith("CERTIFICATE"))
                        {
                            cert = X509CertificateStructure.GetInstance(pem.Content);
                        }
                        else if (pem.Type.EndsWith("PRIVATE KEY"))
                        {
                            if (result == null)
                                result = new CertificateInfo();

                            result.PrivateKey = GetPrivateKeyFromPEM(pem);
                        }
                        pem = reader.ReadPemObject();
                    }
                    break;
                case TCertificateFormat.PFX:
                    break;
                case TCertificateFormat.CER:
                    cert = X509CertificateStructure.GetInstance(certificate);
                    break;
                default:
                    break;
            }
            if (cert != null)
            {
                if (result == null)
                    result = new CertificateInfo();
                result.Subject = new CertificateSubject(cert);
                X509Certificate certX509 = new X509Certificate(cert);
                Asn1OctetString subjectKeyID = certX509.GetExtensionValue(X509Extensions.SubjectKeyIdentifier);
                if (subjectKeyID != null)
                {
                    byte[] encodeKeyID = subjectKeyID.GetOctets();
                    byte[] keyID = new byte[encodeKeyID[1]];
                    Buffer.BlockCopy(encodeKeyID, 2, keyID, 0, encodeKeyID[1]);
                    result.SubjectKeyID = keyID;
                }
            }
            return result;
        }              
Example #17
0
        /// <summary>
        /// Read CA private key file from .key or pfx file
        /// Read data from certificate request file .csr
        /// Generate signed certificate request file .cer
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GenerateCerFile(string certRequestFile,
                                           string privateKeyFile,
                                           string generateSignedCertificateFile,
                                           string password, string friendlyName,
                                           DateTime startDate, DateTime endDate)
        {
            #region LoadCertificate

            // read public & private key from file
            AsymmetricKeyParameter privateKey = null;
            AsymmetricKeyParameter publicKey  = null;

            System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate = null;
            Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = null;

            // Ovo NE radi
            //issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
            //        privateKeyFile,
            //        password
            //        );

            // Ovo RADI
            issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                privateKeyFile,
                password,
                System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                );

            // This doesn't work for selfsign certificate
            //bool isOK = issuerCertificate.Verify();

            bool     isHasPrivateKey = issuerCertificate.HasPrivateKey;
            DateTime noAfter         = issuerCertificate.NotAfter;
            DateTime noBefore        = issuerCertificate.NotBefore;
            X509ExtensionCollection x509extensions = issuerCertificate.Extensions;

            int errorNum = 0;
            X509CertificateParser parser = new X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData);
            BasicConstraints basicConstraints = null;
            bool             isCa             = false;
            Asn1OctetString  str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
            if (str != null)
            {
                basicConstraints = BasicConstraints.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(str));
                if (basicConstraints != null)
                {
                    isCa = basicConstraints.IsCA();
                }
            }

            if (!isCa)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            // This doesn't work for selfsign certificate
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            if (!isHasPrivateKey)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate DOES NOT have a private key." + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noBefore > startDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate start date: " + startDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noAfter < endDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate end date: " + endDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            if (errorNum > 0)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate has error!!!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                return;
            }
            bool isOk = issuerCertificate.Verify();

            AsymmetricCipherKeyPair issuerKeyPairTmp = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
            privateKey = issuerKeyPairTmp.Private;
            publicKey  = issuerKeyPairTmp.Public;

            issuerCertificateX509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData());
            issuerCertificateX509.Verify(publicKey);

            Org.BouncyCastle.X509.X509Certificate x509 = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate);
            x509.Verify(publicKey);
            x509.CheckValidity(startDate);

            #endregion

            // Read certificate request .csr file
            Pkcs10CertificationRequest cerRequest = null;
            try
            {
                String       input_data = File.ReadAllText(certRequestFile);
                StringReader sr         = new StringReader(input_data);
                PemReader    pr         = new PemReader(sr);
                cerRequest = (Pkcs10CertificationRequest)pr.ReadObject();

                tbOutputMessageBox.Text += "Verify file with certificate request : " + certRequestFile + "\n";
                bool requestIsOK = cerRequest.Verify();
                if (requestIsOK)
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " is OK." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " NOT valid." + "\n";
                    return;
                }
            }
            catch (Exception ex)
            {
                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR reading certificate request file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate(
                cerRequest,
                x509,
                issuerKeyPairTmp,
                startDate, endDate);

            try
            {
                File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());
                tbOutputMessageBox.Text += "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n";

                signedRequestFileNamePath = generateSignedCertificateFile;
                btnContinue.IsEnabled     = true;
            }
            catch (Exception)
            {
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }

            #region Public Key
            //try
            //{
            //    var store = new Pkcs12Store();
            //    string friendlyName1 = issuerCertificateX509.SubjectDN.ToString();
            //    var certificateEntry = new X509CertificateEntry(issuerCertificateX509);
            //    store.SetCertificateEntry(friendlyName1, certificateEntry);
            //    store.SetKeyEntry(friendlyName1, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            //    var stream = new MemoryStream();
            //    var random1 = GetSecureRandom();
            //    store.Save(stream, "password".ToCharArray(), random1);

            //    //Verify that the certificate is valid.
            //    var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //    //Write the file.
            //    File.WriteAllBytes(generateSignedCertificateFile, stream.ToArray());

            //    File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());

            //    //using (TextWriter tw = new StreamWriter(outputPublicKeyName))
            //    //{
            //    //    PemWriter pw = new PemWriter(tw);
            //    //    pw.WriteObject(subjectKeyPair.Public);
            //    //    tw.Flush();
            //    //}

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}

            //StringBuilder publicKeyStrBuilder = new StringBuilder();
            //PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder));
            //publicKeyPemWriter.WriteObject(genCert.GetPublicKey());
            //publicKeyPemWriter.Writer.Flush();

            //string publicKey = publicKeyStrBuilder.ToString();
            //try
            //{
            //    using (TextWriter tw = new StreamWriter(generateSignedCertificateFile))
            //    {
            //        PemWriter pw = new PemWriter(tw);
            //        pw.WriteObject(genCert.GetPublicKey());
            //        tw.Flush();
            //    }

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}
            #endregion Public Key
        }
Example #18
0
        /// <summary>
        /// Read CA private key file from .key or pfx file
        /// Read data from certificate request file .csr
        /// Generate signed certificate request file .cer
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GenerateCerFile(string certRequestFile,
                                           string privateKeyFile,
                                           string generateSignedCertificateFile,
                                           string password,
                                           DateTime requestStartDate, DateTime requestEndDate)
        {
            int errorNum = 0;

            issueCertificate.IsEnabled = false;
            progressring.Visibility    = Visibility.Visible;
            await System.Threading.Tasks.TaskEx.Delay(1000);

            tbOutputMessageBox.Text = "";

            #region LoadCertificate

            X509Certificate2 issuerCertificate = null;
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                issuerCertificate = new X509Certificate2(
                    privateKeyFile,
                    password,
                    X509KeyStorageFlags.Exportable
                    );
            }
            // Exceptions:
            //   T:System.Security.Cryptography.CryptographicException:
            //     An error with the certificate occurs. For example:The certificate file does not
            //     exist.The certificate is invalid.The certificate's password is incorrect.
            catch (System.Security.Cryptography.CryptographicException ex)
            {
                errorNum++;

                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Cryptographic ERROR=" + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));

                return;
            }
            catch (Exception ex)
            {
                errorNum++;

                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "General ERROR=" + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));

                return;
            }

            // This doesn't work for selfsign certificate
            //bool isOK = issuerCertificate.Verify();

            bool     isHasPrivateKey = issuerCertificate.HasPrivateKey;
            DateTime noAfter         = issuerCertificate.NotAfter;
            DateTime noBefore        = issuerCertificate.NotBefore;
            X509ExtensionCollection x509extensions = issuerCertificate.Extensions;

            await System.Threading.Tasks.TaskEx.Delay(1000);

            X509CertificateParser parser = new X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData);
            BasicConstraints basicConstraints = null;
            bool             isCa             = false;
            Asn1OctetString  str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19")); // Basic Constraints -> DerObjectIdentifier BasicConstraints = new DerObjectIdentifier("2.5.29.19");
            if (str != null)
            {
                basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(str));
                if (basicConstraints != null)
                {
                    isCa = basicConstraints.IsCA();
                }
            }

            if (!isCa)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            // This doesn't work for selfsign certificate
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            if (!isHasPrivateKey)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate DOES NOT have a private key." + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            if (noBefore > requestStartDate)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate start date: " + requestStartDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            if (noAfter < requestEndDate)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate end date: " + requestEndDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            if (errorNum > 0)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate has error!!!" + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));

                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                return;
            }

            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                bool isOk = issuerCertificate.Verify();
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error Issuer certificate file: " + issuerCertificate + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
                return;
            }


            Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = new X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData());
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                bool isOK = VerifyCertChain(issuerCertificate);
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error Issuer certificate file: " + issuerCertificate + " public key error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
                return;
            }


            Org.BouncyCastle.X509.X509Certificate x509IssuerCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate);
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                x509IssuerCert.CheckValidity(requestStartDate);
                await System.Threading.Tasks.TaskEx.Delay(1000);

                x509IssuerCert.CheckValidity(requestEndDate);
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error Issuer certificate file: " + issuerCertificate + " X509 certificate error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
                return;
            }

            #endregion

            // Read certificate request .csr file
            Pkcs10CertificationRequest cerRequest = null;
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                String       input_data = File.ReadAllText(certRequestFile);
                StringReader sr         = new StringReader(input_data);
                PemReader    pr         = new PemReader(sr);
                cerRequest = (Pkcs10CertificationRequest)pr.ReadObject();

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Verify file with certificate request : " + certRequestFile + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));

                try
                {
                    await System.Threading.Tasks.TaskEx.Delay(1000);

                    bool requestIsOK = cerRequest.Verify();
                    if (requestIsOK)
                    {
                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            tbOutputMessageBox.Inlines.Add(new Run
                            {
                                Text       = "File with certificate request : " + certRequestFile + " is OK." + "\n",
                                Foreground = System.Windows.Media.Brushes.Black
                            });
                        }));
                    }
                    else
                    {
                        progressring.Visibility    = Visibility.Hidden;
                        issueCertificate.IsEnabled = true;

                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            tbOutputMessageBox.Inlines.Add(new Run
                            {
                                Text       = "File with certificate request : " + certRequestFile + " NOT valid." + "\n",
                                Foreground = System.Windows.Media.Brushes.Red
                            });
                        }));
                        return;
                    }
                }
                catch (Exception ex)
                {
                    progressring.Visibility    = Visibility.Hidden;
                    issueCertificate.IsEnabled = true;

                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        tbOutputMessageBox.Inlines.Add(new Run
                        {
                            Text       = "Error certificate request file: " + cerRequest + " Verify error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                            Foreground = System.Windows.Media.Brushes.Red
                        });
                    }));
                    return;
                }
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR reading certificate request file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            await System.Threading.Tasks.TaskEx.Delay(1000);

            AsymmetricCipherKeyPair issuerKeyPair = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);

            await System.Threading.Tasks.TaskEx.Delay(1000);

            Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate(
                cerRequest,
                x509IssuerCert,
                issuerKeyPair,
                requestStartDate,
                requestEndDate);

            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));

                btnContinue.IsEnabled = true;
            }
            catch (Exception)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file sucessfully generated." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            CertData.cerPublicFilePath = tbPathGenerateCer.Text + "\\" + tbCertFileName.Text + ".cer";

            progressring.Visibility    = Visibility.Hidden;
            issueCertificate.IsEnabled = true;
        }
Example #19
0
 private static Asn1Object GetExtensionValue(X509Certificate cert, String oid) {
     byte[] bytes = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetDerEncoded();
     if (bytes == null) {
         return null;
     }
     Asn1InputStream aIn = new Asn1InputStream(new MemoryStream(bytes));
     Asn1OctetString octs = (Asn1OctetString) aIn.ReadObject();
     aIn = new Asn1InputStream(new MemoryStream(octs.GetOctets()));
     return aIn.ReadObject();
 }
Example #20
0
        protected static Asn1Object ObtenerValorDeExtension(X509Certificate in_Certificado,
                string oid)
        {
            if (in_Certificado == null)
            {
                return null;
            }

            byte[] bytes = in_Certificado.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();

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

            Asn1InputStream aIn = new Asn1InputStream(bytes);

            return aIn.ReadObject();
        }
        internal static byte[] GetExtensionValueByOid(X509Certificate certificate, String oid)
        {
            Asn1OctetString extensionValue = certificate.GetExtensionValue(oid);

            return(extensionValue != null?extensionValue.GetDerEncoded() : null);
        }
		private void Init()
		{
			try
			{
				trustedCert = certParser.ReadCertificate(Base64.Decode(Trust_Anchor_CP_01_01_crt));
				trustedCRL = crlParser.ReadCrl(Base64.Decode(Trust_Anchor_CRL_CP_01_01_crl));
				trustedSet = new HashSet();

				byte[] _ncBytes = null;
				Asn1OctetString _oct = trustedCert.GetExtensionValue(X509Extensions.NameConstraints);
				if (_oct != null)
				{
					_ncBytes = _oct.GetOctets();
				}

				trustedSet.Add(new TrustAnchor(trustedCert, _ncBytes));
				testCount = 0;
				testFail = new ArrayList();
				resultBuf = new StringBuilder("\n");
			}
			catch (Exception ex)
			{
				throw new Exception(ex.Message);
			}
		}