DHBasicAgreement.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using Org.BouncyCastle.Crypto.Parameters;
  4. using Org.BouncyCastle.Math;
  5. using Org.BouncyCastle.Security;
  6. namespace Org.BouncyCastle.Crypto.Agreement
  7. {
  8. /**
  9. * a Diffie-Hellman key agreement class.
  10. * <p>
  11. * note: This is only the basic algorithm, it doesn't take advantage of
  12. * long term public keys if they are available. See the DHAgreement class
  13. * for a "better" implementation.</p>
  14. */
  15. public class DHBasicAgreement
  16. : IBasicAgreement
  17. {
  18. private DHPrivateKeyParameters key;
  19. private DHParameters dhParams;
  20. public virtual void Init(
  21. ICipherParameters parameters)
  22. {
  23. if (parameters is ParametersWithRandom)
  24. {
  25. parameters = ((ParametersWithRandom) parameters).Parameters;
  26. }
  27. if (!(parameters is DHPrivateKeyParameters))
  28. {
  29. throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
  30. }
  31. this.key = (DHPrivateKeyParameters) parameters;
  32. this.dhParams = key.Parameters;
  33. }
  34. public virtual int GetFieldSize()
  35. {
  36. return (key.Parameters.P.BitLength + 7) / 8;
  37. }
  38. /**
  39. * given a short term public key from a given party calculate the next
  40. * message in the agreement sequence.
  41. */
  42. public virtual BigInteger CalculateAgreement(
  43. ICipherParameters pubKey)
  44. {
  45. if (this.key == null)
  46. throw new InvalidOperationException("Agreement algorithm not initialised");
  47. DHPublicKeyParameters pub = (DHPublicKeyParameters)pubKey;
  48. if (!pub.Parameters.Equals(dhParams))
  49. {
  50. throw new ArgumentException("Diffie-Hellman public key has wrong parameters.");
  51. }
  52. return pub.Y.ModPow(key.X, dhParams.P);
  53. }
  54. }
  55. }
  56. #endif