CryptographicException was unhandled: System cannot find the specified file

For those of you who received the Cryptographic Exception when attempting to import a X509Certificate2 using the Import method, I found that using the Enum option for MachineKeySet bypassed the need for creating a userContext in IIS, and thus easier to implement.

X509Certificate2 cert = new X509Certificate2();
cert.Import(certificateFilePath, certPasshrase, 
X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

Did you set the following on the application pool in IIS?

  1. Go to IIS Manager
  2. Go to the application pool instance
  3. Click advanced settings
  4. Under Process model, set Load User Profile to true

See this stack question for further reading: What exactly happens when I set LoadUserProfile of IIS pool?


Because this question has a high search ranking I would like to present a way to present X509Certificate2 with an absolute path (which it only accepts) to a relatively located pxf key file in an ASP.net application.

    string path = HttpContext.Current.Server.MapPath("~") + "..\keys\relative_key.pfx";

    X509Certificate2 cert = new X509Certificate2(path, "", X509KeyStorageFlags.DefaultKeySet);

By passing CspParameters with flag csdMachineKeyKeyStore IIS can bypass the restriction that throws the Exception.

CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant();
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cspParams);

I found the solution here.