static bool ValidateCertAgainstBaseline(IDictionary<string, string> certVals, X509Certificate cer) { bool retVal = true; long effectiveDateFound, expiryDateFound, effectiveDateBsl, expiryDateBsl; byte[] bytes; string str; int hash; IntPtr handle; // now validate against the actual cert if (!certVals["HashString"].Equals(cer.GetCertHashString())) { TestFramework.LogError("001", "Expected hash string: " + certVals["HashString"] + ", found: " + cer.GetCertHashString()); retVal = false; } // check the dates try { effectiveDateBsl = Convert.ToInt64(certVals["EffectiveDateStringInTicks"]); effectiveDateFound = DateTime.Parse(cer.GetEffectiveDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks; expiryDateBsl = Convert.ToInt64(certVals["ExpirationDateStringInTicks"]); expiryDateFound = DateTime.Parse(cer.GetExpirationDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks; if (effectiveDateBsl != effectiveDateFound) { TestFramework.LogError("002", "Expected \"Valid From\": [" + (new DateTime(effectiveDateBsl, DateTimeKind.Utc)).ToString() + "], found: [" + cer.GetEffectiveDateString() +" nonUTC]"); TestFramework.LogError("002", " ticks(" + effectiveDateBsl + ") found ticks(" + effectiveDateFound + ")"); retVal = false; } if (expiryDateBsl != expiryDateFound) { TestFramework.LogError("003", "Expected \"Valid To\": [" + (new DateTime(expiryDateBsl)).ToString() + "], found: [" + cer.GetExpirationDateString() + " nonUTC]"); TestFramework.LogError("003", " ticks(" + expiryDateBsl + ") found ticks(" + expiryDateFound + ")"); retVal = false; } } catch (Exception e) { TestFramework.LogError("103", "Unexpected exception: " + e); retVal = false; } TestFramework.LogInformation(" Validating field: Format"); if (!certVals["Format"].Equals(cer.GetFormat())) { TestFramework.LogError("004", "Expected format: " + certVals["Format"] + ", found: " + cer.GetFormat()); retVal = false; } TestFramework.LogInformation(" Validating field: Issuer"); if (!certVals["Issuer"].Equals(cer.Issuer)) { TestFramework.LogError("005", "Expected issuer: " + certVals["Issuer"] + ", found: " + cer.Issuer); retVal = false; } TestFramework.LogInformation(" Validating field: KeyAlgorithm"); if (!certVals["KeyAlgorithm"].Equals(cer.GetKeyAlgorithm())) { TestFramework.LogError("006", "Expected key algorithm: " + certVals["KeyAlgorithm"] + ", found: " + cer.GetKeyAlgorithm()); retVal = false; } TestFramework.LogInformation(" Validating field: KeyAlgorithmParameters"); if (!certVals["KeyAlgorithmParameters"].Equals(cer.GetKeyAlgorithmParametersString())) { TestFramework.LogError("007", "Expected key alg parameters :" + certVals["KeyAlgorithmParameters"] + ", found :" + cer.GetKeyAlgorithmParametersString()); retVal = false; } TestFramework.LogInformation(" Validating field: PublicKeyString"); if (!certVals["PublicKeyString"].Equals(cer.GetPublicKeyString())) { TestFramework.LogError("008", "Expected public key: " + certVals["PublicKeyString"] + ", found: " + cer.GetPublicKeyString()); retVal = false; } TestFramework.LogInformation(" Validating field: SerialNumberString"); if (!certVals["SerialNumberString"].Equals(cer.GetSerialNumberString())) { TestFramework.LogError("009", "Expected serial number: " + certVals["SerialNumberString"] + ", found: " + cer.GetSerialNumberString()); retVal = false; } TestFramework.LogInformation(" Validating field: Subject"); if (!certVals["Subject"].Equals(cer.Subject)) { TestFramework.LogError("010", "Expected subject: " + certVals["Subject"] + ", found: " + cer.Subject); retVal = false; } TestFramework.LogInformation(" Retrieving field: CertHash"); bytes = cer.GetCertHash(); TestFramework.LogInformation(" Retrieving field: HashCode"); hash = cer.GetHashCode(); TestFramework.LogInformation(" Retrieving field: RawCertHash"); bytes = cer.GetRawCertData(); TestFramework.LogInformation(" Retrieving field: RawCertDataString"); str = cer.GetRawCertDataString(); TestFramework.LogInformation(" Retrieving field: SerialNumber"); bytes = cer.GetSerialNumber(); TestFramework.LogInformation(" Retrieving field: ToString()"); str = cer.ToString(); TestFramework.LogInformation(" Retrieving field: ToString(true)"); str = cer.ToString(true); TestFramework.LogInformation(" Retrieving field: Handle"); handle = GetHandle(cer); TestFramework.LogInformation(" Testing: Equality with a string"); if (cer.Equals(str)) { TestFramework.LogError("110", "X509Certificate \"equals\" a string?"); retVal = false; } TestFramework.LogInformation(" Testing: Equality with itself(1)"); if (!cer.Equals((object)cer)) { TestFramework.LogError("120", "X509Certificate does not equal itself"); retVal = false; } TestFramework.LogInformation(" Testing: Equality with itself(2)"); if (!cer.Equals(cer)) { TestFramework.LogError("130", "X509Certificate does not equal itself"); retVal = false; } return retVal; }
private void _BindCert(X509Certificate cert) { IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(_IP), _Port); HttpApi.SslCertificateInfo certificateInfo = HttpApi.QuerySslCertificateInfo(endpoint); if (certificateInfo != null && !certificateInfo.Hash.SequenceEqual(cert.GetCertHash())) { if (!IsAdministrator()) { throw new AuthenticationException(); } HttpApi.DeleteCertificateBinding(endpoint); HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid(_AppGUID)); } }
static bool ValidateServerCertficate( object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { // Good certificate. return(true); } log.DebugFormat("SSL certificate error: {0}", sslPolicyErrors); bool certMatch = false; // Assume failure byte[] certHash = cert.GetCertHash(); if (certHash.Length == apiCertHash.Length) { certMatch = true; // Now assume success. for (int idx = 0; idx < certHash.Length; idx++) { if (certHash[idx] != apiCertHash[idx]) { certMatch = false; // No match break; } } } // Return true => allow unauthenticated server, // false => disallow unauthenticated server. return(certMatch); }
private static bool ValidateClientCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { StringBuilder builder = new StringBuilder(); builder.AppendFormat("SslPolicyErrors: {0}\r\n", errors); if (certificate != null) { builder.AppendFormat("Subject: {0}\r\n", certificate.Subject); builder.AppendFormat("Issuer: {0}\r\n", certificate.Issuer); builder.AppendFormat("Hash: {0}", BitConverter.ToString(certificate.GetCertHash())); } Console.WriteLine(builder.ToString()); SslStream sslStream = sender as SslStream; SslClientCertificateInfo.Add(sslStream.GetHashCode(), builder.ToString()); if (errors == SslPolicyErrors.RemoteCertificateNotAvailable) { // Do not allow the server to communicate with unauthenticated clients. return(false); } return(true); }
private X509SecurityToken getToken(string which) { X509SecurityToken token = null; X509CertificateStore store = null; string serverKeyIdentifier = "bBwPfItvKp3b6TNDq+14qs58VJQ="; //"po3h4Y4J8ITs/pW3acuRjpT8V1o="; string clientKeyIdentifier = "gBfo0147lM6cKnTbbMSuMVvmFY4="; //"Gu4aD7+bYTVtmSveoPIWTRtzD3M="; store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore); store.OpenRead(); X509CertificateCollection coll; if (which == "server") { coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(serverKeyIdentifier)); } else { coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(clientKeyIdentifier)); } if (coll.Count > 0) { X509Certificate cert = (X509Certificate)coll[0]; token = new X509SecurityToken(cert); byte[] hash = cert.GetCertHash(); string hashstring = cert.GetCertHashString(); string serialstring = cert.GetSerialNumberString(); } return(token); }
public bool ValidateServerCertficate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return(true); } if (m_acceptAll) { return(true); } string certHash = null; try { certHash = Utility.ByteArrayAsHexString(cert.GetCertHash()); if (certHash != null && m_validHashes != null) { foreach (var hash in m_validHashes) { if (!string.IsNullOrEmpty(hash) && certHash.Equals(hash, StringComparison.OrdinalIgnoreCase)) { return(true); } } } } catch (Exception ex) { throw new Exception(Strings.SslCertificateValidator.VerifyCertificateHashError(ex, sslPolicyErrors), ex); } return(false); }
internal static void UploadCert(string accessToken, string appId, string certPath) { var cert = new X509Certificate(); cert.Import(certPath);// the path fo cert file var expirationDate = DateTime.Parse(cert.GetExpirationDateString()).ToUniversalTime(); var startDate = DateTime.Parse(cert.GetEffectiveDateString()).ToUniversalTime(); var binCert = cert.GetRawCertData(); var activeDirectoryClient = new ActiveDirectoryClient(new Uri("https://graph.windows.net/erwinmcm.com"), async() => { return(await Task.Run(() => { return accessToken; })); }); var keyCredential = new Microsoft.Azure.ActiveDirectory.GraphClient.KeyCredential { CustomKeyIdentifier = cert.GetCertHash(), EndDate = expirationDate, KeyId = Guid.NewGuid(), StartDate = startDate, Type = "AsymmetricX509Cert", Usage = "Verify", Value = binCert }; var application = activeDirectoryClient.Applications[appId].ExecuteAsync().Result; application.KeyCredentials.Add(keyCredential); application.UpdateAsync().Wait(); }
private static void UploadStandAloneCertificate(X509Store store2, X509Certificate cert) { using (var serverManager = new ServerManager()) { const string newbindinginformation = "*:443:"; foreach (var s in serverManager.Sites) { var bindingIndex = -1; foreach (var b in s.Bindings.Where(r => r.BindingInformation.Contains(newbindinginformation))) { bindingIndex = s.Bindings.IndexOf(b); } if (bindingIndex != -1) { s.Bindings.RemoveAt(bindingIndex); } } var site = serverManager.Sites[HostingEnvironment.SiteName]; AddHttpsBinding(site, newbindinginformation, cert.GetCertHash(), store2.Name); AddRewriteRules(serverManager, site); serverManager.CommitChanges(); } }
public void ConstructorIntPtr() { byte[] cert = { 0x30, 0x82, 0x01, 0xFF, 0x30, 0x82, 0x01, 0x6C, 0x02, 0x05, 0x02, 0x72, 0x00, 0x06, 0xE8, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02, 0x05, 0x00, 0x30, 0x5F, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x20, 0x30, 0x1E, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 0x17, 0x52, 0x53, 0x41, 0x20, 0x44, 0x61, 0x74, 0x61, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x31, 0x2E, 0x30, 0x2C, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x25, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x74, 0x79, 0x30, 0x1E, 0x17, 0x0D, 0x39, 0x36, 0x30, 0x33, 0x31, 0x32, 0x31, 0x38, 0x33, 0x38, 0x34, 0x37, 0x5A, 0x17, 0x0D, 0x39, 0x37, 0x30, 0x33, 0x31, 0x32, 0x31, 0x38, 0x33, 0x38, 0x34, 0x36, 0x5A, 0x30, 0x61, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0A, 0x43, 0x61, 0x6C, 0x69, 0x66, 0x6F, 0x72, 0x6E, 0x69, 0x61, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 0x0B, 0x43, 0x6F, 0x6D, 0x6D, 0x65, 0x72, 0x63, 0x65, 0x4E, 0x65, 0x74, 0x31, 0x27, 0x30, 0x25, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x1E, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x74, 0x79, 0x30, 0x70, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x5F, 0x00, 0x30, 0x5C, 0x02, 0x55, 0x2D, 0x58, 0xE9, 0xBF, 0xF0, 0x31, 0xCD, 0x79, 0x06, 0x50, 0x5A, 0xD5, 0x9E, 0x0E, 0x2C, 0xE6, 0xC2, 0xF7, 0xF9, 0xD2, 0xCE, 0x55, 0x64, 0x85, 0xB1, 0x90, 0x9A, 0x92, 0xB3, 0x36, 0xC1, 0xBC, 0xEA, 0xC8, 0x23, 0xB7, 0xAB, 0x3A, 0xA7, 0x64, 0x63, 0x77, 0x5F, 0x84, 0x22, 0x8E, 0xE5, 0xB6, 0x45, 0xDD, 0x46, 0xAE, 0x0A, 0xDD, 0x00, 0xC2, 0x1F, 0xBA, 0xD9, 0xAD, 0xC0, 0x75, 0x62, 0xF8, 0x95, 0x82, 0xA2, 0x80, 0xB1, 0x82, 0x69, 0xFA, 0xE1, 0xAF, 0x7F, 0xBC, 0x7D, 0xE2, 0x7C, 0x76, 0xD5, 0xBC, 0x2A, 0x80, 0xFB, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02, 0x05, 0x00, 0x03, 0x7E, 0x00, 0x54, 0x20, 0x67, 0x12, 0xBB, 0x66, 0x14, 0xC3, 0x26, 0x6B, 0x7F, 0xDA, 0x4A, 0x25, 0x4D, 0x8B, 0xE0, 0xFD, 0x1E, 0x53, 0x6D, 0xAC, 0xA2, 0xD0, 0x89, 0xB8, 0x2E, 0x90, 0xA0, 0x27, 0x43, 0xA4, 0xEE, 0x4A, 0x26, 0x86, 0x40, 0xFF, 0xB8, 0x72, 0x8D, 0x1E, 0xE7, 0xB7, 0x77, 0xDC, 0x7D, 0xD8, 0x3F, 0x3A, 0x6E, 0x55, 0x10, 0xA6, 0x1D, 0xB5, 0x58, 0xF2, 0xF9, 0x0F, 0x2E, 0xB4, 0x10, 0x55, 0x48, 0xDC, 0x13, 0x5F, 0x0D, 0x08, 0x26, 0x88, 0xC9, 0xAF, 0x66, 0xF2, 0x2C, 0x9C, 0x6F, 0x3D, 0xC3, 0x2B, 0x69, 0x28, 0x89, 0x40, 0x6F, 0x8F, 0x35, 0x3B, 0x9E, 0xF6, 0x8E, 0xF1, 0x11, 0x17, 0xFB, 0x0C, 0x98, 0x95, 0xA1, 0xC2, 0xBA, 0x89, 0x48, 0xEB, 0xB4, 0x06, 0x6A, 0x22, 0x54, 0xD7, 0xBA, 0x18, 0x3A, 0x48, 0xA6, 0xCB, 0xC2, 0xFD, 0x20, 0x57, 0xBC, 0x63, 0x1C }; // will only work on Windows (MS or Mono) // this isn't much of a problem because the structure CERT_CONTEXT (IntPtr) // is specific to CryptoAPI/Windows. IntPtr handle = IntPtr.Zero; if (Path.DirectorySeparatorChar == '\\') { handle = GetHandle(cert); } else { handle = GetHandleEx(cert); } X509Certificate x509 = new X509Certificate(handle); byte[] hash = { 0xD6, 0x2F, 0x48, 0xD0, 0x13, 0xEE, 0x7F, 0xB5, 0x8B, 0x79, 0x07, 0x45, 0x12, 0x67, 0x0D, 0x9C, 0x5B, 0x3A, 0x5D, 0xA9 }; Assert.AreEqual(hash, x509.GetCertHash(), "GetCertHash"); Assert.AreEqual("D62F48D013EE7FB58B79074512670D9C5B3A5DA9", x509.GetCertHashString(), "GetCertHashString"); #if NET_2_0 DateTime from = DateTime.ParseExact(x509.GetEffectiveDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime(); Assert.AreEqual("03/12/1996 18:38:47", from.ToString(), "GetEffectiveDateString"); DateTime until = DateTime.ParseExact(x509.GetExpirationDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime(); Assert.AreEqual("03/12/1997 18:38:46", until.ToString(), "GetExpirationDateString"); #else // fx 1.x has a bug where the returned dates were always in the Seattle time zone Assert.AreEqual("03/12/1996 10:38:47", x509.GetEffectiveDateString(), "GetEffectiveDateString"); Assert.AreEqual("03/12/1997 10:38:46", x509.GetExpirationDateString(), "GetExpirationDateString"); // which was making it easier to test the dates ;-) #endif Assert.AreEqual("X509", x509.GetFormat(), "GetFormat"); Assert.AreEqual(-701544240, x509.GetHashCode(), "GetHashCode"); Assert.AreEqual("C=US, O=\"RSA Data Security, Inc.\", OU=Secure Server Certification Authority", x509.GetIssuerName(), "GetIssuerName"); Assert.AreEqual("1.2.840.113549.1.1.1", x509.GetKeyAlgorithm(), "GetKeyAlgorithm"); byte[] keyparams = { 0x05, 0x00 }; Assert.AreEqual(keyparams, x509.GetKeyAlgorithmParameters(), "GetKeyAlgorithmParameters"); Assert.AreEqual("0500", x509.GetKeyAlgorithmParametersString(), "GetKeyAlgorithmParametersString"); Assert.AreEqual("C=US, S=California, O=CommerceNet, OU=Server Certification Authority", x509.GetName(), "GetName"); byte[] pubkey = { 0x30, 0x5C, 0x02, 0x55, 0x2D, 0x58, 0xE9, 0xBF, 0xF0, 0x31, 0xCD, 0x79, 0x06, 0x50, 0x5A, 0xD5, 0x9E, 0x0E, 0x2C, 0xE6, 0xC2, 0xF7, 0xF9, 0xD2, 0xCE, 0x55, 0x64, 0x85, 0xB1, 0x90, 0x9A, 0x92, 0xB3, 0x36, 0xC1, 0xBC, 0xEA, 0xC8, 0x23, 0xB7, 0xAB, 0x3A, 0xA7, 0x64, 0x63, 0x77, 0x5F, 0x84, 0x22, 0x8E, 0xE5, 0xB6, 0x45, 0xDD, 0x46, 0xAE, 0x0A, 0xDD, 0x00, 0xC2, 0x1F, 0xBA, 0xD9, 0xAD, 0xC0, 0x75, 0x62, 0xF8, 0x95, 0x82, 0xA2, 0x80, 0xB1, 0x82, 0x69, 0xFA, 0xE1, 0xAF, 0x7F, 0xBC, 0x7D, 0xE2, 0x7C, 0x76, 0xD5, 0xBC, 0x2A, 0x80, 0xFB, 0x02, 0x03, 0x01, 0x00, 0x01 }; Assert.AreEqual(pubkey, x509.GetPublicKey(), "GetPublicKey"); Assert.AreEqual("305C02552D58E9BFF031CD7906505AD59E0E2CE6C2F7F9D2CE556485B1909A92B336C1BCEAC823B7AB3AA76463775F84228EE5B645DD46AE0ADD00C21FBAD9ADC07562F89582A280B18269FAE1AF7FBC7DE27C76D5BC2A80FB0203010001", x509.GetPublicKeyString(), "GetPublicKeyString"); Assert.AreEqual(cert, x509.GetRawCertData(), "GetRawCertData"); Assert.AreEqual(ToString(cert), x509.GetRawCertDataString(), "GetRawCertDataString"); byte[] serial = { 0xE8, 0x06, 0x00, 0x72, 0x02 }; Assert.AreEqual(serial, x509.GetSerialNumber(), "GetSerialNumber"); #if NET_2_0 Assert.AreEqual("02720006E8", x509.GetSerialNumberString(), "GetSerialNumberString"); #else Assert.AreEqual("E806007202", x509.GetSerialNumberString(), "GetSerialNumberString"); #endif }
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return true; } byte[] receivedCertificateHash = certificate.GetCertHash(); //If length differs, obviously different hash. if (receivedCertificateHash.Length != hardCodedServerCertificateHash.Length) { return false; } //Check that each byte is the same for (int i = 0; i < hardCodedServerCertificateHash.Length; i++) { if (receivedCertificateHash[i] != hardCodedServerCertificateHash[i]) { return false; } } //Equality of the certificates confirmed. return true; }
public override IHTTPResponse performSync() { OnStart(); WWW wWW = new WWW(getUrl()); ServicePoint servicePoint = ServicePointManager.FindServicePoint(getUrl(), null); if (servicePoint != null) { Debug.Log("Located service point."); X509Certificate certificate = servicePoint.Certificate; if (certificate != null) { Debug.Log("Certificate hash: " + certificate.GetCertHash()); } } else { Debug.Log("None found"); } HTTPBaseResponseImpl hTTPBaseResponseImpl = new HTTPBaseResponseImpl(this); if (!string.IsNullOrEmpty(wWW.error)) { hTTPBaseResponseImpl.setStatusCode(parseStatusFromMessage(wWW.error)); OnError(hTTPBaseResponseImpl, new HTTPException(wWW.error)); } else { hTTPBaseResponseImpl.setStatusCode(200); hTTPBaseResponseImpl.setDocument(new HTTPBaseDocumentImpl(wWW.bytes)); OnSuccess(hTTPBaseResponseImpl); } OnComplete(); return(hTTPBaseResponseImpl); }
private static bool ValidateServerCertficate( object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return(true); } bool certMatch = false; byte[] certHash = cert.GetCertHash(); if (certHash.Length == ApiCertHash.Length) { certMatch = true; for (int idx = 0; idx < certHash.Length; idx++) { if (certHash[idx] != ApiCertHash[idx]) { certMatch = false; break; } } } return(certMatch); }
public void PartialTrust_DenyUnrestricted() { X509Certificate x509 = new X509Certificate(cert); X509Certificate clone = new X509Certificate(x509); Assert.IsTrue(x509.Equals(clone), "Equals 1"); Assert.IsTrue(clone.Equals(x509), "Equals 2"); byte[] hash = { 0xD6, 0x2F, 0x48, 0xD0, 0x13, 0xEE, 0x7F, 0xB5, 0x8B, 0x79, 0x07, 0x45, 0x12, 0x67, 0x0D, 0x9C, 0x5B, 0x3A, 0x5D, 0xA9 }; Assert.AreEqual(hash, x509.GetCertHash(), "GetCertHash"); Assert.AreEqual("D62F48D013EE7FB58B79074512670D9C5B3A5DA9", x509.GetCertHashString(), "GetCertHashString"); DateTime from = DateTime.ParseExact(x509.GetEffectiveDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime(); Assert.AreEqual("03/12/1996 18:38:47", from.ToString(), "GetEffectiveDateString"); DateTime until = DateTime.ParseExact(x509.GetExpirationDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime(); Assert.AreEqual("03/12/1997 18:38:46", until.ToString(), "GetExpirationDateString"); Assert.AreEqual("X509", x509.GetFormat(), "GetFormat"); Assert.AreEqual(-701544240, x509.GetHashCode(), "GetHashCode"); Assert.AreEqual("C=US, O=\"RSA Data Security, Inc.\", OU=Secure Server Certification Authority", x509.GetIssuerName(), "GetIssuerName"); Assert.AreEqual("1.2.840.113549.1.1.1", x509.GetKeyAlgorithm(), "GetKeyAlgorithm"); byte[] keyparams = { 0x05, 0x00 }; Assert.AreEqual(keyparams, x509.GetKeyAlgorithmParameters(), "GetKeyAlgorithmParameters"); Assert.AreEqual("0500", x509.GetKeyAlgorithmParametersString(), "GetKeyAlgorithmParametersString"); Assert.AreEqual("C=US, S=California, O=CommerceNet, OU=Server Certification Authority", x509.GetName(), "GetName"); byte[] pubkey = { 0x30, 0x5C, 0x02, 0x55, 0x2D, 0x58, 0xE9, 0xBF, 0xF0, 0x31, 0xCD, 0x79, 0x06, 0x50, 0x5A, 0xD5, 0x9E, 0x0E, 0x2C, 0xE6, 0xC2, 0xF7, 0xF9, 0xD2, 0xCE, 0x55, 0x64, 0x85, 0xB1, 0x90, 0x9A, 0x92, 0xB3, 0x36, 0xC1, 0xBC, 0xEA, 0xC8, 0x23, 0xB7, 0xAB, 0x3A, 0xA7, 0x64, 0x63, 0x77, 0x5F, 0x84, 0x22, 0x8E, 0xE5, 0xB6, 0x45, 0xDD, 0x46, 0xAE, 0x0A, 0xDD, 0x00, 0xC2, 0x1F, 0xBA, 0xD9, 0xAD, 0xC0, 0x75, 0x62, 0xF8, 0x95, 0x82, 0xA2, 0x80, 0xB1, 0x82, 0x69, 0xFA, 0xE1, 0xAF, 0x7F, 0xBC, 0x7D, 0xE2, 0x7C, 0x76, 0xD5, 0xBC, 0x2A, 0x80, 0xFB, 0x02, 0x03, 0x01, 0x00, 0x01 }; Assert.AreEqual(pubkey, x509.GetPublicKey(), "GetPublicKey"); Assert.AreEqual("305C02552D58E9BFF031CD7906505AD59E0E2CE6C2F7F9D2CE556485B1909A92B336C1BCEAC823B7AB3AA76463775F84228EE5B645DD46AE0ADD00C21FBAD9ADC07562F89582A280B18269FAE1AF7FBC7DE27C76D5BC2A80FB0203010001", x509.GetPublicKeyString(), "GetPublicKeyString"); Assert.AreEqual(cert, x509.GetRawCertData(), "GetRawCertData"); Assert.IsNotNull(x509.GetRawCertDataString(), "GetRawCertDataString"); byte[] serial = { 0xE8, 0x06, 0x00, 0x72, 0x02 }; Assert.AreEqual(serial, x509.GetSerialNumber(), "GetSerialNumber"); Assert.AreEqual("02720006E8", x509.GetSerialNumberString(), "GetSerialNumberString"); Assert.IsNotNull(x509.ToString(true), "ToString"); }
private bool AllTrustingServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Debug.WriteLine("Accepting certificate with thumbprint " + BitConverter.ToString(certificate.GetCertHash())); // Looks good to me! return(true); }
public bool IsMatch(X509Certificate cert) { bool subjectMatches = Subject.Replace(" ", "").Equals(cert.Subject.Replace(" ", ""), StringComparison.InvariantCulture); bool issuerMatches = Issuer.Replace(" ", "").Equals(cert.Issuer.Replace(" ", ""), StringComparison.InvariantCulture); bool thumbprintMatches = Thumbprint == String.Join(" ", cert.GetCertHash().Select(h => h.ToString("x2"))); return(subjectMatches && issuerMatches && thumbprintMatches); }
private static string Fingerprint(X509Certificate certificate) { var data = certificate.GetCertHash(); using (var sha512 = SHA512.Create()) { return(sha512.ComputeHash(data).ToHexString("")); } }
public static void Main() { // The path to the certificate. string Certificate = "Certificate.cer"; // Load the certificate into an X509Certificate object. X509Certificate cert = X509Certificate.CreateFromCertFile(Certificate); // Get the value. byte[] results = cert.GetCertHash(); }
public CertificateValidator AcceptThisCertificate(X509Certificate certificate) { var serverHash = certificate.GetCertHash(); return(new CertificateValidator((s, c, ch, e) => { if (c == null || e == SslPolicyErrors.RemoteCertificateNotAvailable) { return false; } if (e == SslPolicyErrors.None) { return true; } return Compare(c.GetCertHash(), serverHash); })); }
public bool RemoteCertificateValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) { if (tlsSecInfo.ChainValidation) { X509Chain newChain = new X509Chain(); newChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; newChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; newChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; newChain.ChainPolicy.VerificationTime = DateTime.Now; newChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0); foreach (X509Certificate2 caCert in tlsSecInfo.CaCertificates) { newChain.ChainPolicy.ExtraStore.Add(caCert); } bool certificateStatus = newChain.Build(new X509Certificate2(cert.GetRawCertData())); if (certificateStatus == false) { return(false); } } if (tlsSecInfo.AllowOnlySpecificCertificates) { foreach (X509Certificate2 allowedCert in tlsSecInfo.AllowedCertificates) { if (AreByteArraysEqual(allowedCert.GetCertHash(), cert.GetCertHash())) { return(true); } } return(false); } return(true); } else { return(false); } }
private bool ValidateCertificateHttpHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (_cancellationToken.IsCancellationRequested) { return(false); } IsVerified = sslPolicyErrors == SslPolicyErrors.None; if (IsVerified) { return(true); } if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable)) { Log.WriteLine(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_NoBrokerCertificate); _console.WriteError(Resources.Error_NoBrokerCertificate.FormatInvariant(Name)); return(false); } lock (_verificationLock) { if (ConnectionInfo.IsUrlBased && ConnectionInfo.Uri.IsLoopback) { return(true); } if (_certificateValidationResult.HasValue) { return(_certificateValidationResult.Value); } Log.Write(LogVerbosity.Minimal, MessageCategory.General, Resources.Trace_SSLPolicyErrors.FormatInvariant(sslPolicyErrors)); var hashString = GetCertHashString(certificate.GetCertHash()); if (_certificateHash == null || !_certificateHash.EqualsOrdinal(hashString)) { Log.Write(LogVerbosity.Minimal, MessageCategory.Warning, Resources.Trace_UntrustedCertificate.FormatInvariant(certificate.Subject)); var message = Resources.CertificateSecurityWarning.FormatInvariant(ConnectionInfo.Uri.Host); _certificateValidationResult = _services.Security().ValidateX509Certificate(certificate, message); if (_certificateValidationResult.Value) { _certificateHash = hashString; } } return(_certificateValidationResult ?? false); } }
bool RemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { var hash = Encoding.ToHexString(certificate.GetCertHash()); EB.Debug.Log("checking cert hash: " + hash); foreach (var cert in _validCerts) { if (hash == cert) { return(true); } } #if !DEBUG EB.Debug.LogError("Cant find certificate in pinned certificate!"); #else EB.Debug.LogWarning("RemoteCertificateValidationCallback: bad_certificate. it's harmless if proxy used"); #endif return(false); }
/// <summary> /// Validates the given remote certificate to determine if the host is trusted. /// </summary> /// <param name="remoteCertificate">Certificate of the remote host.</param> /// <returns>True if the remote certificate is trusted; false otherwise.</returns> public bool ValidateRemoteCertificate(X509Certificate remoteCertificate) { byte[] hash = remoteCertificate.GetCertHash(); byte[] key = remoteCertificate.GetPublicKey(); bool hashMatch, keyMatch; foreach (X509Certificate certificate in TrustedCertificates) { hashMatch = hash.SequenceEqual(certificate.GetCertHash()); keyMatch = hashMatch && key.SequenceEqual(certificate.GetPublicKey()); if (keyMatch) { return(true); } } m_reasonForFailure = "No matching certificate found in the list of trusted certificates."; return(false); }
public void Remove(X509Certificate certificate) { byte[] certHash = certificate.GetCertHash(); IntPtr num = IntPtr.Zero; byte[] pvData = new byte[20]; while ((num = NativeMethods.CertEnumCertificatesInStore(this.mStoreHandle, num)) != IntPtr.Zero) { uint length = (uint)pvData.Length; NativeMethods.CertGetCertificateContextProperty(num, 3U, pvData, ref length); int index = 0; while ((long)index < (long)length && (int)certHash[index] == (int)pvData[index]) { ++index; } if ((long)index == (long)length) { NativeMethods.CertDeleteCertificateFromStore(NativeMethods.CertDuplicateCertificateContext(num)); } } }
private IEnumerator request() { OnStart(); WWW www = new WWW(getUrl()); ServicePoint sp = ServicePointManager.FindServicePoint(getUrl(), null); if (sp != null) { Debug.Log("Located service point."); X509Certificate certificate = sp.Certificate; if (certificate != null) { Debug.Log("Certificate hash: " + certificate.GetCertHash()); } } else { Debug.Log("None found"); } yield return(www); if (!www.isDone) { yield return(www); } HTTPBaseResponseImpl response = new HTTPBaseResponseImpl(this); if (!string.IsNullOrEmpty(www.error)) { response.setStatusCode(parseStatusFromMessage(www.error)); OnError(response, new HTTPException(www.error)); } else { response.setStatusCode(200); response.setDocument(new HTTPBaseDocumentImpl(www.bytes)); OnSuccess(response); } OnComplete(); }
private static void UploadSaaSCertificate(X509Store store2, X509Certificate cert) { using (var serverManager = new ServerManager()) { var siteName = cert.Issuer.Contains("CN=") ? cert.Issuer.Substring(cert.Issuer.IndexOf("CN=", StringComparison.Ordinal) + 3) : CoreContext.TenantManager.GetCurrentTenant().MappedDomain; var newbindinginformation = "*:443:" + siteName; var site = serverManager.Sites[siteName]; if (site == null) { site = serverManager.Sites.Add(siteName, "http", "*:80:" + siteName, HostingEnvironment.ApplicationPhysicalPath); site.Applications[0].ApplicationPoolName = serverManager.Sites[HostingEnvironment.SiteName].Applications[0].ApplicationPoolName; } AddHttpsBinding(site, newbindinginformation, cert.GetCertHash(), store2.Name); serverManager.CommitChanges(); } }
/// <summary> /// Searches the list of trusted certificates for a certificate that matches the given remote certificate. /// </summary> /// <param name="remoteCertificate">Remote certificate to search for.</param> /// <returns>Trusted X509 certificate, if found; otherwise, <c>null</c>.</returns> public X509Certificate?GetTrustedCertificate(X509Certificate remoteCertificate) { if (remoteCertificate is null) { return(null); } byte[] hash = remoteCertificate.GetCertHash(); byte[] key = remoteCertificate.GetPublicKey(); foreach (X509Certificate trustedCertificate in m_trustedCertificates.Keys) { bool hashMatch = hash.SequenceEqual(trustedCertificate.GetCertHash()); bool keyMatch = hashMatch && key.SequenceEqual(trustedCertificate.GetPublicKey()); if (keyMatch) { return(trustedCertificate); } } return(null); }
internal static Tuple <bool, string> GetCertificateHash() { bool isSuccessful = false; string messageResult = string.Empty; string certificatePath = Utilities.LoadCertificateFromFile(); X509Certificate certificate = Utilities.CreateCertificateFromFile(certificatePath); byte[] results = certificate.GetCertHash(); if (results != null) { isSuccessful = true; messageResult = "The raw certificate hash value was retrieved"; } foreach (byte b in results) { Console.Write(b); } return(new Tuple <bool, string>(isSuccessful, messageResult)); }
/// <summary> /// Searches the list of trusted certificates for a certificate that matches the given remote certificate. /// </summary> /// <param name="remoteCertificate">Remote certificate to search for.</param> /// <returns>Trusted X509 certificate, if found; otherwise, <c>null</c>.</returns> public X509Certificate GetTrustedCertificate(X509Certificate remoteCertificate) { byte[] hash, key; bool hashMatch, keyMatch; if ((object)remoteCertificate != null) { hash = remoteCertificate.GetCertHash(); key = remoteCertificate.GetPublicKey(); foreach (X509Certificate trustedCertificate in m_trustedCertificates.Keys) { hashMatch = hash.SequenceEqual(trustedCertificate.GetCertHash()); keyMatch = hashMatch && key.SequenceEqual(trustedCertificate.GetPublicKey()); if (keyMatch) { return(trustedCertificate); } } } return(null); }
public static bool FindCertificate(X509Certificate2Collection store, X509Certificate certificate) { var matches = store.Find(X509FindType.FindByThumbprint, string.Concat(certificate.GetCertHash().Select(b => b.ToString("X2"))), false); return(matches.Count > 0); }
private static string GetCertHashString(this X509Certificate cert) { return(ByteArrayToString(cert.GetCertHash())); }
public bool RemoteCertificateValidationCallback(object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors) { Assert.Equal(ServerCertificate.GetCertHash(), certificate?.GetCertHash()); return(true); }
// https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/x509certificates/x509certificate.cs,318 internal static string GetCertHashString(this X509Certificate certificate) { var bytes = certificate.GetCertHash(); return(EncodeHexString(bytes)); }