Pkcs7Padding.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
  7. {
  8. /**
  9. * A padder that adds Pkcs7/Pkcs5 padding to a block.
  10. */
  11. public class Pkcs7Padding
  12. : IBlockCipherPadding
  13. {
  14. /**
  15. * Initialise the padder.
  16. *
  17. * @param random - a SecureRandom if available.
  18. */
  19. public void Init(
  20. SecureRandom random)
  21. {
  22. // nothing to do.
  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 "PKCS7"; }
  32. }
  33. /**
  34. * add the pad bytes to the passed in block, returning the
  35. * number of bytes added.
  36. */
  37. public int AddPadding(
  38. byte[] input,
  39. int inOff)
  40. {
  41. byte code = (byte)(input.Length - inOff);
  42. while (inOff < input.Length)
  43. {
  44. input[inOff] = code;
  45. inOff++;
  46. }
  47. return code;
  48. }
  49. /**
  50. * return the number of pad bytes present in the block.
  51. */
  52. public int PadCount(
  53. byte[] input)
  54. {
  55. byte countAsByte = input[input.Length - 1];
  56. int count = countAsByte;
  57. if (count < 1 || count > input.Length)
  58. throw new InvalidCipherTextException("pad block corrupted");
  59. for (int i = 2; i <= count; i++)
  60. {
  61. if (input[input.Length - i] != countAsByte)
  62. throw new InvalidCipherTextException("pad block corrupted");
  63. }
  64. return count;
  65. }
  66. }
  67. }
  68. #pragma warning restore
  69. #endif