DefaultTlsAgreementCredentials.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
  10. {
  11. public class DefaultTlsAgreementCredentials
  12. : AbstractTlsAgreementCredentials
  13. {
  14. protected readonly Certificate mCertificate;
  15. protected readonly AsymmetricKeyParameter mPrivateKey;
  16. protected readonly IBasicAgreement mBasicAgreement;
  17. protected readonly bool mTruncateAgreement;
  18. public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey)
  19. {
  20. if (certificate == null)
  21. throw new ArgumentNullException("certificate");
  22. if (certificate.IsEmpty)
  23. throw new ArgumentException("cannot be empty", "certificate");
  24. if (privateKey == null)
  25. throw new ArgumentNullException("privateKey");
  26. if (!privateKey.IsPrivate)
  27. throw new ArgumentException("must be private", "privateKey");
  28. if (privateKey is DHPrivateKeyParameters)
  29. {
  30. mBasicAgreement = new DHBasicAgreement();
  31. mTruncateAgreement = true;
  32. }
  33. else if (privateKey is ECPrivateKeyParameters)
  34. {
  35. mBasicAgreement = new ECDHBasicAgreement();
  36. mTruncateAgreement = false;
  37. }
  38. else
  39. {
  40. throw new ArgumentException("type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey), "privateKey");
  41. }
  42. this.mCertificate = certificate;
  43. this.mPrivateKey = privateKey;
  44. }
  45. public override Certificate Certificate
  46. {
  47. get { return mCertificate; }
  48. }
  49. /// <exception cref="IOException"></exception>
  50. public override byte[] GenerateAgreement(AsymmetricKeyParameter peerPublicKey)
  51. {
  52. mBasicAgreement.Init(mPrivateKey);
  53. BigInteger agreementValue = mBasicAgreement.CalculateAgreement(peerPublicKey);
  54. if (mTruncateAgreement)
  55. {
  56. return BigIntegers.AsUnsignedByteArray(agreementValue);
  57. }
  58. return BigIntegers.AsUnsignedByteArray(mBasicAgreement.GetFieldSize(), agreementValue);
  59. }
  60. }
  61. }
  62. #pragma warning restore
  63. #endif