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

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

71 statements  

1# 

2# Cipher/mode_ecb.py : ECB mode 

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 

22""" 

23Electronic Code Book (ECB) mode. 

24""" 

25 

26from __future__ import annotations 

27 

28from typing import Any, Optional, Union, overload 

29 

30__all__ = ["EcbMode"] 

31 

32from Crypto.Util._raw_api import ( 

33 SmartPointer, 

34 VoidPointer, 

35 c_size_t, 

36 c_uint8_ptr_len, 

37 c_uint8_ptr_out, 

38 create_output_buffer, 

39 get_raw_buffer, 

40 is_writeable_buffer, 

41 load_pycryptodome_raw_lib, 

42) 

43from Crypto.Util._typing import Buffer 

44 

45raw_ecb_lib = load_pycryptodome_raw_lib( 

46 "Crypto.Cipher._raw_ecb", 

47 """ 

48 int ECB_start_operation(void *cipher, 

49 void **pResult); 

50 int ECB_encrypt(void *ecbState, 

51 const uint8_t *in, 

52 uint8_t *out, 

53 size_t data_len); 

54 int ECB_decrypt(void *ecbState, 

55 const uint8_t *in, 

56 uint8_t *out, 

57 size_t data_len); 

58 int ECB_stop_operation(void *state); 

59 """, 

60) 

61 

62 

63class EcbMode: 

64 """*Electronic Code Book (ECB)*. 

65 

66 This is the simplest encryption mode. Each of the plaintext blocks 

67 is directly encrypted into a ciphertext block, independently of 

68 any other block. 

69 

70 This mode is dangerous because it exposes frequency of symbols 

71 in your plaintext. Other modes (e.g. *CBC*) should be used instead. 

72 

73 See `NIST SP800-38A`_ , Section 6.1. 

74 

75 .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf 

76 """ 

77 

78 def __init__(self, block_cipher: Any) -> None: 

79 """Create a new block cipher, configured in ECB mode. 

80 

81 Args: 

82 block_cipher (C pointer): 

83 A smart pointer to the low-level block cipher instance. 

84 """ 

85 self.block_size = block_cipher.block_size 

86 

87 state = VoidPointer() 

88 result = raw_ecb_lib.ECB_start_operation(block_cipher.get(), state.address_of()) 

89 if result: 

90 raise ValueError("Error %d while instantiating the ECB mode" % result) 

91 

92 # Ensure that object disposal of this Python object will (eventually) 

93 # free the memory allocated by the raw library for the cipher 

94 # mode 

95 self._state = SmartPointer(state.get(), raw_ecb_lib.ECB_stop_operation) 

96 

97 # Memory allocated for the underlying block cipher is now owned 

98 # by the cipher mode 

99 block_cipher.release() 

100 

101 @overload 

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

103 

104 @overload 

105 def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ... 

106 

107 def encrypt( 

108 self, plaintext: Buffer, output: Optional[Union[bytearray, memoryview]] = None 

109 ) -> Optional[bytes]: 

110 """Encrypt data with the key set at initialization. 

111 

112 The data to encrypt can be broken up in two or 

113 more pieces and `encrypt` can be called multiple times. 

114 

115 That is, the statement: 

116 

117 >>> c.encrypt(a) + c.encrypt(b) 

118 

119 is equivalent to: 

120 

121 >>> c.encrypt(a+b) 

122 

123 This function does not add any padding to the plaintext. 

124 

125 Args: 

126 plaintext (bytes/bytearray/memoryview): 

127 The piece of data to encrypt. 

128 The length must be multiple of the cipher block length. 

129 Keyword Args: 

130 output (bytearray/memoryview): 

131 The location where the ciphertext must be written to. 

132 If ``None``, the ciphertext is returned. 

133 Returns: 

134 If ``output`` is ``None``, the ciphertext is returned as ``bytes``. 

135 Otherwise, ``None``. 

136 """ 

137 

138 if output is None: 

139 ciphertext = create_output_buffer(len(plaintext)) 

140 else: 

141 ciphertext = output 

142 

143 if not is_writeable_buffer(output): 

