I have this function I am using to decrypt values that works fine on my dev machine. But when run in production on another server – gives this exact error message :
The system cannot find the file specified.
Here is the function:
public static string Decrypt(string stringToDecrypt, string key)
{
string result = null;
if (string.IsNullOrEmpty(stringToDecrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
}
try
{
System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
cspp.KeyContainerName = key;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None);
byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));
byte[] bytes = rsa.Decrypt(decryptByteArray, true);
result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
}
finally
{
// no need for further processing
}
return result;
}
Update
Guys, I originally went this route because after hours and hours of searching I got an answer on stackoverflow, that this method of encrypting / decrypting works purely on strings and no need to import / export keys.
So…. Now I am missing a key file? How is this possible I didn’t even create a key file.
If you need to copy the key from one machine to another you’re going to have to export it from the key container. We found that the
rsaCryptoServiceProvider.ImportCspBlobandExportCspBlobmethods work nicely for this; you get a single byte array which you can thenConvert.ToBase64StringandConvert.FromBase64String.Of course, it has to be an exportable key (or better yet, export only the public key which is the way PKC is meant to be done so one end has the private key and the other only the public key). A non-exportable key can only export its public key. Once you get the system working, you could create a new non-exportable key where you need the private key to reside, and export the public key to transfer it to whereever else needs to encrypt to that single recipient.
Also, you need to make sure to
Disposethe crypto provider when you’re done (apparentlyClear()isn’t good enough). It’s good to use ausingstatement to do this, if you’re using it in one local scope, or you can do it in yourfinallyblock. Note that it implementsIDisposableexplicitly, so you have to cast it toIDisposablesomewhat awkwardly to do it in a separate statement. Ausingstatement handles the casting itself, so it’s easier.