public static byte[] GetSubjectPublicKeyInfo(this System.Security.Cryptography.X509Certificates.X509Certificate certificate) { var cert = new X509CertificateParser().ReadCertificate(certificate.GetRawCertData()); var tbsCert = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate())); return(tbsCert.SubjectPublicKeyInfo.GetDerEncoded()); }
public static bool LdapSSLHandler(System.Security.Cryptography.X509Certificates.X509Certificate certificate, int[] certificateErrors) { #if !MONO X509Store store = null; X509Stores stores = X509StoreManager.LocalMachine; store = stores.TrustedRoot; X509Certificate x509 = null; byte[] data = certificate.GetRawCertData(); if (data != null) { x509 = new X509Certificate(data); } if (x509 != null) { //coll.Add(x509); if (!store.Certificates.Contains(x509)) { store.Import(x509); } } #endif return(true); }
public static void ValidateCertificate( System.Security.Cryptography.X509Certificates.X509Certificate certificate, MySqlBaseConnectionStringBuilder settings) { if (settings.SslMode >= MySqlSslMode.VerifyCA) { VerifyEmptyOrWhitespaceSslConnectionOption(settings.SslCa, nameof(settings.SslCa)); var sslCA = ReadSslCertificate(settings.SslCa); VerifyIssuer(sslCA, certificate); VerifyDates(sslCA); VerifyCAStatus(sslCA, true); #if NET452 VerifySignature(sslCA, DotNetUtilities.FromX509Certificate(certificate)); #else VerifySignature(sslCA, new X509CertificateParser().ReadCertificate(certificate.GetRawCertData())); #endif } if (settings.SslMode == MySqlSslMode.VerifyFull) { VerifyEmptyOrWhitespaceSslConnectionOption(settings.SslCert, nameof(settings.SslCert)); var sslCert = ReadSslCertificate(settings.SslCert); VerifyDates(sslCert); VerifyCAStatus(sslCert, false); VerifyEmptyOrWhitespaceSslConnectionOption(settings.SslKey, nameof(settings.SslKey)); var sslKey = ReadKey(settings.SslKey); VerifyKeyCorrespondsToCertificateKey(sslCert, sslKey); } }
internal static byte[] GetCertificateAssocicationData(TlsaSelector selector, TlsaMatchingType matchingType, X509Certificate certificate) { byte[] selectedBytes; switch (selector) { case TlsaSelector.FullCertificate: selectedBytes = certificate.GetRawCertData(); break; case TlsaSelector.SubjectPublicKeyInfo: var asymmetricKeyParameter = PublicKeyFactory.CreateKey(certificate.GetRawCertData()); selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter).GetDerEncoded(); break; default: throw new NotSupportedException(); } byte[] matchingBytes; switch (matchingType) { case TlsaMatchingType.Full: matchingBytes = selectedBytes; break; case TlsaMatchingType.Sha256Hash: Sha256Digest sha256Digest = new Sha256Digest(); sha256Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha256Digest.GetDigestSize()]; sha256Digest.DoFinal(matchingBytes, 0); break; case TlsaMatchingType.Sha512Hash: Sha512Digest sha512Digest = new Sha512Digest(); sha512Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha512Digest.GetDigestSize()]; sha512Digest.DoFinal(matchingBytes, 0); break; default: throw new NotSupportedException(); } return(matchingBytes); }
public ServerContext( SslServerStream stream, SecurityProtocolType securityProtocolType, X509Certificate serverCertificate, bool clientCertificateRequired, bool requestClientCertificate) : base(securityProtocolType) { SslStream = stream; ClientCertificateRequired = clientCertificateRequired; RequestClientCertificate = requestClientCertificate; // Convert the System.Security cert to a Mono Cert var cert = new MonoSecurity::Mono.Security.X509.X509Certificate(serverCertificate.GetRawCertData()); // Add server certificate to the certificate collection ServerSettings.Certificates = new X509CertificateCollection(); ServerSettings.Certificates.Add(cert); ServerSettings.UpdateCertificateRSA(); if (CertificateValidationHelper.SupportsX509Chain) { // Build the chain for the certificate and if the chain is correct, add all certificates // (except the root certificate [FIRST ONE] ... the client is supposed to know that one, // otherwise the whole concept of a trusted chain doesn't work out ... var chain = new X509Chain(X509StoreManager.IntermediateCACertificates); if (chain.Build(cert)) { for (var j = chain.Chain.Count - 1; j > 0; j--) { ServerSettings.Certificates.Add(chain.Chain[j]); } } } // Add requested certificate types ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count]; for (var j = 0; j < ServerSettings.CertificateTypes.Length; j++) { ServerSettings.CertificateTypes[j] = ClientCertificateType.RSA; } if (CertificateValidationHelper.SupportsX509Chain) { // Add certificate authorities var trusted = X509StoreManager.TrustedRootCertificates; var list = new string [trusted.Count]; var i = 0; foreach (var root in trusted) { list[i++] = root.IssuerName; } ServerSettings.DistinguisedNames = list; } }
//------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void CheckCertificate(X509Certificate certificate) { if (certificate == null) { throw new ArgumentNullException("certificate"); } if (certificate.GetRawCertData() == null) { throw new ArgumentException(Environment.GetResourceString("Argument_UninitializedCertificate")); } }
public X509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate cert) { if (cert == null) { throw new ArgumentNullException("cert"); } if (cert != null) { byte[] data = cert.GetRawCertData(); if (data != null) { x509 = new Mono.Security.X509.X509Certificate(data); } hideDates = false; } }
private bool Validator(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors ssl_policy_errors) { byte[] server_certificate = cert.GetRawCertData(); bool match = (server_certificate.Length == certificate.Length) && DateTime.Parse(cert.GetEffectiveDateString()) <= DateTime.Now && DateTime.Parse(cert.GetExpirationDateString()) >= DateTime.Now; int size = server_certificate.Length; int i = 0; while (match && i < size) { match = server_certificate[i] == certificate[i]; ++i; } return(match); }
public static bool Validator(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { byte[] rawCert = certificate.GetRawCertData(); System.Security.Cryptography.X509Certificates.X509Certificate2 cert = (System.Security.Cryptography.X509Certificates.X509Certificate2)certificate; string serverName = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.DnsName, false); IntPtr rawRawData = Marshal.AllocHGlobal(rawCert.Length); Marshal.Copy(rawCert, 0, rawRawData, rawCert.Length); bool certIsValid; certIsValid = ValidateCert(rawRawData, (ulong)rawCert.Length, serverName); Marshal.FreeHGlobal(rawRawData); return(certIsValid); }
public static bool Validator(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { //list of raw certs List <byte[]> rawCerts = new List <byte[]> (); rawCerts.Add(certificate.GetRawCertData()); //get rid of any duplicates in list foreach (System.Security.Cryptography.X509Certificates.X509ChainElement nextCertInChain in chain.ChainElements) { if (!certificate.Equals(nextCertInChain.Certificate)) { certificate = nextCertInChain.Certificate; rawCerts.Add(nextCertInChain.Certificate.GetRawCertData()); } } return(doSecurityCheckOnMainThread(rawCerts.ToArray())); }
/// <summary> /// Validates the web certificates. /// </summary> /// <returns> /// <c>true</c>, if web certificates was validated, <c>false</c> otherwise. /// </returns> /// <param name='sender'> /// <c>Object</c> usually parsed as WebRequest or HttpWebRequest. /// </param> /// <param name='endCert'> /// Certificate consumed in the request. /// </param> /// <param name='chain'> /// Certificate chain total or partial. /// </param> /// <param name='Errors'> /// Policy errors found during the chain build process. /// </param> public static bool ValidateWebCertificates(Object sender, System.Security.Cryptography.X509Certificates.X509Certificate endCert, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors Errors) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation"); bool bErrorsFound = false; try { X509Certificate BCCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(endCert); if (!CertificateIsTheSame(BCCert)) { chain.Build(new System.Security.Cryptography.X509Certificates.X509Certificate2(endCert.GetRawCertData())); if (Errors.Equals(SslPolicyErrors.None)) { if (chain == null || chain.ChainElements == null || chain.ChainElements.Count == 0) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Chain is empty"); bErrorsFound = true; } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Chain Element count: " + chain.ChainElements.Count); } foreach (System.Security.Cryptography.X509Certificates.X509ChainElement cert in chain.ChainElements) { X509Certificate BCCerto = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificate); if (CertIsSelfSigned(BCCerto)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** SELF SIGNED Certificate: CERT NAME " + BCCerto.SubjectDN.ToString() + " ;ID = " + BCCerto.SerialNumber); if (cert.Certificate.SerialNumber.Equals(chain.ChainElements[chain.ChainElements.Count - 1].Certificate.SerialNumber)) { string[] stringSeparators = new string[] { ";" }; string[] valids = _VALIDROOTAUTHORITIES.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (String validRoot in valids) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** SELF SIGNED Certificate check [" + validRoot + "]: " + cert.Certificate.SerialNumber + ":" + chain.ChainElements[chain.ChainElements.Count - 1].Certificate.SerialNumber); if (BCCerto.SubjectDN.ToString().Contains(validRoot)) { bErrorsFound = false; } else { bErrorsFound = true; } } } else { bErrorsFound = true; } } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** CERT NAME " + BCCerto.SubjectDN.ToString() + " ;ID = " + BCCerto.SerialNumber); } if (!CertIsValidNow(BCCerto)) { bErrorsFound = true; } } //if (chain.ChainElements.Count > 1 && !VerifyCertificateOCSP(chain)) bCertIsOk = true; //if (chain.ChainElements.Count > 1) bCertIsOk = true; // DO NOT check OCSP revocation URLs. The time consuming this is expensive. // TODO make this configurable and asynchronously in the case of enabled // !VerifyCertificateOCSP(chain) ---> ASYNC SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** OCSP Verification (certificate revocation check) is DISABLED for this build"); if (!bErrorsFound) { myCertificateList.Add(BCCert.GetHashCode(), DateTime.Now); SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Valid Certificate"); return(true); } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Invalid Certificate"); return(false); } } else if (Errors.Equals(SslPolicyErrors.RemoteCertificateChainErrors)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Errors found in the certificate chain."); } else if (Errors.Equals(SslPolicyErrors.RemoteCertificateNameMismatch)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: The certificate contains errors."); } else if (Errors.Equals(SslPolicyErrors.RemoteCertificateNotAvailable)) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: The certificate is not available"); } SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Policy Errors: " + Errors); return(false); } else //Trusted certificate { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Trusted Certificate"); return(true); } } catch (Exception e) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Unhandled exception: " + e.Message); return(false); } }
private static BcCert ToBcCertificate(X509Certificate certificate) { return(new X509CertificateParser().ReadCertificate(certificate.GetRawCertData())); }
//------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void CheckCertificate( X509Certificate certificate ) { if (certificate == null) { throw new ArgumentNullException( "certificate" ); } if (certificate.GetRawCertData() == null) { throw new ArgumentException(Environment.GetResourceString("Argument_UninitializedCertificate")); } }
internal static byte[] GetCertificateAssocicationData(TlsaSelector selector, TlsaMatchingType matchingType, X509Certificate certificate) { byte[] selectedBytes; switch (selector) { case TlsaSelector.FullCertificate: #if NETSTANDARD if (!(certificate is System.Security.Cryptography.X509Certificates.X509Certificate2)) { // what do? throw new NotImplementedException("X509Certificate unsupported, use X509Certificate2"); } selectedBytes = ((System.Security.Cryptography.X509Certificates.X509Certificate2)certificate).RawData; #else selectedBytes = certificate.GetRawCertData(); #endif break; case TlsaSelector.SubjectPublicKeyInfo: #if NETSTANDARD if (!(certificate is System.Security.Cryptography.X509Certificates.X509Certificate2)) { throw new NotImplementedException("X509Certificate unsupported, use X509Certificate2"); } selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(new X509CertificateParser().ReadCertificate(((System.Security.Cryptography.X509Certificates.X509Certificate2)certificate).RawData).GetPublicKey()).GetDerEncoded(); #else selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.FromX509Certificate(certificate).GetPublicKey()).GetDerEncoded(); #endif break; default: throw new NotSupportedException(); } byte[] matchingBytes; switch (matchingType) { case TlsaMatchingType.Full: matchingBytes = selectedBytes; break; case TlsaMatchingType.Sha256Hash: Sha256Digest sha256Digest = new Sha256Digest(); sha256Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha256Digest.GetDigestSize()]; sha256Digest.DoFinal(matchingBytes, 0); break; case TlsaMatchingType.Sha512Hash: Sha512Digest sha512Digest = new Sha512Digest(); sha512Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha512Digest.GetDigestSize()]; sha512Digest.DoFinal(matchingBytes, 0); break; default: throw new NotSupportedException(); } return(matchingBytes); }
public static X509.X509Certificate FromX509Certificate(X509Certificate x509Cert) { return new X509CertificateParser().ReadCertificate(x509Cert.GetRawCertData()); }
public void AdhocTest() { PDFDoc doc = new PDFDoc(GetTestPdf(SamplePdf)); // Ad-hoc field added for signing the PDF var signatureField = doc.FieldCreate("sample-field-name", Field.Type.e_signature, "signer name"); signatureField.SetValue("Signature Name"); var digitalSignatureField = new DigitalSignatureField(signatureField); // Before the rest of the lines or else it fails due to dictionary being empty digitalSignatureField.SignOnNextSave(GetCertificatePath("pdf-signing.pfx"), CertPassword); digitalSignatureField.SetReason("reason"); digitalSignatureField.SetContactInfo("*****@*****.**"); digitalSignatureField.SetLocation("location"); digitalSignatureField.SetFieldPermissions(DigitalSignatureField.FieldPermissions.e_include, new string[0]); digitalSignatureField.SetDocumentPermissions(DigitalSignatureField.DocumentPermissions .e_formfilling_signing_allowed); // Save file var temporaryFile = Path.GetTempFileName(); doc.Save(temporaryFile, pdftron.SDF.SDFDoc.SaveOptions.e_incremental); // VALIDATE var result = new PDFDoc(temporaryFile); var verificationOptions = new VerificationOptions(VerificationOptions.SignatureVerificationSecurityLevel .e_compatibility_and_archiving); // Using filepath/password directly makes it fail on adding trusted cert // THIS ONE FAILS: // verificationOptions.AddTrustedCertificate(GetCertificatePath("pdf-signing.crt")); var x509 = new X509Certificate(GetCertificatePath("pdf-signing.pfx"), CertPassword); verificationOptions.AddTrustedCertificate(x509.GetRawCertData()); DigitalSignatureFieldIterator signatureFieldIterator = result.GetDigitalSignatureFieldIterator(); for (; signatureFieldIterator.HasNext(); signatureFieldIterator.Next()) { var dsField = signatureFieldIterator.Current(); var verificationResult = dsField.Verify(verificationOptions); var status = verificationResult.GetTrustStatus(); var certCount = dsField.GetCertCount(); Console.WriteLine($"Verification status {status}"); Console.WriteLine($"Digest status {verificationResult.GetDigestStatus()}"); Console.WriteLine($"Digest document status {verificationResult.GetDocumentStatus()}"); Console.WriteLine($"Verification status {verificationResult.GetVerificationStatus()}"); Console.WriteLine($"Cert count: {certCount}"); Console.WriteLine($"Signature Name{dsField.GetSignatureName()}"); var sigTime = dsField.GetSigningTime(); Console.WriteLine($"Signing Time: {sigTime.day}/{sigTime.month}/{sigTime.year} {sigTime.hour}:{sigTime.minute}.{sigTime.second}"); Assert.True(status != VerificationResult.TrustStatus.e_untrusted, "Unexpected status e_untrusted"); Assert.True(certCount > 0, "DigitalSignatureField should have a certificate"); } }
public ServerContext( SslServerStream stream, SecurityProtocolType securityProtocolType, System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool requestClientCertificate) : base(securityProtocolType) { this.sslStream = stream; this.clientCertificateRequired = clientCertificateRequired; this.request_client_certificate = requestClientCertificate; Mono.Security.X509.X509Certificate x509Certificate1 = new Mono.Security.X509.X509Certificate(serverCertificate.GetRawCertData()); this.ServerSettings.Certificates = new Mono.Security.X509.X509CertificateCollection(); this.ServerSettings.Certificates.Add(x509Certificate1); this.ServerSettings.UpdateCertificateRSA(); this.ServerSettings.CertificateTypes = new ClientCertificateType[1]; this.ServerSettings.CertificateTypes[0] = ClientCertificateType.RSA; Mono.Security.X509.X509CertificateCollection rootCertificates = X509StoreManager.TrustedRootCertificates; string[] strArray = new string[rootCertificates.Count]; int num = 0; foreach (Mono.Security.X509.X509Certificate x509Certificate2 in rootCertificates) { strArray[num++] = x509Certificate2.IssuerName; } this.ServerSettings.DistinguisedNames = strArray; }
public static X509Certificate FromX509Certificate( System.Security.Cryptography.X509Certificates.X509Certificate x509Cert) { return(new X509CertificateParser().ReadCertificate(x509Cert.GetRawCertData())); }
internal static byte[] GetCertificateAssocicationData(TlsaSelector selector, TlsaMatchingType matchingType, X509Certificate certificate) { byte[] selectedBytes; switch (selector) { case TlsaSelector.FullCertificate: selectedBytes = certificate.GetRawCertData(); break; case TlsaSelector.SubjectPublicKeyInfo: selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.FromX509Certificate(certificate).GetPublicKey()).GetDerEncoded(); break; default: throw new NotSupportedException(); } byte[] matchingBytes; switch (matchingType) { case TlsaMatchingType.Full: matchingBytes = selectedBytes; break; case TlsaMatchingType.Sha256Hash: Sha256Digest sha256Digest = new Sha256Digest(); sha256Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha256Digest.GetDigestSize()]; sha256Digest.DoFinal(matchingBytes, 0); break; case TlsaMatchingType.Sha512Hash: Sha512Digest sha512Digest = new Sha512Digest(); sha512Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha512Digest.GetDigestSize()]; sha512Digest.DoFinal(matchingBytes, 0); break; default: throw new NotSupportedException(); } return matchingBytes; }
public static X509.X509Certificate FromX509Certificate(X509Certificate x509Cert) { return(new X509CertificateParser().ReadCertificate(x509Cert.GetRawCertData())); }
public byte[] CreatePkcs12(X509Certificate certificate, string password) { var store = new Pkcs12Store(); var entry = new X509CertificateEntry(new X509CertificateParser().ReadCertificate(certificate.GetRawCertData())); store.SetKeyEntry("erp", new AsymmetricKeyEntry(asymmetricCipherKeyPair.Private), new[] { entry }); var memoryStream = UnistreamReuse.Create(); store.Save(memoryStream, password.ToCharArray(), SecureRandom); return(memoryStream.ToArrayAndRelease()); }