0

I try to move a request with certificate from an old system made with NodeJS to a new system using .NET 8.0.

Running the .NET code, however, I always get the following error:

The SSL connection could not be established

Here is my NodeJS code:

const Q = require('q');
return Q.Promise((resolve, reject) => {
    const options = {
      method: 'POST',
      url: ConfigPayment.kmobile.url + '/targetUrl',
      headers: {
        'cache-control': 'no-cache',
        'content-type': 'text/xml;charset=UTF-8',
        'SoapAction': '',
      },
      agentOptions: {
        ca: [
          fs.readFileSync('file1.pem'),
          fs.readFileSync('file2.pem'),
          fs.readFileSync('file3.crt'),
          fs.readFileSync('file4.crt'),
          fs.readFileSync('file5.crt'),
          fs.readFileSync('file6.crt')
        ]
      },
      strictSSL: true,
      body: xml
    }

This is my new .NET 8.0 code:

var _trustedCertificates = new X509Certificate2Collection();

var filePathList = new string[]
{
    Path.Combine(this.ProjectRootPath, "file1.pem"),
    Path.Combine(this.ProjectRootPath, "file2.pem"),
    Path.Combine(this.ProjectRootPath, "file3.crt"),
    Path.Combine(this.ProjectRootPath, "file4.crt"),
    Path.Combine(this.ProjectRootPath, "file5.crt"),
    Path.Combine(this.ProjectRootPath, "file6.crt")
};

foreach (var path in filePathList)
{
    if (File.Exists(path))
    {
        logger.LogDebug($"Files exists {path}");
        var cert = new X509Certificate2(path);
        _trustedCertificates.Add(cert);
    }
}

var handler = new HttpClientHandler()
{
    SslProtocols = SslProtocols.Tls12,
    ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) =>
    {
        logger.LogDebug("ServerCertificateCustomValidationCallback called. Errors: {Errors}", errors);

        if (errors == SslPolicyErrors.None)
            return true;

        using var chain2 = new X509Chain();
        chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
        chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

        foreach (var c in _trustedCertificates)
        {
            chain2.ChainPolicy.ExtraStore.Add(c);
        }

        var serverCert = cert as X509Certificate2 ?? new X509Certificate2(cert);
        var isValid = chain2.Build(serverCert);

        foreach (var status in chain2.ChainStatus)
        {
            logger.LogDebug("Chain error: {Status} - {Info}", status.Status, status.StatusInformation);
        }

        return isValid;
    }
};

this.httpClient = new HttpClient(handler);
this.httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
this.httpClient.DefaultRequestHeaders.Add("SoapAction", "");
this.httpClient.BaseAddress = new Uri("https://targetUrl.com/");

Does anyone know what I am doing wrong?

1
  • Suggest you use ChatGPT, there's a few problems, the key being X509Certificate2(string path) expects DER / PFX; it often does not parse PEM. Commented Nov 24 at 3:26

1 Answer 1

0

Certificate Format: In your NodeJS code, you're using PEM files. However, the error may come from the fact that you are attempting to load PEM files directly with X509Certificate2 in .NET. The constructor X509Certificate2(string path) expects the certificate file to be in a different format (like PFX or DER). It generally does not handle PEM files properly. You might need to convert your PEM certificates to PFX format. You can use OpenSSL for this if needed.

For example:

openssl pkcs12 -export -out certificate.pfx -inkey privatekey.key -in certificate.crt
New contributor
Philip is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.