简体   繁体   中英

X509Certificate2 in .NET Core 3.1 vs .Net Framework 4.7

I am porting code from a .NET Framework 4.7.2 project into a new project which is.Net Core 3.1. The code needs to pull data from an https endpoint using an X509Certificate:

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        var cert = new X509Certificate2( X509Certificate.CreateFromCertFile("myCert.cer"));
        req.ClientCertificates.Add(cert);
        req.Timeout = timeoutMs;
        WebResponse response = req.GetResponse();
        Stream responseStream = response.GetResponseStream();

This works fine in the.Net Framework project, but the same code copied into a.Net Core 3.1 project returns 403. Both are simple console applications. I'm using the full path to the.cer file and I have confirmed it loads the certificate data successfully.

Are there any known issues with X509Certificate in.Net Core 3.1? Or something that must be done differently? Most information on the web uses a cert file and a key file, but I only have is a.cer file. Is that an issue (obviously I'm not super familiar with certificates)?

The line:

var cert = new X509Certificate2( X509Certificate.CreateFromCertFile("myCert.cer"));

assumes that you attach only public certificate, without associated private key. This is insufficient for client certificate authentication. The certificate must have X509Certificate2.HasPrivateKey property to return true (eg import from PFX, or personal certificate store). This isn't going to work in any of .NET versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM