TbcPadding.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using Org.BouncyCastle.Crypto;
  4. using Org.BouncyCastle.Security;
  5. namespace Org.BouncyCastle.Crypto.Paddings
  6. {
  7. /// <summary> A padder that adds Trailing-Bit-Compliment padding to a block.
  8. /// <p>
  9. /// This padding pads the block out compliment of the last bit
  10. /// of the plain text.
  11. /// </p>
  12. /// </summary>
  13. public class TbcPadding
  14. : IBlockCipherPadding
  15. {
  16. /// <summary> Return the name of the algorithm the cipher implements.</summary>
  17. /// <returns> the name of the algorithm the cipher implements.
  18. /// </returns>
  19. public string PaddingName
  20. {
  21. get { return "TBC"; }
  22. }
  23. /// <summary> Initialise the padder.</summary>
  24. /// <param name="random">- a SecureRandom if available.
  25. /// </param>
  26. public virtual void Init(SecureRandom random)
  27. {
  28. // nothing to do.
  29. }
  30. /// <summary> add the pad bytes to the passed in block, returning the
  31. /// number of bytes added.
  32. /// <p>
  33. /// Note: this assumes that the last block of plain text is always
  34. /// passed to it inside in. i.e. if inOff is zero, indicating the
  35. /// entire block is to be overwritten with padding the value of in
  36. /// should be the same as the last block of plain text.
  37. /// </p>
  38. /// </summary>
  39. public virtual int AddPadding(byte[] input, int inOff)
  40. {
  41. int count = input.Length - inOff;
  42. byte code;
  43. if (inOff > 0)
  44. {
  45. code = (byte)((input[inOff - 1] & 0x01) == 0?0xff:0x00);
  46. }
  47. else
  48. {
  49. code = (byte)((input[input.Length - 1] & 0x01) == 0?0xff:0x00);
  50. }
  51. while (inOff < input.Length)
  52. {
  53. input[inOff] = code;
  54. inOff++;
  55. }
  56. return count;
  57. }
  58. /// <summary> return the number of pad bytes present in the block.</summary>
  59. public virtual int PadCount(byte[] input)
  60. {
  61. byte code = input[input.Length - 1];
  62. int index = input.Length - 1;
  63. while (index > 0 && input[index - 1] == code)
  64. {
  65. index--;
  66. }
  67. return input.Length - index;
  68. }
  69. }
  70. }
  71. #endif