3

我正在尝试使用 bouncycastle 库在我的 c# 应用程序中使用 ECDH(p521 曲线)生成共享密钥。

我用的是微软的CngKey,服务器和客户端生成的共享密钥是一样的。但是,由于 Win XP 不支持此功能,因此我正在尝试 Bouncycastle。

以下是我生成密钥对的代码,然后获取服务器的 X 和 Y 并从中生成服务器公钥。

X9ECParameters ecP = NistNamedCurves.GetByName("P-521");
ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H,   ecP.GetSeed());
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDH");
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

// Client X and Y
BigInteger ax = ecP.G.X.ToBigInteger();
byte[] axb = ax.ToByteArray();
BigInteger ay = ecP.G.Y.ToBigInteger();
byte[] ayb = ay.ToByteArray();

// Generate Client Keypair
 AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
 IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");
aKeyAgree.Init(aKeyPair.Private);


// Get Servers X and Y
Console.WriteLine("Enter X co-ordinate");
string BobXhex = Console.ReadLine();

Console.WriteLine("Enter Y co-ordinate");
string BobYhex = Console.ReadLine();

// Server public key
FpCurve c = (FpCurve)ecSpec.Curve;
ECFieldElement x = new FpFieldElement(c.Q, new BigInteger(BobXhex, 16));
ECFieldElement y = new FpFieldElement(c.Q, new BigInteger(BobYhex, 16));

ECPoint q = new FpPoint(ecP.Curve, x, y);
ECPublicKeyParameters publicKey = new ECPublicKeyParameters("ECDH", q,    SecObjectIdentifiers.SecP521r1);

// generate shared key
BigInteger k1 = aKeyAgree.CalculateAgreement(publicKey);
byte[] genKey = k1.ToByteArray();

我想知道以上是否是生成共享密钥的正确方法。共享密钥与服务器上生成的不匹配。

谢谢!

4

0 回答 0