DES3.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/DES3.py : DES3
  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 Triple DES:
  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, bchr, bord, bstr
  35. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  36. VoidPointer, SmartPointer,
  37. c_size_t)
  38. _raw_des3_lib = load_pycryptodome_raw_lib(
  39. "Crypto.Cipher._raw_des3",
  40. """
  41. int DES3_start_operation(const uint8_t key[],
  42. size_t key_len,
  43. void **pResult);
  44. int DES3_encrypt(const void *state,
  45. const uint8_t *in,
  46. uint8_t *out,
  47. size_t data_len);
  48. int DES3_decrypt(const void *state,
  49. const uint8_t *in,
  50. uint8_t *out,
  51. size_t data_len);
  52. int DES3_stop_operation(void *state);
  53. """)
  54. def adjust_key_parity(key_in):
  55. """Set the parity bits in a TDES key.
  56. :param key_in: the TDES key whose bits need to be adjusted
  57. :type key_in: byte string
  58. :returns: a copy of ``key_in``, with the parity bits correctly set
  59. :rtype: byte string
  60. :raises ValueError: if the TDES key is not 16 or 24 bytes long
  61. :raises ValueError: if the TDES key degenerates into Single DES
  62. """
  63. def parity_byte(key_byte):
  64. parity = 1
  65. for i in range(1, 8):
  66. parity ^= (key_byte >> i) & 1
  67. return (key_byte & 0xFE) | parity
  68. if len(key_in) not in key_size:
  69. raise ValueError("Not a valid TDES key")
  70. key_out = b"".join([ bchr(parity_byte(bord(x))) for x in key_in ])
  71. if key_out[:8] == key_out[8:16] or key_out[-16:-8] == key_out[-8:]:
  72. raise ValueError("Triple DES key degenerates to single DES")
  73. return key_out
  74. def _create_base_cipher(dict_parameters):
  75. """This method instantiates and returns a handle to a low-level base cipher.
  76. It will absorb named parameters in the process."""
  77. try:
  78. key_in = dict_parameters.pop("key")
  79. except KeyError:
  80. raise TypeError("Missing 'key' parameter")
  81. key = adjust_key_parity(bstr(key_in))
  82. start_operation = _raw_des3_lib.DES3_start_operation
  83. stop_operation = _raw_des3_lib.DES3_stop_operation
  84. cipher = VoidPointer()
  85. result = start_operation(key,
  86. c_size_t(len(key)),
  87. cipher.address_of())
  88. if result:
  89. raise ValueError("Error %X while instantiating the TDES cipher"
  90. % result)
  91. return SmartPointer(cipher.get(), stop_operation)
  92. def new(key, mode, *args, **kwargs):
  93. """Create a new Triple DES cipher.
  94. :param key:
  95. The secret key to use in the symmetric cipher.
  96. It must be 16 or 24 byte long. The parity bits will be ignored.
  97. :type key: bytes/bytearray/memoryview
  98. :param mode:
  99. The chaining mode to use for encryption or decryption.
  100. :type mode: One of the supported ``MODE_*`` constants
  101. :Keyword Arguments:
  102. * **iv** (*bytes*, *bytearray*, *memoryview*) --
  103. (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
  104. and ``MODE_OPENPGP`` modes).
  105. The initialization vector to use for encryption or decryption.
  106. For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
  107. For ``MODE_OPENPGP`` mode only,
  108. it must be 8 bytes long for encryption
  109. and 10 bytes for decryption (in the latter case, it is
  110. actually the *encrypted* IV which was prefixed to the ciphertext).
  111. If not provided, a random byte string is generated (you must then
  112. read its value with the :attr:`iv` attribute).
  113. * **nonce** (*bytes*, *bytearray*, *memoryview*) --
  114. (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
  115. A value that must never be reused for any other encryption done
  116. with this key.
  117. For ``MODE_EAX`` there are no
  118. restrictions on its length (recommended: **16** bytes).
  119. For ``MODE_CTR``, its length must be in the range **[0..7]**.
  120. If not provided for ``MODE_EAX``, a random byte string is generated (you
  121. can read it back via the ``nonce`` attribute).
  122. * **segment_size** (*integer*) --
  123. (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
  124. are segmented in. It must be a multiple of 8.
  125. If not specified, it will be assumed to be 8.
  126. * **mac_len** : (*integer*) --
  127. (Only ``MODE_EAX``)
  128. Length of the authentication tag, in bytes.
  129. It must be no longer than 8 (default).
  130. * **initial_value** : (*integer*) --
  131. (Only ``MODE_CTR``). The initial value for the counter within
  132. the counter block. By default it is **0**.
  133. :Return: a Triple DES object, of the applicable mode.
  134. """
  135. return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  136. MODE_ECB = 1
  137. MODE_CBC = 2
  138. MODE_CFB = 3
  139. MODE_OFB = 5
  140. MODE_CTR = 6
  141. MODE_OPENPGP = 7
  142. MODE_EAX = 9
  143. # Size of a data block (in bytes)
  144. block_size = 8
  145. # Size of a key (in bytes)
  146. key_size = (16, 24)