Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Collections;
- using System.Text;
- using Org.BouncyCastle.Asn1.Sec;
- using Org.BouncyCastle.Asn1.X9;
- using Org.BouncyCastle.Crypto.Parameters;
- using Org.BouncyCastle.Math;
- using Org.BouncyCastle.Math.EC;
- using Org.BouncyCastle.Crypto.Agreement;
- namespace BouncyCastleECDH
- {
- class Program
- {
- public static readonly X9ECParameters _ecparameters = SecNamedCurves.GetByName("secp256k1");
- public static readonly ECDomainParameters _domain = new ECDomainParameters(_ecparameters.Curve, _ecparameters.G, _ecparameters.N, _ecparameters.H);
- public static string ByteArrayToString(byte[] ba)
- {
- StringBuilder hex = new StringBuilder(ba.Length * 2);
- foreach (byte b in ba)
- hex.AppendFormat("{0:x2}", b);
- return hex.ToString();
- }
- public static byte[] ECDH(BigInteger privKeyInt, byte[] publicKey)
- {
- ECPrivateKeyParameters ecPrivateKey = new ECPrivateKeyParameters(privKeyInt, _domain);
- ECPoint publicPoint = _ecparameters.Curve.DecodePoint(publicKey);
- ECPublicKeyParameters ecPublicKey = new ECPublicKeyParameters(publicPoint, _domain);
- // ECDHCBasicAgreement basicAgreement = new ECDHCBasicAgreement();
- ECDHBasicAgreement basicAgreement = new ECDHBasicAgreement();
- basicAgreement.Init(ecPrivateKey);
- BigInteger symKey = basicAgreement.CalculateAgreement(ecPublicKey);
- return symKey.ToByteArray();
- }
- public static byte[] GetPublicKey(BigInteger privKeyInt)
- {
- return GetPublicKey(_ecparameters.G.Multiply(privKeyInt));
- }
- public static byte[] GetPublicKey(ECPoint p)
- {
- var publicParams = new ECPublicKeyParameters(p, _domain);
- return publicParams.Q.GetEncoded();
- }
- static void Main()
- {
- string privkey1 = "82fc9947e878fc7ed01c6c310688603f0a41c8e8704e5b990e8388343b0fd465";
- string privkey2 = "5f706787ac72c1080275c1f398640fb07e9da0b124ae9734b28b8d0f01eda586";
- BigInteger privkey1Int = new BigInteger(privkey1,16);
- BigInteger privkey2Int = new BigInteger(privkey2,16);
- var pubkey1 = GetPublicKey(privkey1Int);
- var pubkey2 = GetPublicKey(privkey2Int);
- Console.WriteLine($"pub1:{ByteArrayToString(pubkey1)}");
- Console.WriteLine($"pub2:{ByteArrayToString(pubkey2)}");
- Console.WriteLine($"ecdh:{ByteArrayToString(ECDH(privkey1Int,pubkey2))}");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement