ARC4.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/ARC4.py : ARC4
  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. from tls.Crypto.Util.py3compat import b
  23. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
  24. create_string_buffer, get_raw_buffer,
  25. SmartPointer, c_size_t, c_uint8_ptr)
  26. _raw_arc4_lib = load_pycryptodome_raw_lib("Crypto.Cipher._ARC4", """
  27. int ARC4_stream_encrypt(void *rc4State, const uint8_t in[],
  28. uint8_t out[], size_t len);
  29. int ARC4_stream_init(uint8_t *key, size_t keylen,
  30. void **pRc4State);
  31. int ARC4_stream_destroy(void *rc4State);
  32. """)
  33. class ARC4Cipher:
  34. """ARC4 cipher object. Do not create it directly. Use
  35. :func:`Crypto.Cipher.ARC4.new` instead.
  36. """
  37. def __init__(self, key, *args, **kwargs):
  38. """Initialize an ARC4 cipher object
  39. See also `new()` at the module level."""
  40. if len(args) > 0:
  41. ndrop = args[0]
  42. args = args[1:]
  43. else:
  44. ndrop = kwargs.pop('drop', 0)
  45. if len(key) not in key_size:
  46. raise ValueError("Incorrect ARC4 key length (%d bytes)" %
  47. len(key))
  48. self._state = VoidPointer()
  49. result = _raw_arc4_lib.ARC4_stream_init(c_uint8_ptr(key),
  50. c_size_t(len(key)),
  51. self._state.address_of())
  52. if result != 0:
  53. raise ValueError("Error %d while creating the ARC4 cipher"
  54. % result)
  55. self._state = SmartPointer(self._state.get(),
  56. _raw_arc4_lib.ARC4_stream_destroy)
  57. if ndrop > 0:
  58. # This is OK even if the cipher is used for decryption,
  59. # since encrypt and decrypt are actually the same thing
  60. # with ARC4.
  61. self.encrypt(b'\x00' * ndrop)
  62. self.block_size = 1
  63. self.key_size = len(key)
  64. def encrypt(self, plaintext):
  65. """Encrypt a piece of data.
  66. :param plaintext: The data to encrypt, of any size.
  67. :type plaintext: bytes, bytearray, memoryview
  68. :returns: the encrypted byte string, of equal length as the
  69. plaintext.
  70. """
  71. ciphertext = create_string_buffer(len(plaintext))
  72. result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(),
  73. c_uint8_ptr(plaintext),
  74. ciphertext,
  75. c_size_t(len(plaintext)))
  76. if result:
  77. raise ValueError("Error %d while encrypting with RC4" % result)
  78. return get_raw_buffer(ciphertext)
  79. def decrypt(self, ciphertext):
  80. """Decrypt a piece of data.
  81. :param ciphertext: The data to decrypt, of any size.
  82. :type ciphertext: bytes, bytearray, memoryview
  83. :returns: the decrypted byte string, of equal length as the
  84. ciphertext.
  85. """
  86. try:
  87. return self.encrypt(ciphertext)
  88. except ValueError as e:
  89. raise ValueError(str(e).replace("enc", "dec"))
  90. def new(key, *args, **kwargs):
  91. """Create a new ARC4 cipher.
  92. :param key:
  93. The secret key to use in the symmetric cipher.
  94. Its length must be in the range ``[5..256]``.
  95. The recommended length is 16 bytes.
  96. :type key: bytes, bytearray, memoryview
  97. :Keyword Arguments:
  98. * *drop* (``integer``) --
  99. The amount of bytes to discard from the initial part of the keystream.
  100. In fact, such part has been found to be distinguishable from random
  101. data (while it shouldn't) and also correlated to key.
  102. The recommended value is 3072_ bytes. The default value is 0.
  103. :Return: an `ARC4Cipher` object
  104. .. _3072: http://eprint.iacr.org/2002/067.pdf
  105. """
  106. return ARC4Cipher(key, *args, **kwargs)
  107. # Size of a data block (in bytes)
  108. block_size = 1
  109. # Size of a key (in bytes)
  110. key_size = range(5, 256+1)