3

我正在为可能遇到不同指数大小的软件创建单元测试。(请参阅本 RFC 的第 3.3.1 节

如何使用 Bouncy Castle 或任何其他 C# 库来生成密钥大小不为 65537 的 RSA 密钥对。

如果答案是我可以直接修改这个,只要我也更新私钥,我应该对公钥和私钥进行哪些具体的更改(或重新计算)?

这是我用来创建指数为 65537 的密钥的示例代码:

        // Create key
        RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
        var param = new KeyGenerationParameters(new SecureRandom(), 1024);
        generator.Init(param);
         AsymmetricCipherKeyPair keyPair= generator.GenerateKeyPair();

        // Save to export format
        SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
        byte[] ret =  info.GetEncoded();
        string ovalue1 = Convert.ToBase64String(ret);

        // Read from export format
        byte[] publicKeyBytes = Convert.FromBase64String(ovalue1);
        AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);

        RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
        RSAParameters rsaParameters = new RSAParameters();
        rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArray();
        rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArray();
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.ImportParameters(rsaParameters);
4

1 回答 1

2

感谢@BrettHale,我能够解决这个问题。

这是在 Bouncy Castle 中创建密钥对的方法

      // Create key
        RsaKeyPairGenerator generator = new RsaKeyPairGenerator();

        /*
         * This value should be a Fermat number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also.
         * 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617,
         * 
         * Practically speaking, Windows does not tolerate public exponents which do not fit in a 32-bit unsigned integer. Using e=3 or e=65537 works "everywhere". 
         */
        BigInteger exponentBigInt = new BigInteger(exponent.ToString());

        var param = new RsaKeyGenerationParameters(
            exponentBigInt, // new BigInteger("10001", 16)  publicExponent
            new SecureRandom(),  // SecureRandom.getInstance("SHA1PRNG"),//prng
            keyStrength, //strength
            certaninty);//certainty
        generator.Init(param);

与他建议使用 RSAKeyGenerationParameters 相关的其他链接包括:

于 2012-07-01T20:27:17.647 回答