ECDH在c#中使用BouncyCastle生成共享密钥

时间:2013-06-12 04:08:56

标签: c# encryption bouncycastle

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

我使用过Microsoft的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();

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

谢谢!

0 个答案:

没有答案