C# – How to get private key from PKCS#12 (.p12) file using C#

cencryptionpkcs#12x509certificate2

Im trying to sign some data using PKCS#12 certificate ,however i have problem with obtaining private key from PKCS#12 (.p12) file.

    public byte[] sign(string text)
    {
        string password = "1111";
        X509Certificate2 cert = new X509Certificate2("c:\\certificate.p12",password);
        byte[] certData = cert.Export(X509ContentType.Pfx,password);

        X509Certificate2 newCert = new X509Certificate2(certData, password);
        RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)newCert.PrivateKey;

        SHA1Managed sha1 = new SHA1Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] data = encoding.GetBytes(text);
        byte[] hash = sha1.ComputeHash(data);
        return crypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
    }

The problem is that newCert.PrivateKey is null but if i am using .pfx certicitae in similar way it works.

    public byte[] sign(string text)
    {
        string password = "1234";
        X509Certificate2 cert = new X509Certificate2("c:\\certificate.pfx", password);
        RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;
        SHA1Managed sha1 = new SHA1Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] data = encoding.GetBytes(text);
        byte[] hash = sha1.ComputeHash(data);
        return crypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
    }

So the question is how to get that private key from .p12 file ?

Best Answer

I had a similar problem which I posted here, although it is not the same thing for you, the problem may be also permissions.
My suggestions are, first, you have to make sure (which I suppose you already did) that the private key is exportable and you have permissions to the file.
Next, try exporting the content type as X509ContentType.Pkcs12 instead of X509ContentType.Pfx
Finally, if it is possible, why don't you try importing it to the certstore. I believe that's more secure. The steps are in the link above.