简体   繁体   中英

Problem in creating X509Certificate2 Public Key

I have an existing asp.net application where I use X509Certificate2 private and public keys. I am migrating it to netcoreapp2.1 (MVC). I'm facing a problem in creating a public key with X509Certificate2. I have the below code

  public string CertificatePublicKeyEncrypt(string stringToEncrypt, string certficatePath)
    {
        byte[] bytesToEncrypt = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

        X509Certificate2 cert = new X509Certificate2(certficatePath);

        RSACryptoServiceProvider rsa = cert.PublicKey.Key as RSACryptoServiceProvider;

        byte[] encryptedData = rsa.Encrypt(bytesToEncrypt, false);

        return Convert.ToBase64String(encryptedData);
    }

in asp.net application, cert.Handle value is "0x0792e4a0" and rsa is created successfully where the certificate location is determined using Server.MapPath function as shown:

   req.Sender = helper.CreateSenderObj(txt_sender_id.Text, txt_sender_name.Text, txt_efinance_password.Text, Server.MapPath("~/Certificates/InternetPaymentCrt.cer"));

Handle Value in asp.net Project but in our MVC project cert.Handle value is"0x0000019d814fffa0" and then rsa is null where the certificate location is determined using Hosting.ContentRootPath function as shown:

 var path = $"{Hosting.ContentRootPath}\\Certificates\\InternetPaymentCrt.cer"; 
         req.Sender = helper.CreateSenderObj(VM.SenderId, VM.SenderName, VM.SenderPassword,path);   

Handle Value in MCV Project and gives null exception error as follows System.NullReferenceException

In .NET Core applications, X509Certificate2.PublicKey and X509Certificate2.PrivateKey are literally obsolete. You have to use X509Certificate2 extension methods (corresponding method depending on key algorithm) to retrieve public and private keys.

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