Example #1
0
        private Validade VerificarValidade(byte[] RawData)
        {
            bool valido = false;

            try
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 certificado =
                    new System.Security.Cryptography.X509Certificates.X509Certificate2(RawData);

                X509Chain ch = new X509Chain();
                ch.Build(certificado);

                DateTime inicioValidade  = DateTime.Parse(certificado.GetEffectiveDateString());
                DateTime terminoValidade = DateTime.Parse(certificado.GetExpirationDateString());

                valido = inicioValidade <= DateTime.Now && terminoValidade >= DateTime.Now;

                if (!valido)
                {
                    return(Validade.Expirado);
                }
                else
                {
                    return(Validade.Valido);
                }
            }

            catch (Exception)
            {
                return(Validade.Null);
            }
        }
Example #2
0
        static void Main(string[] args)
        {
            // Assembly assembly = Assembly.LoadFrom(@"C:\IXCad.dll");
            //  Version ver = assembly.GetName().Version;
            var program = new Program();

            program.CreateExcelFile();



            String filepath1 = @"D:\Learning\TestDLL\pdfshell.dll";
            String filepath2 = @"‪D:\Learning\TestDLL\AcroPDF.dll";

            String[] strarray = new String[] { filepath1, filepath2 };

            foreach (var item in strarray)
            {

                //FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(item);

                //// Print the file name and version number.
                //Console.WriteLine("Copyright: " + myFileVersionInfo.LegalCopyright + '\n' +
                //                  "Version number: " + myFileVersionInfo.FileVersion + "Language:" + myFileVersionInfo.Language +
                //                  myFileVersionInfo.ProductName + myFileVersionInfo.ProductVersion);


                //Console.WriteLine("@@@@@@@@@@");
                //Console.WriteLine("The certificate details are-------");
                X509Certificate2 theCertificate;
                try
                {
                    X509Certificate thesigner = X509Certificate.CreateFromSignedFile(item);
                    theCertificate = new X509Certificate2(thesigner);
                    Console.WriteLine("Publisher Information : " + theCertificate.SubjectName.Name);
                    Console.WriteLine("Valid From: " + theCertificate.GetEffectiveDateString());
                    Console.WriteLine("Valid To: " + theCertificate.GetExpirationDateString());
                    Console.WriteLine("Issued By: " + theCertificate.Issuer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("No signatures found:::" + ex.Message);
                    return;

                }
                Console.ReadLine();
            }
                

            
            
            Console.ReadLine();


        }
Example #3
0
        public static Dictionary <string, string> ParseCert(byte[] certDER)
        {
            var ret = new Dictionary <string, string>();

            try {
                var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certDER);
                //logger.Debug("X.509v3証明書の発行先であるプリンシパルの名前(古い形式)");
                //logger.Debug(x509.GetName());

                ret.Add("X.509v3証明書の形式の名前", x509.GetFormat());
                ret.Add("バージョン", $"{x509.Version}");
                ret.Add("シリアル番号", x509.GetSerialNumberString());
                ret.Add("署名アルゴリズム", x509.SignatureAlgorithm.FriendlyName);
                ret.Add("証明書を発行した証明機関の名前", x509.Issuer);
                ret.Add("サブジェクトの識別名", x509.Subject);
                ret.Add("証明書のハッシュ値の16進文字列", x509.GetCertHashString());
                ret.Add("証明書の発効日", x509.GetEffectiveDateString());
                ret.Add("証明書の失効日", x509.GetExpirationDateString());
                ret.Add("キーアルゴリズム情報", x509.GetKeyAlgorithm());
                ret.Add("キーアルゴリズムパラメータ", x509.GetKeyAlgorithmParametersString());
                ret.Add("公開鍵", x509.GetPublicKeyString());

                foreach (var extension in x509.Extensions)
                {
                    /*
                     * if (extension.Oid.FriendlyName == "キー使用法") {
                     *  var ext = (X509KeyUsageExtension)extension;
                     *  ret.Add("Extension キー使用法", ext.KeyUsages.ToString());
                     * }
                     * if (extension.Oid.FriendlyName == "拡張キー使用法") {
                     *  var ext = (X509EnhancedKeyUsageExtension)extension;
                     *  string value = "";
                     *  var oids = ext.EnhancedKeyUsages;
                     *  foreach (var oid in oids) {
                     *      value = value + oid.FriendlyName + "(" + oid.Value + ")";
                     *  }
                     *  ret.Add("Extension 拡張キー使用法", value);
                     * }
                     */

                    ret.Add($"- Extension {extension.Oid.FriendlyName}", extension.Oid.Value);
                }

                //logger.Debug("X.509v3証明書を発行した証明機関の名前(古い形式)");
                //logger.Debug(x509.GetIssuerName());

                //logger.Debug("X.509証明書全体の生データ");
                //logger.Debug(x509.GetRawCertDataString());
            } catch (Exception ex) {
                logger.Debug(ex);
            }
            return(ret);
        }
