ECMqvWithKdfBasicAgreement.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  9. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
  10. {
  11. public class ECMqvWithKdfBasicAgreement
  12. : ECMqvBasicAgreement
  13. {
  14. private readonly string algorithm;
  15. private readonly IDerivationFunction kdf;
  16. public ECMqvWithKdfBasicAgreement(
  17. string algorithm,
  18. IDerivationFunction kdf)
  19. {
  20. if (algorithm == null)
  21. throw new ArgumentNullException("algorithm");
  22. if (kdf == null)
  23. throw new ArgumentNullException("kdf");
  24. this.algorithm = algorithm;
  25. this.kdf = kdf;
  26. }
  27. public override BigInteger CalculateAgreement(
  28. ICipherParameters pubKey)
  29. {
  30. // Note that the ec.KeyAgreement class in JCE only uses kdf in one
  31. // of the engineGenerateSecret methods.
  32. BigInteger result = base.CalculateAgreement(pubKey);
  33. int keySize = GeneratorUtilities.GetDefaultKeySize(algorithm);
  34. DHKdfParameters dhKdfParams = new DHKdfParameters(
  35. new DerObjectIdentifier(algorithm),
  36. keySize,
  37. BigIntToBytes(result));
  38. kdf.Init(dhKdfParams);
  39. byte[] keyBytes = new byte[keySize / 8];
  40. kdf.GenerateBytes(keyBytes, 0, keyBytes.Length);
  41. return new BigInteger(1, keyBytes);
  42. }
  43. private byte[] BigIntToBytes(BigInteger r)
  44. {
  45. int byteLength = X9IntegerConverter.GetByteLength(privParams.StaticPrivateKey.Parameters.Curve);
  46. return X9IntegerConverter.IntegerToBytes(r, byteLength);
  47. }
  48. }
  49. }
  50. #pragma warning restore
  51. #endif