如何使用Bouncy Castle生成EC密钥对

时间:2017-09-11 21:01:29

标签: c# bouncycastle encryption-asymmetric elliptic-curve fips

我目前的项目是仅使用BouncyCastle的fips资源进行加密/解密签名等等。这些密钥仍然使用通常的C#bouncy城​​堡生成。现在,因为这是浪费我想改变代码,但我找不到任何关于如何做到这一点的文档。

到目前为止我有什么:

ECDomainParameters s = new ECDomainParameters(...?)
        FipsEC.KeyPairGenerator ecGen = CryptoServicesRegistrar.CreateGenerator(new FipsEC.KeyGenerationParameters(s));

但是如何指定曲线的类型G和n?

如果你能以某种方式提供帮助,请提前感谢。

1 个答案:

答案 0 :(得分:0)

我在BouncyCastle单元测试中找到了一些例子。尝试使用测试下载他们的代码:https://www.bouncycastle.org/csharp/download/bccrypto-csharp-1.8.1-src.zip或在他们的网页上找到合适的来源:https://www.bouncycastle.org/csharp/index.html

然后查找具有单元测试的类:ECTest

例如,他们有这样的代码:

/**
 * key generation test
 */
[Test]
public void TestECDsaKeyGenTest()
{
    SecureRandom random = new SecureRandom();

    BigInteger n = new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307");

    FpCurve curve = new FpCurve(
        new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
        new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
        new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16), // b
        n, BigInteger.One);

    ECDomainParameters parameters = new ECDomainParameters(
        curve,
        curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
        n);

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
        parameters,
        random);

    pGen.Init(genParam);

    AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

    ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);

    ECDsaSigner ecdsa = new ECDsaSigner();

    ecdsa.Init(true, param);

    byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
    BigInteger[] sig = ecdsa.GenerateSignature(message);

    ecdsa.Init(false, pair.Public);

    if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
    {
        Fail("signature fails");
    }
}