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

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

39 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 

25 

26from Crypto.Util._raw_api import ( 

27 SmartPointer, 

28 VoidPointer, 

29 c_size_t, 

30 c_uint8_ptr_len, 

31 c_uint8_ptr_out, 

32 create_output_buffer, 

33 get_raw_buffer, 

34 load_pycryptodome_raw_lib, 

35) 

36from Crypto.Util._typing import Buffer 

37 

38_raw_arc4_lib = load_pycryptodome_raw_lib( 

39 "Crypto.Cipher._ARC4", 

40 """ 

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

42 uint8_t out[], size_t len); 

43 int ARC4_stream_init(uint8_t *key, size_t keylen, 

44 void **pRc4State); 

45 int ARC4_stream_destroy(void *rc4State); 

46 """, 

47) 

48 

49 

50class ARC4Cipher: 

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

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

53 """ 

54 

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

56 """Initialize an ARC4 cipher object 

57 

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

59 

60 if len(key) not in key_size: 

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

62 

63 state = VoidPointer() 

64 key_ptr, key_len = c_uint8_ptr_len(key) 

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

66 if result != 0: 

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

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

69 

70 if drop > 0: 

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

72 # since encrypt and decrypt are actually the same thing 

73 # with ARC4. 

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

75 

76 self.block_size = 1 

77 self.key_size = len(key) 

78 

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

80 """Encrypt a piece of data. 

81 

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

83 :type plaintext: bytes, bytearray, memoryview 

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

85 plaintext. 

86 """ 

87 

88 ciphertext = create_output_buffer(len(plaintext)) 

89 with c_uint8_ptr_out(ciphertext) as ciphertext_ptr: 

90 plaintext_ptr, plaintext_len = c_uint8_ptr_len(plaintext) 

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

92 if len(ciphertext_ptr) != plaintext_len: 

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

94 result = _raw_arc4_lib.ARC4_stream_encrypt( 

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

96 ) 

97 if result: 

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

99 return get_raw_buffer(ciphertext) 

100 

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

102 """Decrypt a piece of data. 

103 

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

105 :type ciphertext: bytes, bytearray, memoryview 

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

107 ciphertext. 

108 """ 

109 

110 try: 

111 return self.encrypt(ciphertext) 

112 except ValueError as e: 

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

114 

115 

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

117 """Create a new ARC4 cipher. 

118 

119 :param key: 

120 The secret key to use in the symmetric cipher. 

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

122 The recommended length is 16 bytes. 

123 :type key: bytes, bytearray, memoryview 

124 

125 :Keyword Arguments: 

126 * *drop* (``integer``) -- 

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

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

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

130 

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

132 

133 :Return: an `ARC4Cipher` object 

134 

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

136 """ 

137 return ARC4Cipher(key, drop) 

138 

139 

140# Size of a data block (in bytes) 

141block_size: int = 1 

142# Size of a key (in bytes) 

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