I am trying to encrypt and decrypt data using RSA. Ultimately, I need to be able to place an existing public key into the RSACryptoServiceProvider and encrypt using that, but for now, I'd settle for any success at all.
I have this simple test. I assure you that the LoadFromFile() and SaveToFile() methods are working, and the raw data is a valid byte array with the correct data in it. The line (as indicated below) which encrypts data throws an exception, stating "unspecified error".
I get this behavior on two machines (Windows XP Pro SP2 and Windows XP Home SP2), but not on a third machine (Windows 2000 Pro). What must I do to get it working?
Any ideas are welcome.
private void button2_Click(object sender, EventArgs e)
{
// Load the raw data to be encrypted.
byte[] lOriginal = LoadFromFile(@"c:\firstfile.txt");
// Create an encryptor with new keys
RSACryptoServiceProvider lRSA = new RSACryptoServiceProvider();
// Encrypt the raw data.
//This line throws CryptographicException: "Unspecified Error"
byte[] lEncrypted = lRSA.Encrypt(lOriginal, false);
// Store the encrypted data.
SaveTofile(@"c:\encrypted.txt", lEncrypted);
}
Loading
JamesPosted Sep 2, 2009, 2:03 PM
spgilmorePosted Mar 3, 2006, 1:53 PM
In the 2.0 framework, I get UNSPECIFIED ERROR if I use the default key.
In the 2.0 framework, I get "Key is not valid for use in specified state" if I use an imported key.
In the 1.1 framework, I get "Bad Length".
The problem is explained (briefly) here.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncapi/html/encryptdecrypt2a.asp
Asymmetric encryption methods have a limit on the amount of data that they can encrypt. This limit is just under the modulus size of the asymmetric key. By default, the key size for the RSACryptoServiceProvider on my 2.0 application is 1024 bits / 128 bytes. I cannot encrypt 128 bytes. I can encrypt 100 bytes. The cutoff is somewhere between the two.
When I encrypt 16 bytes (128 bits, the size of the symmetric key I need to encrypt), everything seems to work fine (so far).
I've been reading document after document after document about these classes and encryption in general. Why did it take me a week to find someone who could tell me that this was a property of asymmetric encryption? How frustrating! The CLR 2.0 error messages were no help, either.