BcTlsAeadCipherImpl.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  7. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl.BC
  8. {
  9. internal sealed class BcTlsAeadCipherImpl
  10. : TlsAeadCipherImpl
  11. {
  12. private readonly bool m_isEncrypting;
  13. private readonly IAeadCipher m_cipher;
  14. private KeyParameter key;
  15. internal BcTlsAeadCipherImpl(IAeadCipher cipher, bool isEncrypting)
  16. {
  17. this.m_cipher = cipher;
  18. this.m_isEncrypting = isEncrypting;
  19. }
  20. public void SetKey(byte[] key, int keyOff, int keyLen)
  21. {
  22. this.key = new KeyParameter(key, keyOff, keyLen);
  23. }
  24. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  25. public void SetKey(ReadOnlySpan<byte> key)
  26. {
  27. this.key = new KeyParameter(key);
  28. }
  29. #endif
  30. public void Init(byte[] nonce, int macSize, byte[] additionalData)
  31. {
  32. m_cipher.Init(m_isEncrypting, new AeadParameters(key, macSize * 8, nonce, additionalData));
  33. }
  34. public int GetOutputSize(int inputLength)
  35. {
  36. return m_cipher.GetOutputSize(inputLength);
  37. }
  38. public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset)
  39. {
  40. int len = m_cipher.ProcessBytes(input, inputOffset, inputLength, output, outputOffset);
  41. try
  42. {
  43. len += m_cipher.DoFinal(output, outputOffset + len);
  44. }
  45. catch (InvalidCipherTextException e)
  46. {
  47. throw new TlsFatalAlert(AlertDescription.bad_record_mac, e);
  48. }
  49. return len;
  50. }
  51. public void Reset()
  52. {
  53. m_cipher.Reset();
  54. }
  55. }
  56. }
  57. #pragma warning restore
  58. #endif