CAST.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/CAST.py : CAST
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. """
  23. Module's constants for the modes of operation supported with CAST:
  24. :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
  25. :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
  26. :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
  27. :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
  28. :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
  29. :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
  30. :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
  31. """
  32. import sys
  33. from tls.Crypto.Cipher import _create_cipher
  34. from tls.Crypto.Util.py3compat import byte_string
  35. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  36. VoidPointer, SmartPointer,
  37. c_size_t, c_uint8_ptr)
  38. _raw_cast_lib = load_pycryptodome_raw_lib(
  39. "Crypto.Cipher._raw_cast",
  40. """
  41. int CAST_start_operation(const uint8_t key[],
  42. size_t key_len,
  43. void **pResult);
  44. int CAST_encrypt(const void *state,
  45. const uint8_t *in,
  46. uint8_t *out,
  47. size_t data_len);
  48. int CAST_decrypt(const void *state,
  49. const uint8_t *in,
  50. uint8_t *out,
  51. size_t data_len);
  52. int CAST_stop_operation(void *state);
  53. """)
  54. def _create_base_cipher(dict_parameters):
  55. """This method instantiates and returns a handle to a low-level
  56. base cipher. It will absorb named parameters in the process."""
  57. try:
  58. key = dict_parameters.pop("key")
  59. except KeyError:
  60. raise TypeError("Missing 'key' parameter")
  61. if len(key) not in key_size:
  62. raise ValueError("Incorrect CAST key length (%d bytes)" % len(key))
  63. start_operation = _raw_cast_lib.CAST_start_operation
  64. stop_operation = _raw_cast_lib.CAST_stop_operation
  65. cipher = VoidPointer()
  66. result = start_operation(c_uint8_ptr(key),
  67. c_size_t(len(key)),
  68. cipher.address_of())
  69. if result:
  70. raise ValueError("Error %X while instantiating the CAST cipher"
  71. % result)
  72. return SmartPointer(cipher.get(), stop_operation)
  73. def new(key, mode, *args, **kwargs):
  74. """Create a new CAST cipher
  75. :param key:
  76. The secret key to use in the symmetric cipher.
  77. Its length can vary from 5 to 16 bytes.
  78. :type key: bytes, bytearray, memoryview
  79. :param mode:
  80. The chaining mode to use for encryption or decryption.
  81. :type mode: One of the supported ``MODE_*`` constants
  82. :Keyword Arguments:
  83. * **iv** (*bytes*, *bytearray*, *memoryview*) --
  84. (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
  85. and ``MODE_OPENPGP`` modes).
  86. The initialization vector to use for encryption or decryption.
  87. For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
  88. For ``MODE_OPENPGP`` mode only,
  89. it must be 8 bytes long for encryption
  90. and 10 bytes for decryption (in the latter case, it is
  91. actually the *encrypted* IV which was prefixed to the ciphertext).
  92. If not provided, a random byte string is generated (you must then
  93. read its value with the :attr:`iv` attribute).
  94. * **nonce** (*bytes*, *bytearray*, *memoryview*) --
  95. (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
  96. A value that must never be reused for any other encryption done
  97. with this key.
  98. For ``MODE_EAX`` there are no
  99. restrictions on its length (recommended: **16** bytes).
  100. For ``MODE_CTR``, its length must be in the range **[0..7]**.
  101. If not provided for ``MODE_EAX``, a random byte string is generated (you
  102. can read it back via the ``nonce`` attribute).
  103. * **segment_size** (*integer*) --
  104. (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
  105. are segmented in. It must be a multiple of 8.
  106. If not specified, it will be assumed to be 8.
  107. * **mac_len** : (*integer*) --
  108. (Only ``MODE_EAX``)
  109. Length of the authentication tag, in bytes.
  110. It must be no longer than 8 (default).
  111. * **initial_value** : (*integer*) --
  112. (Only ``MODE_CTR``). The initial value for the counter within
  113. the counter block. By default it is **0**.
  114. :Return: a CAST object, of the applicable mode.
  115. """
  116. return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  117. MODE_ECB = 1
  118. MODE_CBC = 2
  119. MODE_CFB = 3
  120. MODE_OFB = 5
  121. MODE_CTR = 6
  122. MODE_OPENPGP = 7
  123. MODE_EAX = 9
  124. # Size of a data block (in bytes)
  125. block_size = 8
  126. # Size of a key (in bytes)
  127. key_size = range(5, 16 + 1)