DHBasicAgreement.cs 2.5 KB

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