Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/Crypto/Cipher/ARC4.py: 26%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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# ===================================================================
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)
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 """)
37class ARC4Cipher:
38 """ARC4 cipher object. Do not create it directly. Use
39 :func:`Crypto.Cipher.ARC4.new` instead.
40 """
42 def __init__(self, key, *args, **kwargs):
43 """Initialize an ARC4 cipher object
45 See also `new()` at the module level."""
47 if len(args) > 0:
48 ndrop = args[0]
49 args = args[1:]
50 else:
51 ndrop = kwargs.pop('drop', 0)
53 if len(key) not in key_size:
54 raise ValueError("Incorrect ARC4 key length (%d bytes)" %
55 len(key))
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)
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)
73 self.block_size = 1
74 self.key_size = len(key)
76 def encrypt(self, plaintext):
77 """Encrypt a piece of data.
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 """
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)
94 def decrypt(self, ciphertext):
95 """Decrypt a piece of data.
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 """
103 try:
104 return self.encrypt(ciphertext)
105 except ValueError as e:
106 raise ValueError(str(e).replace("enc", "dec"))
109def new(key, *args, **kwargs):
110 """Create a new ARC4 cipher.
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
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.
124 The recommended value is 3072_ bytes. The default value is 0.
126 :Return: an `ARC4Cipher` object
128 .. _3072: http://eprint.iacr.org/2002/067.pdf
129 """
130 return ARC4Cipher(key, *args, **kwargs)
133# Size of a data block (in bytes)
134block_size = 1
135# Size of a key (in bytes)
136key_size = range(1, 256+1)