ISO10126d2Padding.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. /**
  8. * A padder that adds ISO10126-2 padding to a block.
  9. */
  10. public class ISO10126d2Padding: IBlockCipherPadding
  11. {
  12. private SecureRandom random;
  13. /**
  14. * Initialise the padder.
  15. *
  16. * @param random a SecureRandom if available.
  17. */
  18. public void Init(
  19. SecureRandom random)
  20. //throws ArgumentException
  21. {
  22. this.random = CryptoServicesRegistrar.GetSecureRandom(random);
  23. }
  24. /**
  25. * Return the name of the algorithm the cipher implements.
  26. *
  27. * @return the name of the algorithm the cipher implements.
  28. */
  29. public string PaddingName
  30. {
  31. get { return "ISO10126-2"; }
  32. }
  33. public int AddPadding(byte[] input, int inOff)
  34. {
  35. int count = input.Length - inOff;
  36. if (count > 1)
  37. {
  38. random.NextBytes(input, inOff, count - 1);
  39. }
  40. input[input.Length - 1] = (byte)count;
  41. return count;
  42. }
  43. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  44. public int AddPadding(Span<byte> block, int position)
  45. {
  46. int count = block.Length - position;
  47. if (count > 1)
  48. {
  49. random.NextBytes(block[position..(block.Length - 1)]);
  50. }
  51. block[block.Length - 1] = (byte)count;
  52. return count;
  53. }
  54. #endif
  55. public int PadCount(byte[] input)
  56. {
  57. int count = input[input.Length -1];
  58. int position = input.Length - count;
  59. int failed = (position | (count - 1)) >> 31;
  60. if (failed != 0)
  61. throw new InvalidCipherTextException("pad block corrupted");
  62. return count;
  63. }
  64. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  65. public int PadCount(ReadOnlySpan<byte> block)
  66. {
  67. int count = block[block.Length - 1];
  68. int position = block.Length - count;
  69. int failed = (position | (count - 1)) >> 31;
  70. if (failed != 0)
  71. throw new InvalidCipherTextException("pad block corrupted");
  72. return count;
  73. }
  74. #endif
  75. }
  76. }
  77. #pragma warning restore
  78. #endif