RSA C#ImportParameters"参数不正确"例外

时间:2017-05-03 12:48:25

标签: c# exception encryption cryptography rsa

我有一个服务器(python)和一个客户端(c#),我需要使用assymetric rsa加密技术暂时在它们之间进行通信。 当我作为客户端连接到服务器时,我将他的公钥发给他,然后他发给我了他的。我在服务器上使用rsa库,然后我到达那里服务器的公钥参数{n,e}我发送它们并在它们之间留一个空格接收它们。我将它们分开并使用此函数将模数转换为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);
        ...
    }
    ...
}

在ImportParameters行上抛出一个异常:"参数不正确" 。 怎么了?

1 个答案:

答案 0 :(得分:0)

BigInteger.ToByteArray()以little-endian顺序导出数据。 RSAParameters希望以big-endian顺序获取所有数据。

还有一个问题是模数值应该设置其最高有效位,因此BigInteger.ToByteArray()需要添加填充字节以防止数字被重新解释为负数,因此您需要关闭它。

假设你的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;
相关问题