Opps!!! System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

If you are creating the cryptographic keys on the user's profile directory you may get a cryptographic exception saying: "CryptographicException: The system cannot find the file specified".

The stack trace looks like:

System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)

at System.Security.Cryptography.Utils.GetKeyPairHelper(...)

at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()

On most cases the reason for this exception is that RSACryptoServiceProvider calls into CryptAcquireContext.

CryptAcquireContext will create a file for storing keys in the user’s profile. If the user’s profile is not loaded, CryptAcquireContext fails with ERROR_FILE_NOT_FOUND.

What you can do is; you instantiate the RSACryptoServiceProvider class in the following way:

   1: CspParameters cspParams = new CspParameters(); 
   3: cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
   5: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams);

Doing this the cryptographic keys will be created in the MachineKeys folder, which every user has access. However the user that created this key has the only access to this file, unless this user gives others explicit access to this crypto key.

Calling RSACryptoServiceProvider with the CspProviderFlags.UseMachineKeyStore flag is same as calling CryptAcquireContext with the CRYPT_MACHINE_KEYSET flag.

For more information please visit the section "Using the CRYPT_MACHINE_KEYSET flag" at http://support.microsoft.com/?id=238187.

For a greater and detailed reference you can see the well-known blog from "Decrypt my World" by Alex at the link http://blogs.msdn.com/alejacma/archive/2007/12/03/rsacryptoserviceprovider-fails-when-used-with-asp-net.aspx.


Shamik Misra

Windows SDK

Comments (0)

Skip to main content