Decryption Trouble

grip003

Well-known member
Joined
Sep 2, 2004
Messages
89
Location
North Carolina
I created an encryption class that has both an Encrypt and a Decrypt Function. They both work, except when I try to use the Decrypt function more than once in a row. Here is my decrypt function:
[CS]
public static byte[] RSADecrypt(byte[] DataToDecrypt,
string key_file)
{
// Decryption is done using the private key.
System.GC.Collect();
try
{
// Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new
RSACryptoServiceProvider();

// Import the RSA Key information, which only needs to
// include the public key information.
System.IO.FileStream reader = new System.IO.FileStream(
key_file, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.Xml.XmlTextReader xml_reader =
new System.Xml.XmlTextReader(reader);
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(xml_reader);
xml_reader.Close();
reader.Close();

RSA.FromXmlString(doc.InnerXml);

// By default this will create a 128 bit AES object
SymmetricAlgorithm sa = SymmetricAlgorithm.Create();

byte[] keyex = new byte[RSA.KeySize >> 3];
Buffer.BlockCopy(DataToDecrypt, 0, keyex, 0, keyex.Length);

RSAPKCS1KeyExchangeDeformatter def = new
RSAPKCS1KeyExchangeDeformatter(RSA);
byte[] key = def.DecryptKeyExchange(keyex);

byte[] iv = new byte[sa.IV.Length];
Buffer.BlockCopy(DataToDecrypt, keyex.Length, iv, 0, iv.Length);

ICryptoTransform ct = sa.CreateDecryptor(key, iv);
byte[] decrypt = ct.TransformFinalBlock(DataToDecrypt,
keyex.Length + iv.Length, DataToDecrypt.Length -
(keyex.Length + iv.Length));
return decrypt;
}
catch(Exception)
{
return null;
}
}
[/CS]

The second time I call this function, an exception is thrown on the following line:

byte[] key = def.DecryptKeyExchange(keyex);

Can anyone see a problem with this?
 
Last edited by a moderator:
For more information on the project I am working on, I am trying to encrypt and send a 500MB+ file and then decrypt it on the other end. It works fine if I load the entire file into a byte array, encrypt it, send it, receive it on the other end, load the encrypted file into a byte array, decrypt that into another byte array, and then write the new file. As you can imagine, this requires a great deal of memory, and this must work smoothly on machines with 256MB RAM machines.

Thanks in advance.
 
Hey PlausiblyDamp:

I tried writting a test program to reproduce the problem. It turns out, the way I am doing my file transfer is not correct and it is sending corrupted data, so when the client tries to descrypt the byte array, it fails (as it should). Thanks for your reply. It made me go back and try this.

-- PROBLEM SOLVED --
 
Back
Top