padding.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import annotations
  5. import abc
  6. from cryptography import utils
  7. from cryptography.hazmat.bindings._rust import (
  8. ANSIX923PaddingContext,
  9. ANSIX923UnpaddingContext,
  10. PKCS7PaddingContext,
  11. PKCS7UnpaddingContext,
  12. )
  13. class PaddingContext(metaclass=abc.ABCMeta):
  14. @abc.abstractmethod
  15. def update(self, data: utils.Buffer) -> bytes:
  16. """
  17. Pads the provided bytes and returns any available data as bytes.
  18. """
  19. @abc.abstractmethod
  20. def finalize(self) -> bytes:
  21. """
  22. Finalize the padding, returns bytes.
  23. """
  24. def _byte_padding_check(block_size: int) -> None:
  25. if not (0 <= block_size <= 2040):
  26. raise ValueError("block_size must be in range(0, 2041).")
  27. if block_size % 8 != 0:
  28. raise ValueError("block_size must be a multiple of 8.")
  29. class PKCS7:
  30. def __init__(self, block_size: int):
  31. _byte_padding_check(block_size)
  32. self.block_size = block_size
  33. def padder(self) -> PaddingContext:
  34. return PKCS7PaddingContext(self.block_size)
  35. def unpadder(self) -> PaddingContext:
  36. return PKCS7UnpaddingContext(self.block_size)
  37. PaddingContext.register(PKCS7PaddingContext)
  38. PaddingContext.register(PKCS7UnpaddingContext)
  39. class ANSIX923:
  40. def __init__(self, block_size: int):
  41. _byte_padding_check(block_size)
  42. self.block_size = block_size
  43. def padder(self) -> PaddingContext:
  44. return ANSIX923PaddingContext(self.block_size)
  45. def unpadder(self) -> PaddingContext:
  46. return ANSIX923UnpaddingContext(self.block_size)
  47. PaddingContext.register(ANSIX923PaddingContext)
  48. PaddingContext.register(ANSIX923UnpaddingContext)