ECDHKekGenerator.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.X509;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  9. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf
  10. {
  11. /**
  12. * X9.63 based key derivation function for ECDH CMS.
  13. */
  14. public sealed class ECDHKekGenerator
  15. : IDerivationFunction
  16. {
  17. private readonly IDerivationFunction m_kdf;
  18. private DerObjectIdentifier algorithm;
  19. private int keySize;
  20. private byte[] z;
  21. public ECDHKekGenerator(IDigest digest)
  22. {
  23. m_kdf = new Kdf2BytesGenerator(digest);
  24. }
  25. public void Init(IDerivationParameters param)
  26. {
  27. DHKdfParameters parameters = (DHKdfParameters)param;
  28. this.algorithm = parameters.Algorithm;
  29. this.keySize = parameters.KeySize;
  30. this.z = parameters.GetZ(); // TODO Clone?
  31. }
  32. public IDigest Digest => m_kdf.Digest;
  33. public int GenerateBytes(byte[] outBytes, int outOff, int length)
  34. {
  35. Check.OutputLength(outBytes, outOff, length, "output buffer too small");
  36. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  37. return GenerateBytes(outBytes.AsSpan(outOff, length));
  38. #else
  39. // TODO Create an ASN.1 class for this (RFC3278)
  40. // ECC-CMS-SharedInfo
  41. DerSequence s = new DerSequence(
  42. new AlgorithmIdentifier(algorithm, DerNull.Instance),
  43. new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));
  44. m_kdf.Init(new KdfParameters(z, s.GetDerEncoded()));
  45. return m_kdf.GenerateBytes(outBytes, outOff, length);
  46. #endif
  47. }
  48. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  49. public int GenerateBytes(Span<byte> output)
  50. {
  51. // TODO Create an ASN.1 class for this (RFC3278)
  52. // ECC-CMS-SharedInfo
  53. DerSequence s = new DerSequence(
  54. new AlgorithmIdentifier(algorithm, DerNull.Instance),
  55. new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));
  56. m_kdf.Init(new KdfParameters(z, s.GetDerEncoded()));
  57. return m_kdf.GenerateBytes(output);
  58. }
  59. #endif
  60. }
  61. }
  62. #pragma warning restore
  63. #endif