[英]RSA C# ImportParameters “The parameter is incorrect” exception
I have a server (python) and a client (c#), I need to communicate between them temporarily using assymetric rsa cryptography. 我有一个服务器(python)和一个客户端(c#),我需要使用非对称rsa加密在它们之间进行临时通信。 When I connect to the server as the client, I send him my public key and he send me his.
当我以客户端身份连接到服务器时,我将其公钥发送给他,而他将其发送给我。 I use at the server the rsa library and I get there the server's public key parameters {n,e} I send those and receive them with a space between them.
我在服务器上使用rsa库,并在那里获得服务器的公共密钥参数{n,e},然后发送它们并在它们之间留一个空格。 I seperate them and convert the modulus into a BigInteger using this function:
我将它们分开,然后使用以下函数将模数转换为BigInteger:
public static BigInteger GetBigInteger(string number)
{
BigInteger bigNum = new BigInteger();
for (int i = number.Length; i > 0; i--)
{
bigNum *= 10;
bigNum += (int) number[number.Length-i];
}
return bigNum;
}
public static void Connect(IPAddress ipAddress, int port)
{
try
{
string[] message;
byte[] data = new byte[1024];
srvr.Receive(data); //Recieve the server's public key.
int length = int.Parse(Encoding.ASCII.GetString(data.Take(4).ToArray()));
message = Encoding.ASCII.GetString(data.Skip(4).Take(length).ToArray()).Split(' ') ;
RSACryptoServiceProvider RSAserver = new RSACryptoServiceProvider(1024);
RSAParameters par = new RSAParameters();
par.Modulus = GetBigInteger(message[0]).ToByteArray(); // Saves the server's public key.
par.Exponent = new byte[] { 1, 0, 1 }; // Saves the server's public key.
RSAserver.ImportParameters(par);
addresseeKey = RSAserver.ToXmlString(false);
...
}
...
}
An exception is thrown on the ImportParameters line that says: "The parameter is incorrect" . 在ImportParameters行上引发一个异常,该异常是:“参数不正确”。 What's wrong?
怎么了?
BigInteger.ToByteArray() exports the data in little-endian order. BigInteger.ToByteArray()以little-endian顺序导出数据。 RSAParameters wants all of its data in big-endian order.
RSAParameters希望其所有数据按大端顺序排列。
There's also an issue that the modulus value should have its most significant bit set, and therefore BigInteger.ToByteArray() needs to add in a padding byte to prevent the number from being reinterpreted as being negative, so you'll need to trim that off. 还有一个问题是,模数值应该设置其最高有效位,因此BigInteger.ToByteArray()需要添加一个填充字节,以防止将该数字重新解释为负数,因此您需要将其修剪掉。
Assuming that your python export is representing the modulus as a base-10 positive integer, your code will work (though BigInteger.Parse(string) would be more efficient) once you align the data properly. 假设您的python导出将模数表示为以10为底的正整数,则在正确对齐数据后,您的代码将起作用(尽管BigInteger.Parse(string)会更有效)。
byte[] tmp = GetBigInteger(message[0]).ToByteArray();
// Array.Resize (to a smaller number) trims off the high index values,
// so it's slightly more compact code to do this before the resize.
if (tmp.Length > 0 && tmp[tmp.Length-1] == 0)
Array.Resize(ref tmp, tmp.Length - 1);
Array.Reverse(tmp);
par.Modulus = tmp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.