Example #4
0
 public eVRCardReader(X509Certificate2 CSCA, CardRemovedEvent removedEvent, CardInsertedEvent insertedEvent)
 {
     TS.TraceI("Constructing MTVCardReader object.");
     TS.TraceI("eVRCApplicatie = {0}", Helper.ByteArrayToString(eVRCApplicatie));
     if (CSCA != null)
     {
         this.CSCA = CSCA;
         TS.TraceV("CSCA Subject : \"{0}\".", CSCA.Subject);
         TS.TraceV("CSCA Effective date : \"{0}\".", CSCA.GetEffectiveDateString());
         TS.TraceV("CSCA Expiration date : \"{0}\".", CSCA.GetExpirationDateString());
     }
     this.cardReader = new CardReader(removedEvent, insertedEvent);
     TS.TraceI("MTVCardReader constructed.");
 }
        private Nenshkrim MerrNenshkrimInfo(AcroFields af, string name)
        {
            PdfPKCS7 pkcs7 = af.VerifySignature(name);

            var certificate = new X509Certificate2();

            var cert = (Org.BouncyCastle.X509.X509Certificate)pkcs7.Certificates[0];

            certificate.Import(cert.GetEncoded());
            Nenshkrim nenshkruesi = new Nenshkrim();

            nenshkruesi.Nenshkruesi = CertificateInfo.GetSubjectFields(cert).GetField("CN");

            string issuer = certificate.Issuer;
            nenshkruesi.IssuerCN = GetIssuer(issuer, "CN=");
            nenshkruesi.IssuerOU = GetIssuer(issuer, "OU=");
            nenshkruesi.IssuerO = GetIssuer(issuer, "O=");
            nenshkruesi.IssuerC = GetIssuer(issuer, "C=");

            if (nenshkruesi.IssuerC == "KS")
            {
                //largimi i [EMAIL] prej cn
                nenshkruesi.Nenshkruesi = nenshkruesi.Nenshkruesi.Substring(8);
            }

            nenshkruesi.Emri = CertificateInfo.GetSubjectFields(cert).GetField("GIVENNAME");
            nenshkruesi.Mbiemri = CertificateInfo.GetSubjectFields(cert).GetField("SURNAME");
            //algoritmi hash
            nenshkruesi.AlgoritmiHash = pkcs7.GetHashAlgorithm();
            //algoritmi hash
            nenshkruesi.AlgoritmiEnkriptimit = pkcs7.GetEncryptionAlgorithm();
            //data e nenshrimit
            nenshkruesi.DataNenshkrimit = pkcs7.SignDate;
            //certifikata valide prej, deri
            nenshkruesi.CertifikataValidePrej = certificate.GetEffectiveDateString();
            nenshkruesi.CertifikataValideDeri = certificate.GetExpirationDateString();
            nenshkruesi.SerialNumber = certificate.SerialNumber;

            //verifikimi
            if (pkcs7.Verify())
            {
                nenshkruesi.Valid = true;
            }
            else
            {
                nenshkruesi.Valid = false;
            }

            return nenshkruesi;
        }
Example #6
0
        public MFTestResults CertTest_Test()
        {
            bool bRes = true;

            try
            {
                //string filename = "microsoft.cer";
                using (Session session = new Session("", MechanismType.RSA_PKCS))
                {
                    X509Certificate2 cert = new X509Certificate2(session, Properties.Resources.GetBytes(Properties.Resources.BinaryResources.microsoft));
                    Log.Comment(cert.Subject);

                    Log.Comment(cert.Issuer);

                    byte[] serialNumber = new byte[cert.GetSerialNumber().Length];
                    Array.Copy(cert.GetSerialNumber(), 0,
                                         serialNumber, 0,
                                         cert.GetSerialNumber().Length);
                    PrintByteArray(serialNumber);

                    Log.Comment(cert.GetKeyAlgorithm());


                    byte[] publicKey = new byte[cert.GetPublicKey().Length];
                    Array.Copy(cert.GetPublicKey(), 0,
                                         publicKey, 0,
                                         cert.GetPublicKey().Length);
                    PrintByteArray(publicKey);

                    Log.Comment(cert.GetEffectiveDateString());
                    Log.Comment(cert.GetExpirationDateString());
                }
            }
            catch
            {
                bRes = false;
            }

            return bRes ? MFTestResults.Pass : MFTestResults.Fail;
        }
