ECDHBasicAgreement.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using Org.BouncyCastle.Math;
  4. using Org.BouncyCastle.Math.EC;
  5. using Org.BouncyCastle.Crypto;
  6. using Org.BouncyCastle.Crypto.Parameters;
  7. namespace Org.BouncyCastle.Crypto.Agreement
  8. {
  9. /**
  10. * P1363 7.2.1 ECSVDP-DH
  11. *
  12. * ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive,
  13. * Diffie-Hellman version. It is based on the work of [DH76], [Mil86],
  14. * and [Kob87]. This primitive derives a shared secret value from one
  15. * party's private key and another party's public key, where both have
  16. * the same set of EC domain parameters. If two parties correctly
  17. * execute this primitive, they will produce the same output. This
  18. * primitive can be invoked by a scheme to derive a shared secret key;
  19. * specifically, it may be used with the schemes ECKAS-DH1 and
  20. * DL/ECKAS-DH2. It assumes that the input keys are valid (see also
  21. * Section 7.2.2).
  22. */
  23. public class ECDHBasicAgreement
  24. : IBasicAgreement
  25. {
  26. protected internal ECPrivateKeyParameters privKey;
  27. public virtual void Init(
  28. ICipherParameters parameters)
  29. {
  30. if (parameters is ParametersWithRandom)
  31. {
  32. parameters = ((ParametersWithRandom)parameters).Parameters;
  33. }
  34. this.privKey = (ECPrivateKeyParameters)parameters;
  35. }
  36. public virtual int GetFieldSize()
  37. {
  38. return (privKey.Parameters.Curve.FieldSize + 7) / 8;
  39. }
  40. public virtual BigInteger CalculateAgreement(
  41. ICipherParameters pubKey)
  42. {
  43. ECPublicKeyParameters pub = (ECPublicKeyParameters) pubKey;
  44. if (!pub.Parameters.Equals(privKey.Parameters))
  45. throw new InvalidOperationException("ECDH public key has wrong domain parameters");
  46. ECPoint P = pub.Q.Multiply(privKey.D).Normalize();
  47. if (P.IsInfinity)
  48. throw new InvalidOperationException("Infinity is not a valid agreement value for ECDH");
  49. return P.AffineXCoord.ToBigInteger();
  50. }
  51. }
  52. }
  53. #endif