Verifying CAcert Certificate in C #

I am currently creating a C # program that will extract some https data from my server. The server in question uses the CAcert certificate ( http://www.cacert.org/ ), and I need a way to verify the server certificate (checking the topic and that it is signed with the cacert root certificate).

I would like to do this without having to import CAcert root as a trusted certificate authority into the Windows certificate store, someone might not like this, and AFAIK, which requires an administrator.

I am currently using the TcpClient and SslStream classes, not the WebRequest / WebResponse classes, because one day I can switch from using HTTP to using my own protocol, but if the task is simpler with the help of * request classes, I will consider using them.

+3
source share
1 answer

First you want to use the overloaded SslStream constructor:

SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback);

Then the RemoteCertificateValidationCallback method looks something like this:

public bool IsValid(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
     ... you logic here ...
}

You just need to go through the chain and look at the certificates until you find the one that you are ready to accept by checking the public key:

        foreach(X509ChainElement e in chain.ChainElements)
            if( e.Certificate.Subject == "CN=XXX.xx" && e.Certificate.GetPublicKeyString() == "expected public key" )
                return true;
+1
source

Source: https://habr.com/ru/post/1718742/


All Articles