ZeroBytePadding.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  5. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
  6. {
  7. /// <summary> A padder that adds Null byte padding to a block.</summary>
  8. public class ZeroBytePadding : IBlockCipherPadding
  9. {
  10. /// <summary> Return the name of the algorithm the cipher implements.
  11. ///
  12. /// </summary>
  13. /// <returns> the name of the algorithm the cipher implements.
  14. /// </returns>
  15. public string PaddingName
  16. {
  17. get { return "ZeroBytePadding"; }
  18. }
  19. /// <summary> Initialise the padder.
  20. ///
  21. /// </summary>
  22. /// <param name="random">- a SecureRandom if available.
  23. /// </param>
  24. public void Init(SecureRandom random)
  25. {
  26. // nothing to do.
  27. }
  28. public int AddPadding(byte[] input, int inOff)
  29. {
  30. int added = input.Length - inOff;
  31. while (inOff < input.Length)
  32. {
  33. input[inOff++] = 0x00;
  34. }
  35. return added;
  36. }
  37. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  38. public int AddPadding(Span<byte> block, int position)
  39. {
  40. int count = block.Length - position;
  41. block[position..].Fill(0x00);
  42. return count;
  43. }
  44. #endif
  45. public int PadCount(byte[] input)
  46. {
  47. int count = 0, still00Mask = -1;
  48. int i = input.Length;
  49. while (--i >= 0)
  50. {
  51. int next = input[i];
  52. int match00Mask = ((next ^ 0x00) - 1) >> 31;
  53. still00Mask &= match00Mask;
  54. count -= still00Mask;
  55. }
  56. return count;
  57. }
  58. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  59. public int PadCount(ReadOnlySpan<byte> block)
  60. {
  61. int count = 0, still00Mask = -1;
  62. int i = block.Length;
  63. while (--i >= 0)
  64. {
  65. int next = block[i];
  66. int match00Mask = ((next ^ 0x00) - 1) >> 31;
  67. still00Mask &= match00Mask;
  68. count -= still00Mask;
  69. }
  70. return count;
  71. }
  72. #endif
  73. }
  74. }
  75. #pragma warning restore
  76. #endif