RSA Exception {“Bad Length。\ r \ n”} Noi Matter我的密钥大小是多少

我在行上收到运行时错误{“Bad Length。\ r \ n”}:

return rsa.Encrypt(bytes, true); 

这是在function:

  private static byte[] Encrypt(byte[] bytes) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { string test = Properties.Settings.Default.PublicKeyXml; rsa.FromXmlString("mfXS3Na0XfkjhpjS3sL5XcC9o+j6KXi1LB9yBc4SsTMo1Yk/pFsXr74gNj4aRxKB45+hZH/lSo933NCDEh25du1iMsaH4TGQNkCqi+HDLQjOrdXMMNmaQrLXGlY7UCCfFUnkEUxX51AlyVLzqLycaAt6zm5ljnDXojMC7JoCrTM=AQAB"); return rsa.Encrypt(bytes, true); } } 

我使用的密钥大小为8192:

 CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_ENC_RSA_KEY"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(8192, cspParams); string keyXml = rsaKey.ToXmlString(true); 

XML文件很小。 根据运行时的长度,它只有225个字节:

 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); 

根据这篇SOpost ,密钥大小为4096字节就足够了:

 ((KeySize - 384) / 8) + 7 

我必须使用什么密钥大小? 为什么8096字节不起作用? 我怎样才能让它发挥作用?

这是我在尝试一个或另一个post的代码时发现的相同错误。

改变这个

byte [] fileBytes = Encoding.Default.GetBytes(xmlDoc.OuterXml);

对此

byte [] fileBytes = Encoding.Default.GetBytes(xmlDoc.ToString());

我还建议您将编码从默认值更改为Encoding.ASCII或更多定义的内容。 将它转换为要保存的字符串然后再返回到要解密的字节数组会更容易。