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

By : Gabriel
Source: Stackoverflow.com
Question!

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?

By : Gabriel


Answers

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



The keyword is final as you thought. See http://dn.codegear.com/article/34324 and http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.

type
  TSomeClass = class
  protected
    procedure SomeVirtualMethod; virtual;
  end;

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


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