_cipheralgorithm.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. # This exists to break an import cycle. It is normally accessible from the
  8. # ciphers module.
  9. class CipherAlgorithm(metaclass=abc.ABCMeta):
  10. @property
  11. @abc.abstractmethod
  12. def name(self) -> str:
  13. """
  14. A string naming this mode (e.g. "AES", "Camellia").
  15. """
  16. @property
  17. @abc.abstractmethod
  18. def key_sizes(self) -> frozenset[int]:
  19. """
  20. Valid key sizes for this algorithm in bits
  21. """
  22. @property
  23. @abc.abstractmethod
  24. def key_size(self) -> int:
  25. """
  26. The size of the key being used as an integer in bits (e.g. 128, 256).
  27. """
  28. class BlockCipherAlgorithm(CipherAlgorithm):
  29. key: bytes
  30. @property
  31. @abc.abstractmethod
  32. def block_size(self) -> int:
  33. """
  34. The size of a block as an integer in bits (e.g. 64, 128).
  35. """
  36. def _verify_key_size(algorithm: CipherAlgorithm, key: bytes) -> bytes:
  37. # Verify that the key is instance of bytes
  38. utils._check_byteslike("key", key)
  39. # Verify that the key size matches the expected key size
  40. if len(key) * 8 not in algorithm.key_sizes:
  41. raise ValueError(
  42. f"Invalid key size ({len(key) * 8}) for {algorithm.name}."
  43. )
  44. return key