Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/Crypto/Cipher/ARC4.py: 32%

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

40 statements  

1# 

2# Cipher/ARC4.py : ARC4 

3# 

4# =================================================================== 

5# The contents of this file are dedicated to the public domain. To 

6# the extent that dedication to the public domain is not available, 

7# everyone is granted a worldwide, perpetual, royalty-free, 

8# non-exclusive license to exercise all rights associated with the 

9# contents of this file for any purpose whatsoever. 

10# No rights are reserved. 

11# 

12# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 

13# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 

14# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 

15# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 

16# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 

17# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 

18# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 

19# SOFTWARE. 

20# =================================================================== 

21 

22from __future__ import annotations 

23 

24from collections.abc import Iterable 

25from typing import Union 

26 

27from Crypto.Util._raw_api import ( 

28 SmartPointer, 

29 VoidPointer, 

30 c_size_t, 

31 c_uint8_ptr_len, 

32 c_uint8_ptr_out, 

33 create_output_buffer, 

34 get_raw_buffer, 

35 load_pycryptodome_raw_lib, 

36) 

37 

38Buffer = Union[bytes, bytearray, memoryview] 

39 

40 

41_raw_arc4_lib = load_pycryptodome_raw_lib( 

42 "Crypto.Cipher._ARC4", 

43 """ 

44 int ARC4_stream_encrypt(void *rc4State, const uint8_t in[], 

45 uint8_t out[], size_t len); 

46 int ARC4_stream_init(uint8_t *key, size_t keylen, 

47 void **pRc4State); 

48 int ARC4_stream_destroy(void *rc4State); 

49 """, 

50) 

51 

52 

53class ARC4Cipher: 

54 """ARC4 cipher object. Do not create it directly. Use 

55 :func:`Crypto.Cipher.ARC4.new` instead. 

56 """ 

57 

58 def __init__(self, key: Buffer, drop: int = 0) -> None: 

59 """Initialize an ARC4 cipher object 

60 

61 See also `new()` at the module level.""" 

62 

63 if len(key) not in key_size: 

64 raise ValueError("Incorrect ARC4 key length (%d bytes)" % len(key)) 

65 

66 state = VoidPointer() 

67 key_ptr, key_len = c_uint8_ptr_len(key) 

68 result = _raw_arc4_lib.ARC4_stream_init(key_ptr, c_size_t(key_len), state.address_of()) 

69 if result != 0: 

70 raise ValueError("Error %d while creating the ARC4 cipher" % result) 

71 self._state = SmartPointer(state.get(), _raw_arc4_lib.ARC4_stream_destroy) 

72 

73 if drop > 0: 

74 # This is OK even if the cipher is used for decryption, 

75 # since encrypt and decrypt are actually the same thing 

76 # with ARC4. 

77 self.encrypt(b"\x00" * drop) 

78 

79 self.block_size = 1 

80 self.key_size = len(key) 

81 

82 def encrypt(self, plaintext: Buffer) -> bytes: 

83 """Encrypt a piece of data. 

84 

85 :param plaintext: The data to encrypt, of any size. 

86 :type plaintext: bytes, bytearray, memoryview 

87 :returns: the encrypted byte string, of equal length as the 

88 plaintext. 

89 """ 

90 

91 ciphertext = create_output_buffer(len(plaintext)) 

92 with c_uint8_ptr_out(ciphertext) as ciphertext_ptr: 

93 plaintext_ptr, plaintext_len = c_uint8_ptr_len(plaintext) 

94 # Check the lengths of the buffers that C code gets 

95 if len(ciphertext_ptr) != plaintext_len: 

96 raise ValueError("The plaintext changed length while being encrypted") 

97 result = _raw_arc4_lib.ARC4_stream_encrypt( 

98 self._state.get(), plaintext_ptr, ciphertext_ptr, c_size_t(plaintext_len) 

99 ) 

100 if result: 

101 raise ValueError("Error %d while encrypting with RC4" % result) 

102 return get_raw_buffer(ciphertext) 

103 

104 def decrypt(self, ciphertext: Buffer) -> bytes: 

105 """Decrypt a piece of data. 

106 

107 :param ciphertext: The data to decrypt, of any size. 

108 :type ciphertext: bytes, bytearray, memoryview 

109 :returns: the decrypted byte string, of equal length as the 

110 ciphertext. 

111 """ 

112 

113 try: 

114 return self.encrypt(ciphertext) 

115 except ValueError as e: 

116 raise ValueError(str(e).replace("enc", "dec")) 

117 

118 

119def new(key: Buffer, drop: int = 0) -> ARC4Cipher: 

120 """Create a new ARC4 cipher. 

121 

122 :param key: 

123 The secret key to use in the symmetric cipher. 

124 Its length must be in the range ``[1..256]``. 

125 The recommended length is 16 bytes. 

126 :type key: bytes, bytearray, memoryview 

127 

128 :Keyword Arguments: 

129 * *drop* (``integer``) -- 

130 The amount of bytes to discard from the initial part of the keystream. 

131 In fact, such part has been found to be distinguishable from random 

132 data (while it shouldn't) and also correlated to key. 

133 

134 The recommended value is 3072_ bytes. The default value is 0. 

135 

136 :Return: an `ARC4Cipher` object 

137 

138 .. _3072: http://eprint.iacr.org/2002/067.pdf 

139 """ 

140 return ARC4Cipher(key, drop) 

141 

142 

143# Size of a data block (in bytes) 

144block_size: int = 1 

145# Size of a key (in bytes) 

146key_size: Iterable[int] = range(1, 256 + 1)