[Mono-devel-list] Serialization of RSAParameters
Christian Rudh
christian at rudh.se
Tue Oct 21 10:12:24 EDT 2003
Hi
I am trying to serialize the RSA-keys into a bytestream so I can write
them to disk (and a few other things). I'm able now to serialize them
and then use it in encryption, but it doesn't work in decryption. I
export to RSAParameters using the true-flag so I get everything, but
when I deserialize it seems as if I only get the parts of the public key
back? That's why encryption works fine, but not decryption.
I have compiled the following sources from various places and with my
own code. It crashes when (in the end) it uses RSA2.decrypt. But if you
comment out where it gets the RSAParameters from the deserialization
(----2----) and instead import from the original RSA (-----1----) it
works fine.
So are there any problems with serialization of RSAParameters or am I
missing something?
Regards,
Christian Rudh
//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter = new UnicodeEncoding();
//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt = ByteConverter.GetBytes("Text to Encrypt");
byte[] encryptedData;
byte[] decryptedData;
//Create a new pair of keys
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1024);
//Export the public key
RSAParameters RSAP = RSA.ExportParameters(true);
//Serialize the public key
MemoryStream ms = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(ms, RSAP);
byte[] keyHolder = ms.ToArray();
ms.Close();
//Deserialize the public key and store it in newRSAP
MemoryStream ms2 = new MemoryStream(keyHolder);
BinaryFormatter b2 = new BinaryFormatter();
RSAParameters newRSAP = (RSAParameters)b2.Deserialize(ms2);
ms2.Close();
//Encrypt the data using newRSAP which holds the RSAParameters
RSACryptoServiceProvider RSA1 = new RSACryptoServiceProvider();
RSA1.ImportParameters(newRSAP);
encryptedData = RSA1.Encrypt(dataToEncrypt, false);
//Decrypt the data using newRSAP which holds the RSAParameters
RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider();
//-------------1-------------
//RSA2.ImportParameters(RSA.ExportParameters(true));
//-------------2-------------
RSA2.ImportParameters(newRSAP);
decryptedData = RSA2.Decrypt(encryptedData, false);
//Display the decrypted plaintext to the console.
Console.WriteLine("Decrypted plaintext: {0}",
ByteConverter.GetString(decryptedData));
More information about the Mono-devel-list
mailing list