144 raise TypeError("output must be a bytearray or a writeable memoryview") 

145 

146 if len(plaintext) != len(output): 

147 raise ValueError("output must have the same length as the input (%d bytes)" % len(plaintext)) 

148 

149 with c_uint8_ptr_out(ciphertext) as ciphertext_ptr: 

150 plaintext_ptr, plaintext_len = c_uint8_ptr_len(plaintext) 

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

152 if len(ciphertext_ptr) != plaintext_len: 

153 raise ValueError("output must have the same length as the input (%d bytes)" % plaintext_len) 

154 result = raw_ecb_lib.ECB_encrypt( 

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

156 ) 

157 if result: 

158 if result == 3: 

159 raise ValueError("Data must be aligned to block boundary in ECB mode") 

160 raise ValueError("Error %d while encrypting in ECB mode" % result) 

161 

162 if output is None: 

163 return get_raw_buffer(ciphertext) 

164 else: 

165 return None 

166 

167 @overload 

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

169 

170 @overload 

171 def decrypt(self, ciphertext: Buffer, output: Union[bytearray, memoryview]) -> None: ... 

172 

173 def decrypt( 

174 self, ciphertext: Buffer, output: Optional[Union[bytearray, memoryview]] = None 

175 ) -> Optional[bytes]: 

176 """Decrypt data with the key set at initialization. 

177 

178 The data to decrypt can be broken up in two or 

179 more pieces and `decrypt` can be called multiple times. 

180 

181 That is, the statement: 

182 

183 >>> c.decrypt(a) + c.decrypt(b) 

184 

185 is equivalent to: 

186 

187 >>> c.decrypt(a+b) 

188 

189 This function does not remove any padding from the plaintext. 

190 

191 Args: 

192 ciphertext (bytes/bytearray/memoryview): 

193 The piece of data to decrypt. 

194 The length must be multiple of the cipher block length. 

195 Keyword Args: 

196 output (bytearray/memoryview): 

197 The location where the plaintext must be written to. 

198 If ``None``, the plaintext is returned. 

199 Returns: 

200 If ``output`` is ``None``, the plaintext is returned as ``bytes``. 

201 Otherwise, ``None``. 

202 """ 

203 

204 if output is None: 

205 plaintext = create_output_buffer(len(ciphertext)) 

206 else: 

207 plaintext = output 

208 

209 if not is_writeable_buffer(output): 

210 raise TypeError("output must be a bytearray or a writeable memoryview") 

211 

212 if len(ciphertext) != len(output): 

213 raise ValueError("output must have the same length as the input (%d bytes)" % len(plaintext)) 

214 

215 with c_uint8_ptr_out(plaintext) as plaintext_ptr: 

216 ciphertext_ptr, ciphertext_len = c_uint8_ptr_len(ciphertext) 

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

218 if len(plaintext_ptr) != ciphertext_len: 

219 raise ValueError("output must have the same length as the input (%d bytes)" % ciphertext_len) 

220 result = raw_ecb_lib.ECB_decrypt( 

221 self._state.get(), ciphertext_ptr, plaintext_ptr, c_size_t(ciphertext_len) 

222 ) 

223 if result: 

224 if result == 3: 

225 raise ValueError("Data must be aligned to block boundary in ECB mode") 

226 raise ValueError("Error %d while decrypting in ECB mode" % result) 

227 

228 if output is None: 

229 return get_raw_buffer(plaintext) 

230 else: 

231 return None 

232 

233 

234def _create_ecb_cipher(factory, **kwargs): 

235 """Instantiate a cipher object that performs ECB encryption/decryption. 

236 

237 Args: 

238 factory (module): 

239 The underlying block cipher, a module from ``Crypto.Cipher``. 

240 

241 All keywords are passed to the underlying block cipher. 

242 See the relevant documentation for details (at least ``key`` will need 

243 to be present""" 

244 

245 cipher_state = factory._create_base_cipher(kwargs) 

246 cipher_state.block_size = factory.block_size 

247 if kwargs: 

248 raise TypeError("Unknown parameters for ECB: %s" % str(kwargs)) 

249 return EcbMode(cipher_state)