How to load another's certificate to my local certificate store?

I have a certificate (.pem file) that is distributed by another service vendor. I downloaded the certificate from the vendor and saved it to my local drive. In my WCF client, I am trying to load this certificate from the local drive and it is giving me an error “The private key is not present in the X.509 certificate” when communicating with the service. I was told that I need to load this certificate to my local certificate store to resolve this error. Can anyone provide some directions? Thanks!

I have the below attached function to load certificate from the path specified in the file parameter.

In the WCF Client, I have

public X509Certificate Certificate { get; set; }

    ClientCredentials loginCredentials = new ClientCredentials();
    loginCredentials.UserName.UserName = this.UserId;
    loginCredentials.UserName.Password = this.Password;
    loginCredentials.ClientCertificate.Certificate = new X509Certificate2(this.Certificate);
public static X509Certificate LoadCertificate(string file)
    {
        try
        {
            return X509Certificate.CreateFromCertFile(file);
        }
        catch (System.Security.Cryptography.CryptographicException)
        {
            string filestr = File.ReadAllText(file);

            StringBuilder sb = new StringBuilder(filestr.Remove(0, filestr.IndexOf("-----BEGIN CERTIFICATE-----")));

            sb.Replace("-----BEGIN CERTIFICATE-----", "");
            sb.Replace("-----END CERTIFICATE-----", "");
            //Decode 
            try
            {        //see if the file is a valid Base64 encoded cert
                byte[] certBytes = Convert.FromBase64String(sb.ToString());

                return new X509Certificate(certBytes);
            }
            catch (System.FormatException)
            {
                throw;
            }
        }
    }

Open in new window

ipjyoAsked:
Who is Participating?
 
NavneetSoftware EngineerCommented:
0
 
OklahomaDaveCommented:
Hmmm....

Been a while since I dealt with certs and keys, but I believe the .pem file is typically the container for the private key; the cert is usually in a .cer file. As a result, creating the cert from the .pem is probably not going to work. I'd take a look at that angle first. In fact,  you might look into using the openssl tool to create a cert including the private key from the .cer and .pem files, then import the result.

0
 
ipjyoAuthor Commented:
Thank you both. I will look into your comments and see if I can get it working.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.