ECDHWithKdfBasicAgreement.cs 1.9 KB

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