X923Padding.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
  7. {
  8. /**
  9. * A padder that adds X9.23 padding to a block - if a SecureRandom is
  10. * passed in random padding is assumed, otherwise padding with zeros is used.
  11. */
  12. public class X923Padding
  13. : IBlockCipherPadding
  14. {
  15. private SecureRandom random;
  16. /**
  17. * Initialise the padder.
  18. *
  19. * @param random a SecureRandom if one is available.
  20. */
  21. public void Init(
  22. SecureRandom random)
  23. {
  24. this.random = random;
  25. }
  26. /**
  27. * Return the name of the algorithm the cipher implements.
  28. *
  29. * @return the name of the algorithm the cipher implements.
  30. */
  31. public string PaddingName
  32. {
  33. get { return "X9.23"; }
  34. }
  35. public int AddPadding(byte[] input, int inOff)
  36. {
  37. int count = input.Length - inOff;
  38. if (count > 1)
  39. {
  40. if (random == null)
  41. {
  42. Arrays.Fill(input, inOff, input.Length - 1, 0x00);
  43. }
  44. else
  45. {
  46. random.NextBytes(input, inOff, count - 1);
  47. }
  48. }
  49. input[input.Length - 1] = (byte)count;
  50. return count;
  51. }
  52. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  53. public int AddPadding(Span<byte> block, int position)
  54. {
  55. int count = block.Length - position;
  56. if (count > 1)
  57. {
  58. var body = block[position..(block.Length - 1)];
  59. if (random == null)
  60. {
  61. body.Fill(0x00);
  62. }
  63. else
  64. {
  65. random.NextBytes(body);
  66. }
  67. }
  68. block[block.Length - 1] = (byte)count;
  69. return count;
  70. }
  71. #endif
  72. public int PadCount(byte[] input)
  73. {
  74. int count = input[input.Length - 1];
  75. int position = input.Length - count;
  76. int failed = (position | (count - 1)) >> 31;
  77. if (failed != 0)
  78. throw new InvalidCipherTextException("pad block corrupted");
  79. return count;
  80. }
  81. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  82. public int PadCount(ReadOnlySpan<byte> block)
  83. {
  84. int count = block[block.Length - 1];
  85. int position = block.Length - count;
  86. int failed = (position | (count - 1)) >> 31;
  87. if (failed != 0)
  88. throw new InvalidCipherTextException("pad block corrupted");
  89. return count;
  90. }
  91. #endif
  92. }
  93. }
  94. #pragma warning restore
  95. #endif