How can I access a private key with the ASPNET user account?

By : Gabriel

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;

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

By : Gabriel


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!


The keyword is final as you thought. See and Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.

  TSomeClass = class
    procedure SomeVirtualMethod; virtual;

  TOtherClass = class(TSomeClass)
    procedure SomeVirtualMethod; override; final;

You can set the Transaction property of the DataContext to make it participate in a transaction you already have.

By : DamienG

This video can help you solving your question :)
By: admin