FastTlsBlockCipherImpl.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.Parameters;
  6. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl;
  7. namespace Best.HTTP.Shared.TLS.Crypto.Impl
  8. {
  9. internal sealed class FastTlsBlockCipherImpl
  10. : TlsBlockCipherImpl
  11. {
  12. private readonly bool m_isEncrypting;
  13. private readonly IBlockCipher m_cipher;
  14. private KeyParameter key;
  15. internal FastTlsBlockCipherImpl(IBlockCipher 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[] iv, int ivOff, int ivLen)
  31. {
  32. m_cipher.Init(m_isEncrypting, new ParametersWithIV(key, iv, ivOff, ivLen));
  33. }
  34. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  35. public void Init(ReadOnlySpan<byte> iv)
  36. {
  37. m_cipher.Init(m_isEncrypting, new ParametersWithIV(key, iv));
  38. }
  39. #endif
  40. public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset)
  41. {
  42. int blockSize = m_cipher.GetBlockSize();
  43. for (int i = 0; i < inputLength; i += blockSize)
  44. {
  45. m_cipher.ProcessBlock(input, inputOffset + i, output, outputOffset + i);
  46. }
  47. return inputLength;
  48. }
  49. public int GetBlockSize()
  50. {
  51. return m_cipher.GetBlockSize();
  52. }
  53. }
  54. }
  55. #pragma warning restore
  56. #endif