1
votes

I'm having some trouble importing and accessing a private key with the ASPNET user. I know that when one imports a private key (.pfx file) manually, in windows, you get an option to mark the key as exportable. Now, as far as I can tell, this is needed in order to retrieve that private key later on.

My problem comes in that I'm importing the private key in code, as the ASPNET user, and there doesn't seem to be a way to mark it as exportable, in the way that the windows certificate import wizard does. To clarify, the import works just fine, but when I access the details on the now-imported certificate, there is no private key data.

This is the code I'm using to import the certificate, once I have already opened the .pfx file, with the correct password.

public void ImportCertificate(X509Certificate2 cert, StoreName name, StoreLocation loc)
{
    X509Store certStore = new X509Store(name, loc);
    StorePermission permission = new StorePermission(PermissionState.Unrestricted);
    permission.Flags = StorePermissionFlags.AddToStore;
    permission.Assert();
    certStore.Open(OpenFlags.ReadWrite);
    certStore.Add(cert);
    certStore.Close();
}

Am I mucking up the permissions or the way I import this private key? Or am I going about this the wrong way entirely?

1

1 Answers

1
votes

I believe you need to set the X509KeyStorageFlags.Exportable flag when you import the certificate. You don't show that code, but there is an overload of the Import method with this signature:

public override void Import(string fileName, string password, 
                            X509KeyStorageFlags keyStorageFlags);

or this one:

public override void Import(byte[] rawData, string password, 
                            X509KeyStorageFlags keyStorageFlags);

Which will let you set it before you import. Otherwise, everything looks good!

Richard