I am getting the runtime error {"Bad Length.\r\n"} on the line:
return rsa.Encrypt(bytes, true);
This is in the function:
private static byte[] Encrypt(byte[] bytes)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
string test = Properties.Settings.Default.PublicKeyXml;
rsa.FromXmlString("<RSAKeyValue><Modulus>mfXS3Na0XfkjhpjS3sL5XcC9o+j6KXi1LB9yBc4SsTMo1Yk/pFsXr74gNj4aRxKB45+hZH/lSo933NCDEh25du1iMsaH4TGQNkCqi+HDLQjOrdXMMNmaQrLXGlY7UCCfFUnkEUxX51AlyVLzqLycaAt6zm5ljnDXojMC7JoCrTM=</Modulus><Exponent>AQAB</Exponent></RSAKeyFile>");
return rsa.Encrypt(bytes, true);
}
}
I am using a key size of 8192:
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_ENC_RSA_KEY";
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(8192, cspParams);
string keyXml = rsaKey.ToXmlString(true);
The XML file is small. According to the length at runtime, it is only 225 bytes:
string fileName = System.IO.Path.Combine(Application.StartupPath, "alphaService.xml");
XDocument doc = new XDocument();
XElement xml = new XElement("Info",
new XElement("DatabaseServerName", txtServerName.Text),
new XElement("DatabaseUserName", txtDatabaseUserName.Text),
new XElement("DatabasePassword", txtDatabasePassword.Text),
new XElement("ServiceAccount", txtAccount.Text),
new XElement("ServicePassword", txtServicePassword.Text),
new XElement("RegistrationCode", txtRegistrationCode.Text));
doc.Add(xml);
doc.Save(fileName);
// Convert XML doc to byte stream
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
byte[] fileBytes = Encoding.Default.GetBytes(xmlDoc.OuterXml);
int fileBytesLength = fileBytes.Length;
Encrypt(fileBytes);
According to this SO post, a key size of 4096 bytes should have been sufficient:
((KeySize - 384) / 8) + 7
What key size do I have to use? Why doesn't 8096 bytes work? How can I get this to work?