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