ARC2.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/ARC2.py : ARC2.py
  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 ARC2:
  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_arc2_lib = load_pycryptodome_raw_lib(
  39. "Crypto.Cipher._raw_arc2",
  40. """
  41. int ARC2_start_operation(const uint8_t key[],
  42. size_t key_len,
  43. size_t effective_key_len,
  44. void **pResult);
  45. int ARC2_encrypt(const void *state,
  46. const uint8_t *in,
  47. uint8_t *out,
  48. size_t data_len);
  49. int ARC2_decrypt(const void *state,
  50. const uint8_t *in,
  51. uint8_t *out,
  52. size_t data_len);
  53. int ARC2_stop_operation(void *state);
  54. """
  55. )
  56. def _create_base_cipher(dict_parameters):
  57. """This method instantiates and returns a handle to a low-level
  58. base cipher. It will absorb named parameters in the process."""
  59. try:
  60. key = dict_parameters.pop("key")
  61. except KeyError:
  62. raise TypeError("Missing 'key' parameter")
  63. effective_keylen = dict_parameters.pop("effective_keylen", 1024)
  64. if len(key) not in key_size:
  65. raise ValueError("Incorrect ARC2 key length (%d bytes)" % len(key))
  66. if not (40 <= effective_keylen <= 1024):
  67. raise ValueError("'effective_key_len' must be at least 40 and no larger than 1024 "
  68. "(not %d)" % effective_keylen)
  69. start_operation = _raw_arc2_lib.ARC2_start_operation
  70. stop_operation = _raw_arc2_lib.ARC2_stop_operation
  71. cipher = VoidPointer()
  72. result = start_operation(c_uint8_ptr(key),
  73. c_size_t(len(key)),
  74. c_size_t(effective_keylen),
  75. cipher.address_of())
  76. if result:
  77. raise ValueError("Error %X while instantiating the ARC2 cipher"
  78. % result)
  79. return SmartPointer(cipher.get(), stop_operation)
  80. def new(key, mode, *args, **kwargs):
  81. """Create a new RC2 cipher.
  82. :param key:
  83. The secret key to use in the symmetric cipher.
  84. Its length can vary from 5 to 128 bytes; the actual search space
  85. (and the cipher strength) can be reduced with the ``effective_keylen`` parameter.
  86. :type key: bytes, bytearray, memoryview
  87. :param mode:
  88. The chaining mode to use for encryption or decryption.
  89. :type mode: One of the supported ``MODE_*`` constants
  90. :Keyword Arguments:
  91. * **iv** (*bytes*, *bytearray*, *memoryview*) --
  92. (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
  93. and ``MODE_OPENPGP`` modes).
  94. The initialization vector to use for encryption or decryption.
  95. For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
  96. For ``MODE_OPENPGP`` mode only,
  97. it must be 8 bytes long for encryption
  98. and 10 bytes for decryption (in the latter case, it is
  99. actually the *encrypted* IV which was prefixed to the ciphertext).
  100. If not provided, a random byte string is generated (you must then
  101. read its value with the :attr:`iv` attribute).
  102. * **nonce** (*bytes*, *bytearray*, *memoryview*) --
  103. (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
  104. A value that must never be reused for any other encryption done
  105. with this key.
  106. For ``MODE_EAX`` there are no
  107. restrictions on its length (recommended: **16** bytes).
  108. For ``MODE_CTR``, its length must be in the range **[0..7]**.
  109. If not provided for ``MODE_EAX``, a random byte string is generated (you
  110. can read it back via the ``nonce`` attribute).
  111. * **effective_keylen** (*integer*) --
  112. Optional. Maximum strength in bits of the actual key used by the ARC2 algorithm.
  113. If the supplied ``key`` parameter is longer (in bits) of the value specified
  114. here, it will be weakened to match it.
  115. If not specified, no limitation is applied.
  116. * **segment_size** (*integer*) --
  117. (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
  118. are segmented in. It must be a multiple of 8.
  119. If not specified, it will be assumed to be 8.
  120. * **mac_len** : (*integer*) --
  121. (Only ``MODE_EAX``)
  122. Length of the authentication tag, in bytes.
  123. It must be no longer than 8 (default).
  124. * **initial_value** : (*integer*) --
  125. (Only ``MODE_CTR``). The initial value for the counter within
  126. the counter block. By default it is **0**.
  127. :Return: an ARC2 object, of the applicable mode.
  128. """
  129. return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  130. MODE_ECB = 1
  131. MODE_CBC = 2
  132. MODE_CFB = 3
  133. MODE_OFB = 5
  134. MODE_CTR = 6
  135. MODE_OPENPGP = 7
  136. MODE_EAX = 9
  137. # Size of a data block (in bytes)
  138. block_size = 8
  139. # Size of a key (in bytes)
  140. key_size = range(5, 128 + 1)