Example #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            string fileName = textBox1.Text;
            string fileExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (textBox1.TextLength < 1)
            {
                MessageBox.Show("Укажите путь к файлу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else {
                if (CheckFile(textBox1.Text))
                {
                    MessageBox.Show("Модуль PE32 имеет подпись", "CheckPE32", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    X509Certificate theSigner = X509Certificate.CreateFromSignedFile(textBox1.Text);
                    X509Certificate2 theCertificate = new X509Certificate2(theSigner);
                    System.IO.StreamWriter textFile = new System.IO.StreamWriter("SertificateInfo.txt");
                    textFile.WriteLine("Проверяемый файл: " + textBox1.Text);
                    textFile.WriteLine("Серийный номер сертификата: " + theCertificate.SerialNumber);
                    textFile.WriteLine("Информация о владельце: " + theCertificate.SubjectName.Name);
                    textFile.WriteLine("Действителен с: " + theCertificate.GetEffectiveDateString());
                    textFile.WriteLine("Истекает: " + theCertificate.GetExpirationDateString());
                    textFile.WriteLine("Центр сертификации, выдавший сертификат: " + theCertificate.Issuer);
                    textFile.Close();
                    System.Diagnostics.Process.Start("notepad.exe", "SertificateInfo.txt");
                }
                else
                {
                    MessageBox.Show("Модуль PE32 не подписан!", "CheckPE32", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
            }
        }
Example #8
0
        private int ValidateCert(uint dwType, IntPtr pvArg, uint dwChainLen, IntPtr pCertChain, uint dwFlags)
        {
            //According to http://msdn.microsoft.com/en-us/library/ms940451.aspx:
            //
            //- dwChainLen is always 1
            //- Windows CE performs the cert chain validation
            //- pvArg is the context data we passed into the SO_SSL_SET_VALIDATE_CERT_HOOK call so in our
            //- case is the host name
            //
            //So here we are responsible for validating the dates on the certificate and the CN

            if (dwType != SSL_CERT_X59)
                return SSL_ERR_BAD_TYPE;

            //When in debug mode let self-signed certificates through ...
            #if !DEBUG
            if ((dwFlags & SSL_CERT_FLAG_ISSUER_UNKNOWN) != 0)
                return SSL_ERR_CERT_UNKNOWN;
            #endif

            Debug.Assert(dwChainLen == 1);

            //Note about the note: an unmanaged long is 32 bits, unlike a managed long which is 64. I was missing
            //this fact when I wrote the comment. So the docs are accurate.
            //NOTE: The documentation says pCertChain is a pointer to a LPBLOB struct:
            //
            // {ulong size, byte* data}
            //
            //in reality the size is a 32 bit integer (not 64).
            int certSize = Marshal.ReadInt32(pCertChain);
            IntPtr pData = Marshal.ReadIntPtr(new IntPtr(pCertChain.ToInt32() + sizeof(int)));

            byte[] certData = new byte[certSize];

            for (int i = 0; i < certSize; i++)
                certData[i] = Marshal.ReadByte(pData, (int)i);

            X509Certificate2 cert;
            try
            {
                cert = new X509Certificate2(certData);
            }
            catch (ArgumentException) { return SSL_ERR_BAD_DATA; }
            catch (CryptographicException) { return SSL_ERR_BAD_DATA; }

            //Validate the expiration date
            if (DateTime.Now > DateTime.Parse(cert.GetExpirationDateString(), CultureInfo.CurrentCulture))
                return SSL_ERR_CERT_EXPIRED;

            //Validate the effective date
            if (DateTime.Now < DateTime.Parse(cert.GetEffectiveDateString(), CultureInfo.CurrentCulture))
                return SSL_ERR_FAILED;

            string certName = cert.GetName();
            Debug.WriteLine(certName);

            //Validate the CN
            string host = ReadAnsiString(pvArg);
            if (!certName.Contains("CN=" + host))
                return SSL_ERR_FAILED;

            return SSL_ERR_OKAY;
        }
Example #9
0
        /// <summary>
        /// Validate certificate method as callback to the socket
        /// </summary>
        /// <param name="dwType">Data type pointed to by pCertChain (SSL_CERT_X.509 if X509 certs chain)</param>
        /// <param name="pvArg">Pointer to application-defined context (passed by the SSLVALIDATECERTHOOK structure)</param>
        /// <param name="dwChainLen">Number of certificates pointed to by pCertChain (It will always be equal to one)</param>
        /// <param name="pCertChain">Pointer to the root certificate</param>
        /// <param name="dwFlags">Will contain SSL_CERT_FLAG_ISSUER_UNKNOWN if the root issuer of the certificate could not be found in the CA database</param>
        /// <param name="certificate">X509 certificate</param>
        /// <returns>Result</returns>
        private int ValidateCertificateInternal(uint dwType, IntPtr pvArg, uint dwChainLen, IntPtr pCertChain, uint dwFlags, out X509Certificate2 certificate)
        {
            certificate = null;

            // check if it is a valid X509 certificate
            if (dwType != SSL_CERT_X509)
                return SSL_ERR_BAD_TYPE;

            // in debug mode accept self-signed certificates
            #if !DEBUG
            // check if issuer is unknown
            if ((dwFlags & SSL_CERT_FLAG_ISSUER_UNKNOWN) != 0)
                return SSL_ERR_CERT_UNKNOWN;
            #endif

            // sslsock.h : pCertChain is a pointer to BLOB structure
            //             - first 4 bytes are the certificate size
            //             - following bytes are the certificate itself
            // read certificate size
            int certSize = Marshal.ReadInt32(pCertChain);
            // pointer to start of certificate data
            IntPtr pCertData = Marshal.ReadIntPtr(new IntPtr(pCertChain.ToInt32() + sizeof(int)));

            byte[] certData = new byte[certSize];
            // read certificate data bytes
            for (int i = 0; i < certSize; i++)
                certData[i] = Marshal.ReadByte(pCertData, (int)i);

            // create X509 certificate from raw bytes
            try
            {
                certificate = new X509Certificate2(certData);
            }
            catch (ArgumentException) { return SSL_ERR_BAD_DATA; }
            catch (CryptographicException) { return SSL_ERR_BAD_DATA; }

            // check expiration date
            if (DateTime.Now > DateTime.Parse(certificate.GetExpirationDateString(), CultureInfo.CurrentCulture))
                return SSL_ERR_CERT_EXPIRED;

            // check the effective date
            if (DateTime.Now < DateTime.Parse(certificate.GetEffectiveDateString(), CultureInfo.CurrentCulture))
                return SSL_ERR_FAILED;

            // validate the certificate CN with provided host name
            string host = Marshal.PtrToStringBSTR(pvArg);
            if (!certificate.GetName().Contains("CN=" + host))
                return SSL_ERR_FAILED;

            return SSL_ERR_OKAY;
        }
Example #10
0
        /// <summary>
        /// Prepares this signer to sign an application
        ///   Modifies the following files:
        ///	 embedded.mobileprovision
        /// </summary>
        public void PrepareForSigning()
        {
            // Load Info.plist, which guides nearly everything else
            Info = LoadInfoPList();

            // Get the name of the bundle
            string CFBundleIdentifier;
            if (!Info.GetString("CFBundleIdentifier", out CFBundleIdentifier))
            {
                throw new InvalidDataException("Info.plist must contain the key CFBundleIdentifier");
            }

            // Load the mobile provision, which provides entitlements and a partial cert which can be used to find an installed certificate
            LoadMobileProvision(CFBundleIdentifier);
            if (Provision == null)
            {
                return;
            }

            // Install the Apple trust chain certs (required to do a CMS signature with full chain embedded)
            List<string> TrustChainCertFilenames = new List<string>();

            string CertPath = Path.GetFullPath(Config.EngineBuildDirectory);
            TrustChainCertFilenames.Add(Path.Combine(CertPath, "AppleWorldwideDeveloperRelationsCA.pem"));
            TrustChainCertFilenames.Add(Path.Combine(CertPath, "AppleRootCA.pem"));

            InstallCertificates(TrustChainCertFilenames);

            // Find and load the signing cert
            SigningCert = LoadSigningCertificate();
            if (SigningCert == null)
            {
                // Failed to find a cert already installed or to install, cannot proceed any futher
                Program.Error("... Failed to find a certificate that matches the mobile provision to be used for code signing");
                Program.ReturnCode = (int)ErrorCodes.Error_CertificateNotFound;
                throw new InvalidDataException("Certificate not found!");
            }
            else
            {
                Program.Log("... Found matching certificate '{0}' (valid from {1} to {2})", SigningCert.FriendlyName, SigningCert.GetEffectiveDateString(), SigningCert.GetExpirationDateString());
            }
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            contextMenuStrip1.Enabled = false;
            StreamWriter file = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\inc\\certificate.cer");
            X509Certificate2 theCertificate;

            try
            {
                // Write the string to a file.

                file.WriteLine(richTextBox1.Text);
                file.Close();
            }
            catch (Exception ex)
            {
                richTextBox2.Text = ex.Message;
            }

            try
            {
                X509Certificate theSigner = X509Certificate.CreateFromCertFile(AppDomain.CurrentDomain.BaseDirectory + "\\inc\\certificate.cer");
                //X509Certificate theSigner = X509Certificate.CreateFromSignedFile("https://niyazialpay.com");
                theCertificate = new X509Certificate2(theSigner);
            }
            catch
            {
                richTextBox2.Text = "No digital signature found";
                return;
            }

            bool chainIsValid = false;

            /*
            *
            * This section will check that the certificate is from a trusted authority IE
            * not self-signed.
            *
            */

            var theCertificateChain = new X509Chain();

            theCertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;

            /*
            *
            * Using .Online here means that the validation WILL CALL OUT TO THE INTERNET
            * to check the revocation status of the certificate. Change to .Offline if you
            * don't want that to happen.
            */

            theCertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;

            theCertificateChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);

            theCertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

            chainIsValid = theCertificateChain.Build(theCertificate);

            try
            {
                if (chainIsValid)
                {
                    Font boldfont = new Font("Arial", 10, FontStyle.Bold);
                    Font boldfont2 = new Font("Arial", 11, FontStyle.Bold);
                    Font normalfont = new Font("Arial", 10, FontStyle.Regular);

                    richTextBox2.Clear();

                    string[] certArray = Functions.explode(",", theCertificate.SubjectName.Name);

                    richTextBox2.SelectionFont = boldfont2;
                    richTextBox2.AppendText("Publisher Information : \n\n");

                    int certCount = certArray.Count();

                    for (int i = 0; i < certCount; i++)
                    {
                        string[] certeElements = Functions.explode("=", certArray[i]);
                        richTextBox2.SelectionFont = boldfont;
                        richTextBox2.AppendText(certeElements[0].Trim() + ": ");
                        richTextBox2.SelectionFont = normalfont;
                        richTextBox2.AppendText(certeElements[1].Trim() + "\n");
                    }

                    richTextBox2.SelectionFont = boldfont;
                    richTextBox2.AppendText("\nValid From: ");
                    richTextBox2.SelectionFont = normalfont;
                    richTextBox2.AppendText(theCertificate.GetEffectiveDateString());

                    richTextBox2.SelectionFont = boldfont;
                    richTextBox2.AppendText("\nValid To: ");
                    richTextBox2.SelectionFont = normalfont;
                    richTextBox2.AppendText(theCertificate.GetExpirationDateString());

                    string[] iusserArray = Functions.explode(",", theCertificate.Issuer);

                    int iusserCount = iusserArray.Count();

                    richTextBox2.SelectionFont = boldfont2;
                    richTextBox2.AppendText("\n\nIssued By: \n\n");

                    for (int i=0; i<iusserCount; i++)
                    {
                        richTextBox2.SelectionFont = boldfont;

                        string[] iusserElements = Functions.explode("=", iusserArray[i]);

                        richTextBox2.AppendText(iusserElements[0].Trim() + ": ");
                        richTextBox2.SelectionFont = normalfont;
                        richTextBox2.AppendText(iusserElements[1].Trim() + "\n");
                    }
                }
                else
                {
                    richTextBox2.Clear();
                    richTextBox2.Text = "Chain Not Valid (certificate is self-signed)";
                }
            }
            catch(Exception ex)
            {
                richTextBox2.Text = ex.Message;
            }
            finally
            {
                richTextBox1.Focus();
                contextMenuStrip1.Enabled = true;
            }
        }
        private static SSLCertificate GetSSLCertificateFromX509Certificate2(X509Certificate2 cert)
        {
            var certificate = new SSLCertificate
            {
                Hostname = cert.GetNameInfo(X509NameType.SimpleName, false),
                FriendlyName = cert.FriendlyName,
                CSRLength = Convert.ToInt32(cert.PublicKey.Key.KeySize.ToString(CultureInfo.InvariantCulture)),
                Installed = true,
                DistinguishedName = cert.Subject,
                Hash = cert.GetCertHash(),
                SerialNumber = cert.SerialNumber,
                ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()),
                ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()),
                Success = true
            };

            return certificate;
        }
        public override void AssignSession(Session oS)
        {
            base.AssignSession(oS);
            var dataItems = new List<DataItem>();
            dataItems.Add(new DataItem("Is Https", oS.isHTTPS));

            if (oS.isHTTPS && oS.oFlags.ContainsKey(CertificateStorage.CeritificateRequestPropertyName))
            {
                try
                {
                    var thumbprint = oS.oFlags[CertificateStorage.CeritificateRequestPropertyName];
                    FiddlerApplication.Log.LogString(thumbprint);

                    if (CertificateStorage.Certificates.ContainsKey(thumbprint))
                    {
                        var certificate = CertificateStorage.Certificates[thumbprint];
                        var cert = new X509Certificate2(certificate);

                        _informationTab.Certificate = cert;
                        //most commonly desired information up top.
                        dataItems.InsertRange(0, new[] { new DataItem("FriendlyName", cert.FriendlyName),
                                                         new DataItem("Subject", cert.Subject),
                                                         new DataItem("Issuer", cert.Issuer),
                                                         new DataItem("Effective Date", cert.GetEffectiveDateString()),
                                                         new DataItem("Expiration Date", cert.GetExpirationDateString()),
                                                         new DataItem("Thumbprint", cert.Thumbprint),
                                                         new DataItem("------------------------", "------------------------")});

                        //alphabatized data properties below
                        dataItems.Add(new DataItem("Archived", cert.Archived));
                        dataItems.Add(new DataItem("FriendlyName", cert.FriendlyName));
                        dataItems.Add(new DataItem("Certficate Hash", cert.GetCertHashString()));
                        dataItems.Add(new DataItem("Certificate Format", cert.GetFormat()));
                        dataItems.Add(new DataItem("Effective Date", cert.GetEffectiveDateString()));
                        dataItems.Add(new DataItem("Expiration Date", cert.GetExpirationDateString()));
                        dataItems.Add(new DataItem("Full Issuer Name", cert.IssuerName.Format(true)));
                        dataItems.Add(new DataItem("Full Subject Name", cert.SubjectName.Format(true)));
                        dataItems.Add(new DataItem("Has Private Key", cert.HasPrivateKey));
                        dataItems.Add(new DataItem("Issuer", cert.Issuer));
                        dataItems.Add(new DataItem("Key Algorithm", cert.GetKeyAlgorithm()));
                        dataItems.Add(new DataItem("Key Algorithm Parameters", cert.GetKeyAlgorithmParametersString()));
                        dataItems.Add(new DataItem("Public Key", cert.GetPublicKeyString()));
                        dataItems.Add(new DataItem("Raw Certificate Data", cert.GetRawCertDataString()));
                        dataItems.Add(new DataItem("SerialNumberString", cert.GetSerialNumberString()));
                        dataItems.Add(new DataItem("Subject", cert.Subject));
                        dataItems.Add(new DataItem("Thumbprint", cert.Thumbprint));
                        dataItems.Add(new DataItem("Version", cert.Version));

                        dataItems.Add(new DataItem("------------------------", "------------------------"));
                        dataItems.Add(new DataItem("Extensions", string.Empty));
                        dataItems.Add(new DataItem("------------------------", "------------------------"));
                        foreach (var extension in cert.Extensions)
                        {
                            dataItems.Add(new DataItem(extension.Oid.FriendlyName, extension.Format(true)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    FiddlerApplication.Log.LogString("Unexpected error loading the assigned certificate." + ex.Message);
                }
            }

            _informationTab.DataGrid.DataSource = dataItems;
        }
Example #14
0
        private void Analizar(Byte[] ContenidoCertificado)
        {
            try
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(ContenidoCertificado);
                NumeroSerie            = InvertirStr(System.Text.Encoding.ASCII.GetString(cer.GetSerialNumber()));
                FechaFinCertificado    = System.Convert.ToDateTime(cer.GetExpirationDateString());
                FechaInicioCertificado = System.Convert.ToDateTime(cer.GetEffectiveDateString());
                EmisorCertificado      = cer.GetNameInfo(X509NameType.SimpleName, true);

                if (CA != null)
                {
                    foreach (System.Data.DataRow FilaCA in CA.Rows)
                    {
                        System.Security.Cryptography.X509Certificates.X509Certificate2 cerSAT = new System.Security.Cryptography.X509Certificates.X509Certificate2(System.Convert.FromBase64String(FilaCA["base64"].ToString()));
                        if (System.Convert.ToBase64String(cer.IssuerName.RawData) == System.Convert.ToBase64String(cerSAT.SubjectName.RawData))
                        {
                            EmitidoAutoridadCertificadora = true;
                        }
                    }
                }



                if (!String.IsNullOrEmpty(sArchivoKey) && !String.IsNullOrEmpty(sContraseña))
                {
                    byte[] CertModulus  = new byte[0];
                    byte[] CertExponent = new byte[0];

                    if (GetCertPublicKey(cer, out CertModulus, out CertExponent))
                    {
                        System.Security.Cryptography.RSACryptoServiceProvider RSA = null;
                        byte[] keyblob = SSLKey.opensslkey.GetFileBytes(sArchivoKey);
                        if (keyblob != null)
                        {
                            byte[] keyModulus  = new byte[0];
                            byte[] keyExponent = new byte[0];
                            if (SSLKey.opensslkey.getModulusExponentPrivateKeyInfo(keyblob, ConvertToSecureString(sContraseña), out keyModulus, out keyExponent))
                            {
                                if (CertExponent.Length == 3)
                                {
                                    CertExponent = IngresarByte(CertExponent, 4);
                                }
                                if (keyExponent.Length == 3)
                                {
                                    keyExponent = IngresarByte(keyExponent, 4);
                                }
                                if (CertModulus.Length < 128)
                                {
                                    CertModulus = IngresarByte(CertModulus, 128);
                                }
                                if (keyModulus.Length < 128)
                                {
                                    keyModulus = IngresarByte(keyModulus, 128);
                                }

                                if (CompareBytearrays(CertExponent, keyExponent) && CompareBytearrays(CertModulus, keyModulus))
                                {
                                    esKeyCertificado = true;
                                }
                            }
                        }
                    }
                }

                try
                {
                    String DatCert = cer.Subject;
                    int    posrfc  = DatCert.IndexOf("OID.2.5.4.45=") + ("OID.2.5.4.45=").Length;
                    RFCCertificado = DatCert.Substring(posrfc, DatCert.IndexOf(" ", posrfc) - posrfc).Trim().Replace(",", "");
                }
                catch (Exception ei)
                {
                }



                if (cer.Extensions["Uso de la clave"] != null)
                {
                    if (cer.Extensions["Uso de la clave"].RawData[3] == 192)
                    {
                        esCSD  = true;
                        esFIEL = false;
                    }

                    if (cer.Extensions["Uso de la clave"].RawData[3] == 232 || cer.Extensions["Uso de la clave"].RawData[3] == 216)
                    {
                        esFIEL = true;
                        esCSD  = false;
                    }
                }
                else if (cer.Extensions["Key Usage"] != null)
                {
                    if (cer.Extensions["Key Usage"].RawData[3] == 192)
                    {
                        esCSD  = true;
                        esFIEL = false;
                    }

                    if (cer.Extensions["Key Usage"].RawData[3] == 232 || cer.Extensions["Key Usage"].RawData[3] == 216)
                    {
                        esFIEL = true;
                        esCSD  = false;
                    }
                }
            }
            catch (Exception ex)
            {
                String Inner  = "";
                String Source = "";
                String Target = "";

                /* if (ex.InnerException != null)
                 *   Inner = " InnerException: " + ex.InnerException.Message;
                 * if (ex.Source != null)
                 *   Source = " Source: " + ex.Source;
                 * if (ex.TargetSite != null)
                 *   Target = " TargetSite: " + ex.TargetSite;
                 * throw new Exception("error analizando el certificado error: " + ex.Message + Inner + Source + Target );*/

                throw new Exception(ex.Message);
            }
        }
Example #15
0
        public static void SignPackage(Stream input, X509Certificate2 certificate, Stream output, bool signWholeFile)
        {
            JarFile inputJar = null;
            ZipOutputStream outputJar = null;

            // Assume the certificate is valid for at least an hour.
            DateTime timestamp = DateTime.Parse(certificate.GetEffectiveDateString()).AddHours(1);

            inputJar = new JarFile(input);  // Don't verify.

            Stream outputStream = null;
            if (signWholeFile)
            {
                outputStream = new MemoryStream();
            }
            else
            {
                outputStream = output;
            }
            outputJar = new ZipOutputStream(outputStream);
            outputJar.SetComment(null);
            outputJar.SetLevel(9);

            JarEntry je;

            Manifest manifest = addDigestsToManifest(inputJar);

            // Everything else
            copyFiles(manifest, inputJar, outputJar, timestamp);

            // otacert
            if (signWholeFile)
            {
                addOtacert(outputJar, certificate, timestamp, manifest);
            }

            var buffer = new MemoryStream();

            // MANIFEST.MF
            je = new JarEntry(JarFile.MANIFEST_NAME);
            je.DateTime = timestamp;
            manifest.Write(buffer);
            je.Size = buffer.Length;
            outputJar.PutNextEntry(je);
            buffer.WriteTo(outputJar);

            // CERT.SF
            var signature = new MemoryStream();
            je = new JarEntry(CERT_SF_NAME);
            je.DateTime = timestamp;
            buffer.SetLength(0);
            writeSignatureFile(manifest, signature);
            signature.WriteTo(buffer);
            je.Size = buffer.Length;
            outputJar.PutNextEntry(je);
            buffer.WriteTo(outputJar);

            // CERT.RSA
            je = new JarEntry(CERT_RSA_NAME);
            je.DateTime = timestamp;
            buffer.SetLength(0);
            writeSignatureBlock(signature, certificate, buffer);
            je.Size = buffer.Length;
            outputJar.PutNextEntry(je);
            buffer.WriteTo(outputJar);

            outputJar.Close();
            outputJar = null;

            if (signWholeFile)
            {
                signWholeOutputFile(((MemoryStream)outputStream).ToArray(),
                                    output, certificate);
            }
        }
		public SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website)
		{
			X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
			//
			SSLCertificate newcert = null, oldcert = null;
			// Ensure we perform operations safely and preserve the original state during all manipulations
			if (CheckCertificate(website))
				oldcert = GetCurrentSiteCertificate(website);
			//
			X509Certificate2 x509Cert = new X509Certificate2(certificate, password);

			#region Step 1: Register X.509 certificate in the store
			// Trying to keep X.509 store open as less as possible
			try
			{
				store.Open(OpenFlags.ReadWrite);
				//
				store.Add(x509Cert);
			}
			catch (Exception ex)
			{
				Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex);
				// Re-throw error
				throw;
			}
			finally
			{
				store.Close();
			} 
			#endregion

			#region Step 2: Instantiate a copy of new X.509 certificate
			try
			{
				//
				store.Open(OpenFlags.ReadWrite);
				//
				newcert = new SSLCertificate
				{
					Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false),
					FriendlyName = x509Cert.FriendlyName,
					CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()),
					Installed = true,
					DistinguishedName = x509Cert.Subject,
					Hash = x509Cert.GetCertHash(),
					SerialNumber = x509Cert.SerialNumber,
					ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()),
					ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()),
				};
			}
			catch (Exception ex)
			{
				// Rollback X.509 store changes
				store.Remove(x509Cert);
				// Log error
				Log.WriteError("SSLModuleService could not instantiate a copy of new X.509 certificate. All previous changes have been rolled back.", ex);
				// Re-throw
				throw;
			}
			finally
			{
				store.Close();
			} 
			#endregion

			#region Step 3: Remove old certificate from the web site if any
			try
			{
				store.Open(OpenFlags.ReadWrite);
				// Check if certificate already exists, remove it.
				if (oldcert != null)
					DeleteCertificate(oldcert, website);
			}
			catch (Exception ex)
			{
				// Rollback X.509 store changes
				store.Remove(x509Cert);
				// Log the error
				Log.WriteError(
					String.Format("SSLModuleService could not remove existing certificate from '{0}' web site. All changes have been rolled back.", website.Name), ex);
				// Re-throw
				throw;
			}
			finally
			{
				store.Close();
			} 
			#endregion

			#region Step 4: Register new certificate with HTTPS binding on the web site
			try
			{
				store.Open(OpenFlags.ReadWrite);
				//
				AddBinding(newcert, website);
			}
			catch (Exception ex)
			{
				// Install old certificate back if any
				if (oldcert != null)
					InstallCertificate(oldcert, website);
				// Rollback X.509 store changes
				store.Remove(x509Cert);
				// Log the error
				Log.WriteError(
					String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site. All changes have been rolled back.", website.Name), ex);
				// Re-throw
				throw;
			}
			finally
			{
				store.Close();
			} 
			#endregion
			//
			return newcert;
		}
        public static void VerifyItem(X509Certificate2 certificate)
        {
            try
              {
            if (certificate == null)
            {
              throw new Exception("Certificate is null.");
            }

            DateTime effectiveDate;

            if (!DateTime.TryParse(certificate.GetEffectiveDateString(), out effectiveDate))
            {
              throw new Exception("Could not parse client certificate effective date.");
            }
            if (effectiveDate > DateTime.Now)
            {
              throw new Exception("The client certificate is not yet effective.");
            }

            DateTime expirationDate;

            if (!DateTime.TryParse(certificate.GetExpirationDateString(), out expirationDate))
            {
              throw new Exception("Could not parse client certificate expiration date.");
            }
            if (expirationDate <= DateTime.Now)
            {
              throw new Exception("The client certificate has expired.");
            }
              }
              catch (Exception exception)
              {
            Log.Error(exception);
              }
        }