Error setting X509Certificate2 PrivateKey

前端 未结 2 1846
日久生厌
日久生厌 2020-12-18 00:08

I am migrating a .NetFramework 4.6.1 library to a .NetCore 2.2. But i am unable to set x509certificate.PrivateKey as shown below.

I have read that may be due to the

2条回答
  •  一个人的身影
    2020-12-18 00:43

    As LexLi said, setting the private key on an existing certificate is not possible by design in .net core.

    Following what is described here, what you can do is use the method RSACertificateExtensions.CopyWithPrivateKey.

    Instead of

    x509certificate.PrivateKey = DotNetUtilities.ToRSA(rsaParams);
    

    you could have

    var rsa = DotNetUtilities.ToRSA(rsaParams);
    var cert = x509certificate.CopyWithPrivateKey(rsa);
    return cert;
    

    To get access to the "CopyWithPrivateKey" extension method, add this using :

    using System.Security.Cryptography.X509Certificates; /* for getting access to extension methods in RSACertificateExtensions */
    

    "(CopyWithPrivateKey) Combines a private key with the public key of an RSA certificate to generate a new RSA certificate."

    https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.rsacertificateextensions.copywithprivatekey?view=netcore-3.0

提交回复
热议问题