使用C#中的小素数创建RSA密钥的问题

时间:2018-01-09 16:06:11

标签: c# encryption rsa

我想为Cicdia 2012 triange拼图编写基于.net的解决方案。 http://uncovering-cicada.wikia.com/wiki/The_Triangle_Puzzle

不幸的是,我一直收到错误"错误的数据"使用解决方案中的素数创建RSA密钥时:

 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSAParameters RSAKeyInfo = new RSAParameters();
        RSAKeyInfo.Exponent = BigInteger.Parse("65537").ToByteArray();
        RSAKeyInfo.P = BigInteger.Parse("99554414790940424414351515490472769096534141749790794321708050837").ToByteArray();
        RSAKeyInfo.Q = BigInteger.Parse("104593961812606247801193807142122161186583731774511103180935025763").ToByteArray();

        RSA.ImportParameters(RSAKeyInfo);

我理解不对称加密的基础知识,但我不明白为什么我不能用小素数创建自己的密钥...除非RSACryptoServiceProvider有某种"强度检查器"什么的。

1 个答案:

答案 0 :(得分:0)

以下是一些说明我的评论的示例代码。

    public static void Main(string[] args)
    {
        RSAParameters RSAKeyInfo = new RSAParameters();
        BigInteger p = BigInteger.Parse("99554414790940424414351515490472769096534141749790794321708050837");
        BigInteger q = BigInteger.Parse("104593961812606247801193807142122161186583731774511103180935025763");
        BigInteger modulus = p * q;
        BigInteger e = BigInteger.Parse("65537");
        BigInteger d = BigInteger.Parse("3198894071003639550820071093788580812499328515050919260466968671765341413862337988421155590663267840745788239672194253184260553629");
        BigInteger dp = d % (p - 1);
        BigInteger dq = d % (q - 1);
        BigInteger inverseQ = BigInteger.ModPow(q, p - 2, p);

        RSAKeyInfo.Modulus = SwapEndian(modulus.ToByteArray());
        RSAKeyInfo.Exponent = SwapEndian(e.ToByteArray());
        RSAKeyInfo.P = SwapEndian(p.ToByteArray());
        RSAKeyInfo.Q = SwapEndian(q.ToByteArray());
        RSAKeyInfo.D = SwapEndian(d.ToByteArray());
        RSAKeyInfo.DP = SwapEndian(dp.ToByteArray());
        RSAKeyInfo.DQ = SwapEndian(dq.ToByteArray());
        RSAKeyInfo.InverseQ = SwapEndian(inverseQ.ToByteArray());
        RSA rsa = RSA.Create();
        rsa.ImportParameters(RSAKeyInfo);
        Console.WriteLine("Hello World!");
    }

    private static byte[] SwapEndian(byte[] v0)
    {
        byte[] v = (byte[])v0.Clone();
        int i = 0;
        int j = v.Length - 1;
        while (i < j)
        {
            byte t = v[i];
            v[i] = v[j];
            v[j] = t;
            i++;
            j--;
        }
        return v;
    }