example ejemplo c# xml encryption cryptography rsa

c# - ejemplo - Excepción de RSA{"Bad Length. / R / n"} Noi importa cuál es el tamaño de mi clave



rsacryptoserviceprovider c# example (1)

Obtengo el error de tiempo de ejecución {"Bad Length. / R / n"} en la línea:

return rsa.Encrypt(bytes, true);

Esto está en la función:

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

Estoy usando un tamaño de clave de 8192:

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

El archivo XML es pequeño. De acuerdo con la longitud en tiempo de ejecución, solo tiene 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);

De acuerdo con esta publicación SO , un tamaño de clave de 4096 bytes debería haber sido suficiente:

((KeySize - 384) / 8) + 7

¿Qué tamaño de clave debo usar? ¿Por qué no funcionan los 8096 bytes? ¿Cómo puedo hacer que esto funcione?


Este es el mismo error que encontré cuando probé el código de una de las otras publicaciones.

Cambia esto

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

a esto

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

También le sugiero que cambie su codificación de forma predeterminada a Encoding.ASCII o algo más definido. Será más fácil convertirlo en una cadena para guardar y luego volver a una matriz de bytes para descifrar.