Hi
I'm trying to encrypt and decrypt some data with RSA. I'm having problems in creating my own public and private keys and use them. This is what I did so far
I create an RSACryptoServiceProvider and a CspParameters because Im storing my keys into a key container:
CspParameters cp = new CspParameters();
cp.KeyContainerName = stContainerName;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, cp);
Then I retrieve the public RSA key with this. I use a XmlDocument to handle the RSA Key Data
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = rsa.ToXmlString(true);
XmlNodeList xmlPublicModulus = xmlDoc.GetElementsByTagName("Modulus");
XmlNodeList xmlPublicExp = xmlDoc.GetElementsByTagName("Exponent");
After that i try to encrypt and decrypt some data. I declare a new RSACryptoServiceProvider which will have the public key info.
string stDataToEncrypt = "Hey there";
string stDeencryptedData;
byte[] btEncryptedData;
byte[] publicModulus = Encoding.ASCII.GetBytes(xmlPublicModulus[0].InnerText);
byte[] publicExp = Encoding.ASCII.GetBytes(xmlPublicExp[0].InnerText);
RSAParameters publicRSAKeyInfo = new RSAParameters(); publicRSAKeyInfo.Modulus = publicModulus;
publicRSAKeyInfo.Exponent = publicExp;
RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider(2048);
rsaPublic.ImportParameters(publicRSAKeyInfo);
btEncryptedData= rsa.Encrypt(Encoding.ASCII.GetBytes(stDataToEncrypt ),false);
stDeencryptedData= Encoding.ASCII.GetString(rsaPublic.Decrypt(btDatoEncriptado,false));
Console.WriteLine("datoDesencriptado: " + datoDesencriptado);
I got an exception:
incorrect key. Cheking the parameters of the rsaPublic object, the KeyLenght property is 2752. This parameter in rsa object is 2048. This tells me that I am doing somethin wrong.
What I understand of RSACryptoServiceProvider object is that it creates a RSA Key pair. So if I want to give someone else the public key, and I want to encrypt or decrypt with the private key, this is what I have to do
Any help would be appreciated and excuse my english
Regards
Iván