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); } }
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(); }
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); }
public override void Validate(X509Certificate2 certificate) { //Tools.Instance.Logger.LogInfo("performing Client certificate validation into ServerCertificateValidator"); // Check that there is a certificate. if (certificate == null) { Tools.Instance.Logger.LogError("missing client certificate"); throw new ArgumentNullException("missing client certificate"); } //Stopwatch stopwatch = new Stopwatch(); //stopwatch.Start(); //// the client certificate must be in your trusted certificates store //bool validCertificate = new X509Chain().Build(certificate); //stopwatch.Stop(); //Tools.Instance.Logger.LogInfo("Client certificate validation: " + validCertificate.ToString() // + " took " + stopwatch.Elapsed.TotalSeconds + " sec"); //if (validCertificate) //{ // Check that the certificate issuer matches the configured issuer. if (_allowedIssuerName != certificate.IssuerName.Name) { Tools.Instance.Logger.LogError("client Certificate was not issued by a trusted issuer"); throw new SecurityTokenValidationException ("client Certificate was not issued by a trusted issuer"); } if (DateTime.Parse(certificate.GetExpirationDateString()) < DateTime.Now) { Tools.Instance.Logger.LogError("client Certificate Expired"); throw new IdentityValidationException("client Certificate Expired"); } if (_clientCertificate.Equals(certificate) == false) { Tools.Instance.Logger.LogError("Untrusted client Certificate"); throw new SecurityTokenValidationException ("Untrusted client Certificate"); } //} //else //{ // Tools.Instance.Logger.LogError("Client certificate validation X509 Validation failure. Invalid or Untrusted X509 Client Certificate"); // throw new SecurityTokenValidationException("Client certificate validation X509 Validation failure. Invalid or Untrusted X509 Client Certificate"); //} //Tools.Instance.Logger.LogInfo("Client certificate validation ended without exceptions"); }
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."); }
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; }
private bool ValidateCertificate(X509Certificate2 certificate, out string validationFailedMsg) { validationFailedMsg = null; if (certificate == null || string.IsNullOrEmpty(certificate.Subject) || string.IsNullOrEmpty(certificate.SerialNumber)) { validationFailedMsg = "Invalid Certificate."; return false; } // Check the issuer if (string.Compare(validCertificate.Issuer, certificate.Issuer) != 0) { validationFailedMsg = "Invalid Certificate."; return false; } // Check the expiry date of the certificate string certExpiryDate = certificate.GetExpirationDateString(); int? certExpiredDays = null; if (!string.IsNullOrEmpty(certExpiryDate)) certExpiredDays = DateTime.Compare(DateTime.Now, DateTime.Parse(certExpiryDate)); if (!certExpiredDays.HasValue) { validationFailedMsg = "Invalid Certificate."; return false; } else if (certExpiredDays.Value > 0) { validationFailedMsg = "Certificate has expired."; return false; } return true; }
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; } }
public static bool VerifySign(string plaintext, string publicKey, string signature) { byte[] bInput; bInput = Convert.FromBase64String(publicKey); X509Certificate2 x509 = new X509Certificate2(); x509.Import(bInput); # region 1. Check Chữ ký còn hạn hay không? // 1. Check Chữ ký còn hạn hay không? DateTime expirationDate = DateTime.Parse(x509.GetExpirationDateString()); if (expirationDate.CompareTo(DateTime.Now) <= 0) throw new Exception("Chữ ký không còn hạn sử dụng"); # endregion # region 2. Check chữ ký có bị thu hồi hay không? // 2. Check chữ ký có bị thu hồi hay không? //check ở tầng trên // Đoạn này trở lên con web service của em: số serial number lấy bằng số: x509.SerialNumber # endregion # region 3. Check Root // 3. Check Root //error if (!x509.Verify()) throw new VerifySignatureHQException("Lỗi check root publickey"); bool valid = false; X509Certificate2 crt2 = FindIssuer(x509); if (crt2 == null) valid = FindRoot(x509); else valid = FindRoot(crt2); //if (!valid) throw new VerifySignatureHQException("Khóa là sai root"); # endregion # region 4. Xác thực chữ ký có đúng không? (Check Signature) // 4. Xác thực chữ ký có đúng không? (Check Signature) RSACryptoServiceProvider CSP = (RSACryptoServiceProvider)(x509.PublicKey.Key); byte[] data = UnicodeEncoding.UTF8.GetBytes(plaintext); SHA1 sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(data); byte[] signatureByte = System.Convert.FromBase64String(signature); //VerifyHash if (!CSP.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signatureByte)) throw new Exception("Xác minh chữ ký không thành công"); # endregion return 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; }
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; }
/// <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; }
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); } }
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); } }
public static ClaimsIdentity CreateFromCertificate(X509Certificate2 certificate, string authenticationType = "X.509", bool includeAllClaims = false) { var claims = new List<Claim>(); var issuer = certificate.Issuer; claims.Add(new Claim("issuer", issuer)); var thumbprint = certificate.Thumbprint; claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, ClaimValueTypes.Base64Binary, issuer)); string name = certificate.SubjectName.Name; if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.X500DistinguishedName, name, ClaimValueTypes.String, issuer)); } if (includeAllClaims) { name = certificate.SerialNumber; if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.SerialNumber, name, "http://www.w3.org/2001/XMLSchema#string", issuer)); } name = certificate.GetNameInfo(X509NameType.DnsName, false); if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.Dns, name, ClaimValueTypes.String, issuer)); } name = certificate.GetNameInfo(X509NameType.SimpleName, false); if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, issuer)); } name = certificate.GetNameInfo(X509NameType.EmailName, false); if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.Email, name, ClaimValueTypes.String, issuer)); } name = certificate.GetNameInfo(X509NameType.UpnName, false); if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.Upn, name, ClaimValueTypes.String, issuer)); } name = certificate.GetNameInfo(X509NameType.UrlName, false); if (!string.IsNullOrEmpty(name)) { claims.Add(new Claim(ClaimTypes.Uri, name, ClaimValueTypes.String, issuer)); } RSA key = certificate.PublicKey.Key as RSA; if (key != null) { claims.Add(new Claim(ClaimTypes.Rsa, key.ToXmlString(false), ClaimValueTypes.RsaKeyValue, issuer)); } DSA dsa = certificate.PublicKey.Key as DSA; if (dsa != null) { claims.Add(new Claim(ClaimTypes.Dsa, dsa.ToXmlString(false), ClaimValueTypes.DsaKeyValue, issuer)); } var expiration = certificate.GetExpirationDateString(); if (!string.IsNullOrEmpty(expiration)) { claims.Add(new Claim(ClaimTypes.Expiration, expiration, ClaimValueTypes.DateTime, issuer)); } } return new ClaimsIdentity(claims, authenticationType); }
/// <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()); } }
static void Main(string[] args) { Console.Error.WriteLine("ShowAdCerts v1.0, (c) 2012 Zetetic LLC"); if (args.Length == 1 && args[0].EndsWith("?")) { Console.Error.WriteLine(@"Switches (all are optional): -h host or domain name (default = default logon server) -f ldap filter (default = userCertificate=* ) -b search base (default = domain root NC ) -v (turn on cert validation of non-expired certs ) -r (dump raw cert data ) "); System.Environment.ExitCode = 1; return; } string searchbase = null, filter = "(&(userCertificate=*))", host = ""; bool validate = false, raw = false; try { for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "-h": host = args[++i]; break; case "-r": raw = true; break; case "-f": filter = args[++i]; switch (filter.ToLowerInvariant()) { case "computer": filter = "(&(userCertificate=*)(objectCategory=computer))"; break; case "user": case "person": filter = "(&(userCertificate=*)(objectCategory=person))"; break; } break; case "-b": searchbase = args[++i]; break; case "-v": validate = true; break; default: Console.Error.WriteLine("Unknown argument {0}", args[i]); break; } } using (var conn = new LdapConnection(host)) { conn.SessionOptions.ProtocolVersion = 3; if (string.IsNullOrEmpty(searchbase)) { var e = ((SearchResponse)conn.SendRequest(new SearchRequest( "", "(&(objectClass=*))", SearchScope.Base, "defaultNamingContext"))).Entries[0]; searchbase = e.Attributes["defaultNamingContext"][0].ToString(); } var srch = new SearchRequest(searchbase, filter, SearchScope.Subtree, "userCertificate"); var pager = new PageResultRequestControl(); srch.Controls.Add(pager); int count = 0; while (true) { var resp = (SearchResponse)conn.SendRequest(srch); foreach (SearchResultEntry se in resp.Entries) { if (!se.Attributes.Contains("userCertificate")) { continue; } Console.WriteLine("# {0}", ++count); Console.WriteLine("dn: {0}", se.DistinguishedName); foreach (var o in se.Attributes["userCertificate"].GetValues(typeof(byte[]))) { byte[] bytes = (byte[])o; try { X509Certificate2 cert = new X509Certificate2(bytes); Console.WriteLine("subject: {0}", string.IsNullOrEmpty(cert.Subject) ? cert.SubjectName.Name : cert.Subject); Console.WriteLine("issuer: {0}", cert.Issuer); Console.WriteLine("thumbprint: {0}", cert.Thumbprint); Console.WriteLine("serial: {0}", cert.SerialNumber); var estr = cert.GetExpirationDateString(); var expired = false; if (!string.IsNullOrEmpty(estr)) { Console.WriteLine("exp: {0}", estr); DateTime dt; if (DateTime.TryParse(estr, out dt) && dt < DateTime.Now) { Console.WriteLine("expired: TRUE"); expired = true; } } if (validate && !expired) { Console.WriteLine("valid: {0}", cert.Verify().ToString().ToUpperInvariant()); } } catch (Exception e) { Console.WriteLine("exception: {0}, {1}", e.GetType(), e.Message); } if (raw) { var s = Convert.ToBase64String(bytes); Console.WriteLine("-----BEGIN CERTIFICATE-----"); for (int i = 0; i < s.Length; i += 78) { Console.WriteLine(s.Substring(i, Math.Min(78, s.Length - i))); } Console.WriteLine("-----END CERTIFICATE-----"); } Console.WriteLine("-"); } Console.WriteLine(""); } var rc = resp.Controls.SingleOrDefault(t => t is PageResultResponseControl) as PageResultResponseControl; if (rc == null || rc.Cookie == null || rc.Cookie.Length == 0) break; pager.Cookie = rc.Cookie; } } } catch (Exception e) { Console.Error.WriteLine("Error type = {0}, message = {1}, stack = {2}", e.GetType(), e.Message, e.StackTrace); System.Environment.ExitCode = 2; } }
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; }
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; }
///<summary> /// /// Método que retorna a data da expiração da chave certificada /// através do caminho passado. /// /// Retorna excecao: Certificado Inválido ou com senha /// ///</summary> public static string dataExpiracao(string caminho) { try { X509Certificate2 data = new X509Certificate2(caminho); return data.GetExpirationDateString(); } catch (CryptographicException ce) { throw new excecao.excecao(MSG_CERTIFICADO); } catch (ArgumentException ae) { throw new excecao.excecao(MSG_CERTIFICADO_INEXISTENTE); } }
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); } } }