geored commited on
Commit
0a06673
1 Parent(s): 6091007

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +15 -0
  2. app.py +1 -1
  3. gtm/bin/flask +8 -0
  4. gtm/bin/markdown2 +8 -0
  5. gtm/lib/python3.12/site-packages/Crypto/Cipher/AES.py +234 -0
  6. gtm/lib/python3.12/site-packages/Crypto/Cipher/AES.pyi +156 -0
  7. gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC2.py +175 -0
  8. gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC2.pyi +35 -0
  9. gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC4.py +136 -0
  10. gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC4.pyi +16 -0
  11. gtm/lib/python3.12/site-packages/Crypto/Cipher/Blowfish.py +159 -0
  12. gtm/lib/python3.12/site-packages/Crypto/Cipher/Blowfish.pyi +35 -0
  13. gtm/lib/python3.12/site-packages/Crypto/Cipher/CAST.py +159 -0
  14. gtm/lib/python3.12/site-packages/Crypto/Cipher/CAST.pyi +35 -0
  15. gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20.py +287 -0
  16. gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20.pyi +25 -0
  17. gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20_Poly1305.py +336 -0
  18. gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20_Poly1305.pyi +28 -0
  19. gtm/lib/python3.12/site-packages/Crypto/Cipher/DES.py +158 -0
  20. gtm/lib/python3.12/site-packages/Crypto/Cipher/DES.pyi +35 -0
  21. gtm/lib/python3.12/site-packages/Crypto/Cipher/DES3.py +187 -0
  22. gtm/lib/python3.12/site-packages/Crypto/Cipher/DES3.pyi +37 -0
  23. gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_OAEP.py +231 -0
  24. gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_OAEP.pyi +35 -0
  25. gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_v1_5.py +189 -0
  26. gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_v1_5.pyi +20 -0
  27. gtm/lib/python3.12/site-packages/Crypto/Cipher/Salsa20.py +167 -0
  28. gtm/lib/python3.12/site-packages/Crypto/Cipher/Salsa20.pyi +26 -0
  29. gtm/lib/python3.12/site-packages/Crypto/Cipher/_ARC4.abi3.so +0 -0
  30. gtm/lib/python3.12/site-packages/Crypto/Cipher/_EKSBlowfish.py +131 -0
  31. gtm/lib/python3.12/site-packages/Crypto/Cipher/_EKSBlowfish.pyi +15 -0
  32. gtm/lib/python3.12/site-packages/Crypto/Cipher/_Salsa20.abi3.so +0 -0
  33. gtm/lib/python3.12/site-packages/Crypto/Cipher/__init__.py +79 -0
  34. gtm/lib/python3.12/site-packages/Crypto/Cipher/__init__.pyi +0 -0
  35. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/AES.cpython-312.pyc +0 -0
  36. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ARC2.cpython-312.pyc +0 -0
  37. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ARC4.cpython-312.pyc +0 -0
  38. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/Blowfish.cpython-312.pyc +0 -0
  39. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/CAST.cpython-312.pyc +0 -0
  40. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ChaCha20.cpython-312.pyc +0 -0
  41. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ChaCha20_Poly1305.cpython-312.pyc +0 -0
  42. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/DES.cpython-312.pyc +0 -0
  43. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/DES3.cpython-312.pyc +0 -0
  44. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/PKCS1_OAEP.cpython-312.pyc +0 -0
  45. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/PKCS1_v1_5.cpython-312.pyc +0 -0
  46. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/Salsa20.cpython-312.pyc +0 -0
  47. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/_EKSBlowfish.cpython-312.pyc +0 -0
  48. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/__init__.cpython-312.pyc +0 -0
  49. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/_mode_cbc.cpython-312.pyc +0 -0
  50. gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/_mode_ccm.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -64,3 +64,18 @@ gtm/lib/python3.12/site-packages/torch/lib/libtorch_cpu.dylib filter=lfs diff=lf
64
  gtm/lib/python3.12/site-packages/torch/lib/libtorch_python.dylib filter=lfs diff=lfs merge=lfs -text
65
  gtm/lib/python3.12/site-packages/torchvision/.dylibs/libc++.1.0.dylib filter=lfs diff=lfs merge=lfs -text
66
  gtm/lib/python3.12/site-packages/torchvision/_C.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  gtm/lib/python3.12/site-packages/torch/lib/libtorch_python.dylib filter=lfs diff=lfs merge=lfs -text
65
  gtm/lib/python3.12/site-packages/torchvision/.dylibs/libc++.1.0.dylib filter=lfs diff=lfs merge=lfs -text
66
  gtm/lib/python3.12/site-packages/torchvision/_C.so filter=lfs diff=lfs merge=lfs -text
67
+ gtm/lib/python3.12/site-packages/bcrypt/_bcrypt.abi3.so filter=lfs diff=lfs merge=lfs -text
68
+ gtm/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
69
+ gtm/lib/python3.12/site-packages/nacl/_sodium.abi3.so filter=lfs diff=lfs merge=lfs -text
70
+ gtm/lib/python3.12/site-packages/scipy/.dylibs/libgfortran.5.dylib filter=lfs diff=lfs merge=lfs -text
71
+ gtm/lib/python3.12/site-packages/scipy/.dylibs/libopenblas.0.dylib filter=lfs diff=lfs merge=lfs -text
72
+ gtm/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
73
+ gtm/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
74
+ gtm/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
75
+ gtm/lib/python3.12/site-packages/scipy/misc/face.dat filter=lfs diff=lfs merge=lfs -text
76
+ gtm/lib/python3.12/site-packages/scipy/optimize/_highs/_highs_wrapper.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
77
+ gtm/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
78
+ gtm/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
79
+ gtm/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
80
+ gtm/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
81
+ gtm/lib/python3.12/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -35,7 +35,7 @@ iface = gr.Interface(
35
  outputs=gr.outputs.Textbox(label="Output Text"),
36
  title="Chat Interface",
37
  description="Enter text and get a response using the LLM model",
38
- live=True # Enable live updates
39
  )
40
 
41
  # Launch the interface using Hugging Face Spaces
 
35
  outputs=gr.outputs.Textbox(label="Output Text"),
36
  title="Chat Interface",
37
  description="Enter text and get a response using the LLM model",
38
+ # live=True # Enable live updates
39
  )
40
 
41
  # Launch the interface using Hugging Face Spaces
gtm/bin/flask ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/gorgigeorgievski/code/ai/gtmio/gtm/bin/python3.12
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from flask.cli import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
gtm/bin/markdown2 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/gorgigeorgievski/code/ai/gtmio/gtm/bin/python3.12
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from markdown2 import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
gtm/lib/python3.12/site-packages/Crypto/Cipher/AES.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/AES.py : AES
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
+
23
+ import sys
24
+
25
+ from Crypto.Cipher import _create_cipher
26
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
27
+ VoidPointer, SmartPointer,
28
+ c_size_t, c_uint8_ptr)
29
+
30
+ from Crypto.Util import _cpu_features
31
+ from Crypto.Random import get_random_bytes
32
+
33
+ MODE_ECB = 1 #: Electronic Code Book (:ref:`ecb_mode`)
34
+ MODE_CBC = 2 #: Cipher-Block Chaining (:ref:`cbc_mode`)
35
+ MODE_CFB = 3 #: Cipher Feedback (:ref:`cfb_mode`)
36
+ MODE_OFB = 5 #: Output Feedback (:ref:`ofb_mode`)
37
+ MODE_CTR = 6 #: Counter mode (:ref:`ctr_mode`)
38
+ MODE_OPENPGP = 7 #: OpenPGP mode (:ref:`openpgp_mode`)
39
+ MODE_CCM = 8 #: Counter with CBC-MAC (:ref:`ccm_mode`)
40
+ MODE_EAX = 9 #: :ref:`eax_mode`
41
+ MODE_SIV = 10 #: Synthetic Initialization Vector (:ref:`siv_mode`)
42
+ MODE_GCM = 11 #: Galois Counter Mode (:ref:`gcm_mode`)
43
+ MODE_OCB = 12 #: Offset Code Book (:ref:`ocb_mode`)
44
+
45
+
46
+ _cproto = """
47
+ int AES_start_operation(const uint8_t key[],
48
+ size_t key_len,
49
+ void **pResult);
50
+ int AES_encrypt(const void *state,
51
+ const uint8_t *in,
52
+ uint8_t *out,
53
+ size_t data_len);
54
+ int AES_decrypt(const void *state,
55
+ const uint8_t *in,
56
+ uint8_t *out,
57
+ size_t data_len);
58
+ int AES_stop_operation(void *state);
59
+ """
60
+
61
+
62
+ # Load portable AES
63
+ _raw_aes_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_aes",
64
+ _cproto)
65
+
66
+ # Try to load AES with AES NI instructions
67
+ try:
68
+ _raw_aesni_lib = None
69
+ if _cpu_features.have_aes_ni():
70
+ _raw_aesni_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_aesni",
71
+ _cproto.replace("AES",
72
+ "AESNI"))
73
+ # _raw_aesni may not have been compiled in
74
+ except OSError:
75
+ pass
76
+
77
+
78
+ def _create_base_cipher(dict_parameters):
79
+ """This method instantiates and returns a handle to a low-level
80
+ base cipher. It will absorb named parameters in the process."""
81
+
82
+ use_aesni = dict_parameters.pop("use_aesni", True)
83
+
84
+ try:
85
+ key = dict_parameters.pop("key")
86
+ except KeyError:
87
+ raise TypeError("Missing 'key' parameter")
88
+
89
+ if len(key) not in key_size:
90
+ raise ValueError("Incorrect AES key length (%d bytes)" % len(key))
91
+
92
+ if use_aesni and _raw_aesni_lib:
93
+ start_operation = _raw_aesni_lib.AESNI_start_operation
94
+ stop_operation = _raw_aesni_lib.AESNI_stop_operation
95
+ else:
96
+ start_operation = _raw_aes_lib.AES_start_operation
97
+ stop_operation = _raw_aes_lib.AES_stop_operation
98
+
99
+ cipher = VoidPointer()
100
+ result = start_operation(c_uint8_ptr(key),
101
+ c_size_t(len(key)),
102
+ cipher.address_of())
103
+ if result:
104
+ raise ValueError("Error %X while instantiating the AES cipher"
105
+ % result)
106
+ return SmartPointer(cipher.get(), stop_operation)
107
+
108
+
109
+ def _derive_Poly1305_key_pair(key, nonce):
110
+ """Derive a tuple (r, s, nonce) for a Poly1305 MAC.
111
+
112
+ If nonce is ``None``, a new 16-byte nonce is generated.
113
+ """
114
+
115
+ if len(key) != 32:
116
+ raise ValueError("Poly1305 with AES requires a 32-byte key")
117
+
118
+ if nonce is None:
119
+ nonce = get_random_bytes(16)
120
+ elif len(nonce) != 16:
121
+ raise ValueError("Poly1305 with AES requires a 16-byte nonce")
122
+
123
+ s = new(key[:16], MODE_ECB).encrypt(nonce)
124
+ return key[16:], s, nonce
125
+
126
+
127
+ def new(key, mode, *args, **kwargs):
128
+ """Create a new AES cipher.
129
+
130
+ Args:
131
+ key(bytes/bytearray/memoryview):
132
+ The secret key to use in the symmetric cipher.
133
+
134
+ It must be 16 (*AES-128)*, 24 (*AES-192*) or 32 (*AES-256*) bytes long.
135
+
136
+ For ``MODE_SIV`` only, it doubles to 32, 48, or 64 bytes.
137
+ mode (a ``MODE_*`` constant):
138
+ The chaining mode to use for encryption or decryption.
139
+ If in doubt, use ``MODE_EAX``.
140
+
141
+ Keyword Args:
142
+ iv (bytes/bytearray/memoryview):
143
+ (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
144
+ and ``MODE_OPENPGP`` modes).
145
+
146
+ The initialization vector to use for encryption or decryption.
147
+
148
+ For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 16 bytes long.
149
+
150
+ For ``MODE_OPENPGP`` mode only,
151
+ it must be 16 bytes long for encryption
152
+ and 18 bytes for decryption (in the latter case, it is
153
+ actually the *encrypted* IV which was prefixed to the ciphertext).
154
+
155
+ If not provided, a random byte string is generated (you must then
156
+ read its value with the :attr:`iv` attribute).
157
+
158
+ nonce (bytes/bytearray/memoryview):
159
+ (Only applicable for ``MODE_CCM``, ``MODE_EAX``, ``MODE_GCM``,
160
+ ``MODE_SIV``, ``MODE_OCB``, and ``MODE_CTR``).
161
+
162
+ A value that must never be reused for any other encryption done
163
+ with this key (except possibly for ``MODE_SIV``, see below).
164
+
165
+ For ``MODE_EAX``, ``MODE_GCM`` and ``MODE_SIV`` there are no
166
+ restrictions on its length (recommended: **16** bytes).
167
+
168
+ For ``MODE_CCM``, its length must be in the range **[7..13]**.
169
+ Bear in mind that with CCM there is a trade-off between nonce
170
+ length and maximum message size. Recommendation: **11** bytes.
171
+
172
+ For ``MODE_OCB``, its length must be in the range **[1..15]**
173
+ (recommended: **15**).
174
+
175
+ For ``MODE_CTR``, its length must be in the range **[0..15]**
176
+ (recommended: **8**).
177
+
178
+ For ``MODE_SIV``, the nonce is optional, if it is not specified,
179
+ then no nonce is being used, which renders the encryption
180
+ deterministic.
181
+
182
+ If not provided, for modes other than ``MODE_SIV``, a random
183
+ byte string of the recommended length is used (you must then
184
+ read its value with the :attr:`nonce` attribute).
185
+
186
+ segment_size (integer):
187
+ (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
188
+ are segmented in. It must be a multiple of 8.
189
+ If not specified, it will be assumed to be 8.
190
+
191
+ mac_len (integer):
192
+ (Only ``MODE_EAX``, ``MODE_GCM``, ``MODE_OCB``, ``MODE_CCM``)
193
+ Length of the authentication tag, in bytes.
194
+
195
+ It must be even and in the range **[4..16]**.
196
+ The recommended value (and the default, if not specified) is **16**.
197
+
198
+ msg_len (integer):
199
+ (Only ``MODE_CCM``). Length of the message to (de)cipher.
200
+ If not specified, ``encrypt`` must be called with the entire message.
201
+ Similarly, ``decrypt`` can only be called once.
202
+
203
+ assoc_len (integer):
204
+ (Only ``MODE_CCM``). Length of the associated data.
205
+ If not specified, all associated data is buffered internally,
206
+ which may represent a problem for very large messages.
207
+
208
+ initial_value (integer or bytes/bytearray/memoryview):
209
+ (Only ``MODE_CTR``).
210
+ The initial value for the counter. If not present, the cipher will
211
+ start counting from 0. The value is incremented by one for each block.
212
+ The counter number is encoded in big endian mode.
213
+
214
+ counter (object):
215
+ (Only ``MODE_CTR``).
216
+ Instance of ``Crypto.Util.Counter``, which allows full customization
217
+ of the counter block. This parameter is incompatible to both ``nonce``
218
+ and ``initial_value``.
219
+
220
+ use_aesni: (boolean):
221
+ Use Intel AES-NI hardware extensions (default: use if available).
222
+
223
+ Returns:
224
+ an AES object, of the applicable mode.
225
+ """
226
+
227
+ kwargs["add_aes_modes"] = True
228
+ return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
229
+
230
+
231
+ # Size of a data block (in bytes)
232
+ block_size = 16
233
+ # Size of a key (in bytes)
234
+ key_size = (16, 24, 32)
gtm/lib/python3.12/site-packages/Crypto/Cipher/AES.pyi ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, Tuple, Union, overload
2
+ from typing_extensions import Literal
3
+
4
+ Buffer=bytes|bytearray|memoryview
5
+
6
+ from Crypto.Cipher._mode_ecb import EcbMode
7
+ from Crypto.Cipher._mode_cbc import CbcMode
8
+ from Crypto.Cipher._mode_cfb import CfbMode
9
+ from Crypto.Cipher._mode_ofb import OfbMode
10
+ from Crypto.Cipher._mode_ctr import CtrMode
11
+ from Crypto.Cipher._mode_openpgp import OpenPgpMode
12
+ from Crypto.Cipher._mode_ccm import CcmMode
13
+ from Crypto.Cipher._mode_eax import EaxMode
14
+ from Crypto.Cipher._mode_gcm import GcmMode
15
+ from Crypto.Cipher._mode_siv import SivMode
16
+ from Crypto.Cipher._mode_ocb import OcbMode
17
+
18
+ MODE_ECB: Literal[1]
19
+ MODE_CBC: Literal[2]
20
+ MODE_CFB: Literal[3]
21
+ MODE_OFB: Literal[5]
22
+ MODE_CTR: Literal[6]
23
+ MODE_OPENPGP: Literal[7]
24
+ MODE_CCM: Literal[8]
25
+ MODE_EAX: Literal[9]
26
+ MODE_SIV: Literal[10]
27
+ MODE_GCM: Literal[11]
28
+ MODE_OCB: Literal[12]
29
+
30
+ # MODE_ECB
31
+ @overload
32
+ def new(key: Buffer,
33
+ mode: Literal[1],
34
+ use_aesni : bool = ...) -> \
35
+ EcbMode: ...
36
+
37
+ # MODE_CBC
38
+ @overload
39
+ def new(key: Buffer,
40
+ mode: Literal[2],
41
+ iv : Optional[Buffer] = ...,
42
+ use_aesni : bool = ...) -> \
43
+ CbcMode: ...
44
+
45
+ @overload
46
+ def new(key: Buffer,
47
+ mode: Literal[2],
48
+ IV : Optional[Buffer] = ...,
49
+ use_aesni : bool = ...) -> \
50
+ CbcMode: ...
51
+
52
+ # MODE_CFB
53
+ @overload
54
+ def new(key: Buffer,
55
+ mode: Literal[3],
56
+ iv : Optional[Buffer] = ...,
57
+ segment_size : int = ...,
58
+ use_aesni : bool = ...) -> \
59
+ CfbMode: ...
60
+
61
+ @overload
62
+ def new(key: Buffer,
63
+ mode: Literal[3],
64
+ IV : Optional[Buffer] = ...,
65
+ segment_size : int = ...,
66
+ use_aesni : bool = ...) -> \
67
+ CfbMode: ...
68
+
69
+ # MODE_OFB
70
+ @overload
71
+ def new(key: Buffer,
72
+ mode: Literal[5],
73
+ iv : Optional[Buffer] = ...,
74
+ use_aesni : bool = ...) -> \
75
+ OfbMode: ...
76
+
77
+ @overload
78
+ def new(key: Buffer,
79
+ mode: Literal[5],
80
+ IV : Optional[Buffer] = ...,
81
+ use_aesni : bool = ...) -> \
82
+ OfbMode: ...
83
+
84
+ # MODE_CTR
85
+ @overload
86
+ def new(key: Buffer,
87
+ mode: Literal[6],
88
+ nonce : Optional[Buffer] = ...,
89
+ initial_value : Union[int, Buffer] = ...,
90
+ counter : Dict = ...,
91
+ use_aesni : bool = ...) -> \
92
+ CtrMode: ...
93
+
94
+ # MODE_OPENPGP
95
+ @overload
96
+ def new(key: Buffer,
97
+ mode: Literal[7],
98
+ iv : Optional[Buffer] = ...,
99
+ use_aesni : bool = ...) -> \
100
+ OpenPgpMode: ...
101
+
102
+ @overload
103
+ def new(key: Buffer,
104
+ mode: Literal[7],
105
+ IV : Optional[Buffer] = ...,
106
+ use_aesni : bool = ...) -> \
107
+ OpenPgpMode: ...
108
+
109
+ # MODE_CCM
110
+ @overload
111
+ def new(key: Buffer,
112
+ mode: Literal[8],
113
+ nonce : Optional[Buffer] = ...,
114
+ mac_len : int = ...,
115
+ assoc_len : int = ...,
116
+ use_aesni : bool = ...) -> \
117
+ CcmMode: ...
118
+
119
+ # MODE_EAX
120
+ @overload
121
+ def new(key: Buffer,
122
+ mode: Literal[9],
123
+ nonce : Optional[Buffer] = ...,
124
+ mac_len : int = ...,
125
+ use_aesni : bool = ...) -> \
126
+ EaxMode: ...
127
+
128
+ # MODE_GCM
129
+ @overload
130
+ def new(key: Buffer,
131
+ mode: Literal[10],
132
+ nonce : Optional[Buffer] = ...,
133
+ use_aesni : bool = ...) -> \
134
+ SivMode: ...
135
+
136
+ # MODE_SIV
137
+ @overload
138
+ def new(key: Buffer,
139
+ mode: Literal[11],
140
+ nonce : Optional[Buffer] = ...,
141
+ mac_len : int = ...,
142
+ use_aesni : bool = ...) -> \
143
+ GcmMode: ...
144
+
145
+ # MODE_OCB
146
+ @overload
147
+ def new(key: Buffer,
148
+ mode: Literal[12],
149
+ nonce : Optional[Buffer] = ...,
150
+ mac_len : int = ...,
151
+ use_aesni : bool = ...) -> \
152
+ OcbMode: ...
153
+
154
+
155
+ block_size: int
156
+ key_size: Tuple[int, int, int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC2.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/ARC2.py : ARC2.py
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
+ """
23
+ Module's constants for the modes of operation supported with ARC2:
24
+
25
+ :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
26
+ :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
27
+ :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
28
+ :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
29
+ :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
30
+ :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
31
+ :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
32
+ """
33
+
34
+ import sys
35
+
36
+ from Crypto.Cipher import _create_cipher
37
+ from Crypto.Util.py3compat import byte_string
38
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
39
+ VoidPointer, SmartPointer,
40
+ c_size_t, c_uint8_ptr)
41
+
42
+ _raw_arc2_lib = load_pycryptodome_raw_lib(
43
+ "Crypto.Cipher._raw_arc2",
44
+ """
45
+ int ARC2_start_operation(const uint8_t key[],
46
+ size_t key_len,
47
+ size_t effective_key_len,
48
+ void **pResult);
49
+ int ARC2_encrypt(const void *state,
50
+ const uint8_t *in,
51
+ uint8_t *out,
52
+ size_t data_len);
53
+ int ARC2_decrypt(const void *state,
54
+ const uint8_t *in,
55
+ uint8_t *out,
56
+ size_t data_len);
57
+ int ARC2_stop_operation(void *state);
58
+ """
59
+ )
60
+
61
+
62
+ def _create_base_cipher(dict_parameters):
63
+ """This method instantiates and returns a handle to a low-level
64
+ base cipher. It will absorb named parameters in the process."""
65
+
66
+ try:
67
+ key = dict_parameters.pop("key")
68
+ except KeyError:
69
+ raise TypeError("Missing 'key' parameter")
70
+
71
+ effective_keylen = dict_parameters.pop("effective_keylen", 1024)
72
+
73
+ if len(key) not in key_size:
74
+ raise ValueError("Incorrect ARC2 key length (%d bytes)" % len(key))
75
+
76
+ if not (40 <= effective_keylen <= 1024):
77
+ raise ValueError("'effective_key_len' must be at least 40 and no larger than 1024 "
78
+ "(not %d)" % effective_keylen)
79
+
80
+ start_operation = _raw_arc2_lib.ARC2_start_operation
81
+ stop_operation = _raw_arc2_lib.ARC2_stop_operation
82
+
83
+ cipher = VoidPointer()
84
+ result = start_operation(c_uint8_ptr(key),
85
+ c_size_t(len(key)),
86
+ c_size_t(effective_keylen),
87
+ cipher.address_of())
88
+ if result:
89
+ raise ValueError("Error %X while instantiating the ARC2 cipher"
90
+ % result)
91
+
92
+ return SmartPointer(cipher.get(), stop_operation)
93
+
94
+
95
+ def new(key, mode, *args, **kwargs):
96
+ """Create a new RC2 cipher.
97
+
98
+ :param key:
99
+ The secret key to use in the symmetric cipher.
100
+ Its length can vary from 5 to 128 bytes; the actual search space
101
+ (and the cipher strength) can be reduced with the ``effective_keylen`` parameter.
102
+ :type key: bytes, bytearray, memoryview
103
+
104
+ :param mode:
105
+ The chaining mode to use for encryption or decryption.
106
+ :type mode: One of the supported ``MODE_*`` constants
107
+
108
+ :Keyword Arguments:
109
+ * **iv** (*bytes*, *bytearray*, *memoryview*) --
110
+ (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
111
+ and ``MODE_OPENPGP`` modes).
112
+
113
+ The initialization vector to use for encryption or decryption.
114
+
115
+ For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
116
+
117
+ For ``MODE_OPENPGP`` mode only,
118
+ it must be 8 bytes long for encryption
119
+ and 10 bytes for decryption (in the latter case, it is
120
+ actually the *encrypted* IV which was prefixed to the ciphertext).
121
+
122
+ If not provided, a random byte string is generated (you must then
123
+ read its value with the :attr:`iv` attribute).
124
+
125
+ * **nonce** (*bytes*, *bytearray*, *memoryview*) --
126
+ (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
127
+
128
+ A value that must never be reused for any other encryption done
129
+ with this key.
130
+
131
+ For ``MODE_EAX`` there are no
132
+ restrictions on its length (recommended: **16** bytes).
133
+
134
+ For ``MODE_CTR``, its length must be in the range **[0..7]**.
135
+
136
+ If not provided for ``MODE_EAX``, a random byte string is generated (you
137
+ can read it back via the ``nonce`` attribute).
138
+
139
+ * **effective_keylen** (*integer*) --
140
+ Optional. Maximum strength in bits of the actual key used by the ARC2 algorithm.
141
+ If the supplied ``key`` parameter is longer (in bits) of the value specified
142
+ here, it will be weakened to match it.
143
+ If not specified, no limitation is applied.
144
+
145
+ * **segment_size** (*integer*) --
146
+ (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
147
+ are segmented in. It must be a multiple of 8.
148
+ If not specified, it will be assumed to be 8.
149
+
150
+ * **mac_len** : (*integer*) --
151
+ (Only ``MODE_EAX``)
152
+ Length of the authentication tag, in bytes.
153
+ It must be no longer than 8 (default).
154
+
155
+ * **initial_value** : (*integer*) --
156
+ (Only ``MODE_CTR``). The initial value for the counter within
157
+ the counter block. By default it is **0**.
158
+
159
+ :Return: an ARC2 object, of the applicable mode.
160
+ """
161
+
162
+ return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
163
+
164
+ MODE_ECB = 1
165
+ MODE_CBC = 2
166
+ MODE_CFB = 3
167
+ MODE_OFB = 5
168
+ MODE_CTR = 6
169
+ MODE_OPENPGP = 7
170
+ MODE_EAX = 9
171
+
172
+ # Size of a data block (in bytes)
173
+ block_size = 8
174
+ # Size of a key (in bytes)
175
+ key_size = range(5, 128 + 1)
gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC2.pyi ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict, Iterable, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ from Crypto.Cipher._mode_ecb import EcbMode
6
+ from Crypto.Cipher._mode_cbc import CbcMode
7
+ from Crypto.Cipher._mode_cfb import CfbMode
8
+ from Crypto.Cipher._mode_ofb import OfbMode
9
+ from Crypto.Cipher._mode_ctr import CtrMode
10
+ from Crypto.Cipher._mode_openpgp import OpenPgpMode
11
+ from Crypto.Cipher._mode_eax import EaxMode
12
+
13
+ ARC2Mode = int
14
+
15
+ MODE_ECB: ARC2Mode
16
+ MODE_CBC: ARC2Mode
17
+ MODE_CFB: ARC2Mode
18
+ MODE_OFB: ARC2Mode
19
+ MODE_CTR: ARC2Mode
20
+ MODE_OPENPGP: ARC2Mode
21
+ MODE_EAX: ARC2Mode
22
+
23
+ def new(key: Buffer,
24
+ mode: ARC2Mode,
25
+ iv : Optional[Buffer] = ...,
26
+ IV : Optional[Buffer] = ...,
27
+ nonce : Optional[Buffer] = ...,
28
+ segment_size : int = ...,
29
+ mac_len : int = ...,
30
+ initial_value : Union[int, Buffer] = ...,
31
+ counter : Dict = ...) -> \
32
+ Union[EcbMode, CbcMode, CfbMode, OfbMode, CtrMode, OpenPgpMode]: ...
33
+
34
+ block_size: int
35
+ key_size: Iterable[int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC4.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
23
+ from 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
+
37
+ class 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
+
109
+ def 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)
134
+ block_size = 1
135
+ # Size of a key (in bytes)
136
+ key_size = range(1, 256+1)
gtm/lib/python3.12/site-packages/Crypto/Cipher/ARC4.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Union, Iterable
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ class ARC4Cipher:
6
+ block_size: int
7
+ key_size: int
8
+
9
+ def __init__(self, key: Buffer, *args: Any, **kwargs: Any) -> None: ...
10
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
11
+ def decrypt(self, ciphertext: Buffer) -> bytes: ...
12
+
13
+ def new(key: Buffer, drop : int = ...) -> ARC4Cipher: ...
14
+
15
+ block_size: int
16
+ key_size: Iterable[int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/Blowfish.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/Blowfish.py : Blowfish
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
+ """
23
+ Module's constants for the modes of operation supported with Blowfish:
24
+
25
+ :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
26
+ :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
27
+ :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
28
+ :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
29
+ :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
30
+ :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
31
+ :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
32
+ """
33
+
34
+ import sys
35
+
36
+ from Crypto.Cipher import _create_cipher
37
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
38
+ VoidPointer, SmartPointer, c_size_t,
39
+ c_uint8_ptr)
40
+
41
+ _raw_blowfish_lib = load_pycryptodome_raw_lib(
42
+ "Crypto.Cipher._raw_blowfish",
43
+ """
44
+ int Blowfish_start_operation(const uint8_t key[],
45
+ size_t key_len,
46
+ void **pResult);
47
+ int Blowfish_encrypt(const void *state,
48
+ const uint8_t *in,
49
+ uint8_t *out,
50
+ size_t data_len);
51
+ int Blowfish_decrypt(const void *state,
52
+ const uint8_t *in,
53
+ uint8_t *out,
54
+ size_t data_len);
55
+ int Blowfish_stop_operation(void *state);
56
+ """
57
+ )
58
+
59
+
60
+ def _create_base_cipher(dict_parameters):
61
+ """This method instantiates and returns a smart pointer to
62
+ a low-level base cipher. It will absorb named parameters in
63
+ the process."""
64
+
65
+ try:
66
+ key = dict_parameters.pop("key")
67
+ except KeyError:
68
+ raise TypeError("Missing 'key' parameter")
69
+
70
+ if len(key) not in key_size:
71
+ raise ValueError("Incorrect Blowfish key length (%d bytes)" % len(key))
72
+
73
+ start_operation = _raw_blowfish_lib.Blowfish_start_operation
74
+ stop_operation = _raw_blowfish_lib.Blowfish_stop_operation
75
+
76
+ void_p = VoidPointer()
77
+ result = start_operation(c_uint8_ptr(key),
78
+ c_size_t(len(key)),
79
+ void_p.address_of())
80
+ if result:
81
+ raise ValueError("Error %X while instantiating the Blowfish cipher"
82
+ % result)
83
+ return SmartPointer(void_p.get(), stop_operation)
84
+
85
+
86
+ def new(key, mode, *args, **kwargs):
87
+ """Create a new Blowfish cipher
88
+
89
+ :param key:
90
+ The secret key to use in the symmetric cipher.
91
+ Its length can vary from 5 to 56 bytes.
92
+ :type key: bytes, bytearray, memoryview
93
+
94
+ :param mode:
95
+ The chaining mode to use for encryption or decryption.
96
+ :type mode: One of the supported ``MODE_*`` constants
97
+
98
+ :Keyword Arguments:
99
+ * **iv** (*bytes*, *bytearray*, *memoryview*) --
100
+ (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
101
+ and ``MODE_OPENPGP`` modes).
102
+
103
+ The initialization vector to use for encryption or decryption.
104
+
105
+ For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
106
+
107
+ For ``MODE_OPENPGP`` mode only,
108
+ it must be 8 bytes long for encryption
109
+ and 10 bytes for decryption (in the latter case, it is
110
+ actually the *encrypted* IV which was prefixed to the ciphertext).
111
+
112
+ If not provided, a random byte string is generated (you must then
113
+ read its value with the :attr:`iv` attribute).
114
+
115
+ * **nonce** (*bytes*, *bytearray*, *memoryview*) --
116
+ (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
117
+
118
+ A value that must never be reused for any other encryption done
119
+ with this key.
120
+
121
+ For ``MODE_EAX`` there are no
122
+ restrictions on its length (recommended: **16** bytes).
123
+
124
+ For ``MODE_CTR``, its length must be in the range **[0..7]**.
125
+
126
+ If not provided for ``MODE_EAX``, a random byte string is generated (you
127
+ can read it back via the ``nonce`` attribute).
128
+
129
+ * **segment_size** (*integer*) --
130
+ (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
131
+ are segmented in. It must be a multiple of 8.
132
+ If not specified, it will be assumed to be 8.
133
+
134
+ * **mac_len** : (*integer*) --
135
+ (Only ``MODE_EAX``)
136
+ Length of the authentication tag, in bytes.
137
+ It must be no longer than 8 (default).
138
+
139
+ * **initial_value** : (*integer*) --
140
+ (Only ``MODE_CTR``). The initial value for the counter within
141
+ the counter block. By default it is **0**.
142
+
143
+ :Return: a Blowfish object, of the applicable mode.
144
+ """
145
+
146
+ return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
147
+
148
+ MODE_ECB = 1
149
+ MODE_CBC = 2
150
+ MODE_CFB = 3
151
+ MODE_OFB = 5
152
+ MODE_CTR = 6
153
+ MODE_OPENPGP = 7
154
+ MODE_EAX = 9
155
+
156
+ # Size of a data block (in bytes)
157
+ block_size = 8
158
+ # Size of a key (in bytes)
159
+ key_size = range(4, 56 + 1)
gtm/lib/python3.12/site-packages/Crypto/Cipher/Blowfish.pyi ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict, Iterable, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ from Crypto.Cipher._mode_ecb import EcbMode
6
+ from Crypto.Cipher._mode_cbc import CbcMode
7
+ from Crypto.Cipher._mode_cfb import CfbMode
8
+ from Crypto.Cipher._mode_ofb import OfbMode
9
+ from Crypto.Cipher._mode_ctr import CtrMode
10
+ from Crypto.Cipher._mode_openpgp import OpenPgpMode
11
+ from Crypto.Cipher._mode_eax import EaxMode
12
+
13
+ BlowfishMode = int
14
+
15
+ MODE_ECB: BlowfishMode
16
+ MODE_CBC: BlowfishMode
17
+ MODE_CFB: BlowfishMode
18
+ MODE_OFB: BlowfishMode
19
+ MODE_CTR: BlowfishMode
20
+ MODE_OPENPGP: BlowfishMode
21
+ MODE_EAX: BlowfishMode
22
+
23
+ def new(key: Buffer,
24
+ mode: BlowfishMode,
25
+ iv : Optional[Buffer] = ...,
26
+ IV : Optional[Buffer] = ...,
27
+ nonce : Optional[Buffer] = ...,
28
+ segment_size : int = ...,
29
+ mac_len : int = ...,
30
+ initial_value : Union[int, Buffer] = ...,
31
+ counter : Dict = ...) -> \
32
+ Union[EcbMode, CbcMode, CfbMode, OfbMode, CtrMode, OpenPgpMode]: ...
33
+
34
+ block_size: int
35
+ key_size: Iterable[int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/CAST.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/CAST.py : CAST
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
+ """
23
+ Module's constants for the modes of operation supported with CAST:
24
+
25
+ :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
26
+ :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
27
+ :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
28
+ :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
29
+ :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
30
+ :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
31
+ :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
32
+ """
33
+
34
+ import sys
35
+
36
+ from Crypto.Cipher import _create_cipher
37
+ from Crypto.Util.py3compat import byte_string
38
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
39
+ VoidPointer, SmartPointer,
40
+ c_size_t, c_uint8_ptr)
41
+
42
+ _raw_cast_lib = load_pycryptodome_raw_lib(
43
+ "Crypto.Cipher._raw_cast",
44
+ """
45
+ int CAST_start_operation(const uint8_t key[],
46
+ size_t key_len,
47
+ void **pResult);
48
+ int CAST_encrypt(const void *state,
49
+ const uint8_t *in,
50
+ uint8_t *out,
51
+ size_t data_len);
52
+ int CAST_decrypt(const void *state,
53
+ const uint8_t *in,
54
+ uint8_t *out,
55
+ size_t data_len);
56
+ int CAST_stop_operation(void *state);
57
+ """)
58
+
59
+
60
+ def _create_base_cipher(dict_parameters):
61
+ """This method instantiates and returns a handle to a low-level
62
+ base cipher. It will absorb named parameters in the process."""
63
+
64
+ try:
65
+ key = dict_parameters.pop("key")
66
+ except KeyError:
67
+ raise TypeError("Missing 'key' parameter")
68
+
69
+ if len(key) not in key_size:
70
+ raise ValueError("Incorrect CAST key length (%d bytes)" % len(key))
71
+
72
+ start_operation = _raw_cast_lib.CAST_start_operation
73
+ stop_operation = _raw_cast_lib.CAST_stop_operation
74
+
75
+ cipher = VoidPointer()
76
+ result = start_operation(c_uint8_ptr(key),
77
+ c_size_t(len(key)),
78
+ cipher.address_of())
79
+ if result:
80
+ raise ValueError("Error %X while instantiating the CAST cipher"
81
+ % result)
82
+
83
+ return SmartPointer(cipher.get(), stop_operation)
84
+
85
+
86
+ def new(key, mode, *args, **kwargs):
87
+ """Create a new CAST cipher
88
+
89
+ :param key:
90
+ The secret key to use in the symmetric cipher.
91
+ Its length can vary from 5 to 16 bytes.
92
+ :type key: bytes, bytearray, memoryview
93
+
94
+ :param mode:
95
+ The chaining mode to use for encryption or decryption.
96
+ :type mode: One of the supported ``MODE_*`` constants
97
+
98
+ :Keyword Arguments:
99
+ * **iv** (*bytes*, *bytearray*, *memoryview*) --
100
+ (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
101
+ and ``MODE_OPENPGP`` modes).
102
+
103
+ The initialization vector to use for encryption or decryption.
104
+
105
+ For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
106
+
107
+ For ``MODE_OPENPGP`` mode only,
108
+ it must be 8 bytes long for encryption
109
+ and 10 bytes for decryption (in the latter case, it is
110
+ actually the *encrypted* IV which was prefixed to the ciphertext).
111
+
112
+ If not provided, a random byte string is generated (you must then
113
+ read its value with the :attr:`iv` attribute).
114
+
115
+ * **nonce** (*bytes*, *bytearray*, *memoryview*) --
116
+ (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
117
+
118
+ A value that must never be reused for any other encryption done
119
+ with this key.
120
+
121
+ For ``MODE_EAX`` there are no
122
+ restrictions on its length (recommended: **16** bytes).
123
+
124
+ For ``MODE_CTR``, its length must be in the range **[0..7]**.
125
+
126
+ If not provided for ``MODE_EAX``, a random byte string is generated (you
127
+ can read it back via the ``nonce`` attribute).
128
+
129
+ * **segment_size** (*integer*) --
130
+ (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
131
+ are segmented in. It must be a multiple of 8.
132
+ If not specified, it will be assumed to be 8.
133
+
134
+ * **mac_len** : (*integer*) --
135
+ (Only ``MODE_EAX``)
136
+ Length of the authentication tag, in bytes.
137
+ It must be no longer than 8 (default).
138
+
139
+ * **initial_value** : (*integer*) --
140
+ (Only ``MODE_CTR``). The initial value for the counter within
141
+ the counter block. By default it is **0**.
142
+
143
+ :Return: a CAST object, of the applicable mode.
144
+ """
145
+
146
+ return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
147
+
148
+ MODE_ECB = 1
149
+ MODE_CBC = 2
150
+ MODE_CFB = 3
151
+ MODE_OFB = 5
152
+ MODE_CTR = 6
153
+ MODE_OPENPGP = 7
154
+ MODE_EAX = 9
155
+
156
+ # Size of a data block (in bytes)
157
+ block_size = 8
158
+ # Size of a key (in bytes)
159
+ key_size = range(5, 16 + 1)
gtm/lib/python3.12/site-packages/Crypto/Cipher/CAST.pyi ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict, Iterable, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ from Crypto.Cipher._mode_ecb import EcbMode
6
+ from Crypto.Cipher._mode_cbc import CbcMode
7
+ from Crypto.Cipher._mode_cfb import CfbMode
8
+ from Crypto.Cipher._mode_ofb import OfbMode
9
+ from Crypto.Cipher._mode_ctr import CtrMode
10
+ from Crypto.Cipher._mode_openpgp import OpenPgpMode
11
+ from Crypto.Cipher._mode_eax import EaxMode
12
+
13
+ CASTMode = int
14
+
15
+ MODE_ECB: CASTMode
16
+ MODE_CBC: CASTMode
17
+ MODE_CFB: CASTMode
18
+ MODE_OFB: CASTMode
19
+ MODE_CTR: CASTMode
20
+ MODE_OPENPGP: CASTMode
21
+ MODE_EAX: CASTMode
22
+
23
+ def new(key: Buffer,
24
+ mode: CASTMode,
25
+ iv : Optional[Buffer] = ...,
26
+ IV : Optional[Buffer] = ...,
27
+ nonce : Optional[Buffer] = ...,
28
+ segment_size : int = ...,
29
+ mac_len : int = ...,
30
+ initial_value : Union[int, Buffer] = ...,
31
+ counter : Dict = ...) -> \
32
+ Union[EcbMode, CbcMode, CfbMode, OfbMode, CtrMode, OpenPgpMode]: ...
33
+
34
+ block_size: int
35
+ key_size : Iterable[int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2014, Legrandin <[email protected]>
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions
8
+ # are met:
9
+ #
10
+ # 1. Redistributions of source code must retain the above copyright
11
+ # notice, this list of conditions and the following disclaimer.
12
+ # 2. Redistributions in binary form must reproduce the above copyright
13
+ # notice, this list of conditions and the following disclaimer in
14
+ # the documentation and/or other materials provided with the
15
+ # distribution.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21
+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
+ # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+ # ===================================================================
30
+
31
+ from Crypto.Random import get_random_bytes
32
+
33
+ from Crypto.Util.py3compat import _copy_bytes
34
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
35
+ create_string_buffer,
36
+ get_raw_buffer, VoidPointer,
37
+ SmartPointer, c_size_t,
38
+ c_uint8_ptr, c_ulong,
39
+ is_writeable_buffer)
40
+
41
+ _raw_chacha20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._chacha20",
42
+ """
43
+ int chacha20_init(void **pState,
44
+ const uint8_t *key,
45
+ size_t keySize,
46
+ const uint8_t *nonce,
47
+ size_t nonceSize);
48
+
49
+ int chacha20_destroy(void *state);
50
+
51
+ int chacha20_encrypt(void *state,
52
+ const uint8_t in[],
53
+ uint8_t out[],
54
+ size_t len);
55
+
56
+ int chacha20_seek(void *state,
57
+ unsigned long block_high,
58
+ unsigned long block_low,
59
+ unsigned offset);
60
+ int hchacha20( const uint8_t key[32],
61
+ const uint8_t nonce16[16],
62
+ uint8_t subkey[32]);
63
+ """)
64
+
65
+
66
+ def _HChaCha20(key, nonce):
67
+
68
+ assert(len(key) == 32)
69
+ assert(len(nonce) == 16)
70
+
71
+ subkey = bytearray(32)
72
+ result = _raw_chacha20_lib.hchacha20(
73
+ c_uint8_ptr(key),
74
+ c_uint8_ptr(nonce),
75
+ c_uint8_ptr(subkey))
76
+ if result:
77
+ raise ValueError("Error %d when deriving subkey with HChaCha20" % result)
78
+
79
+ return subkey
80
+
81
+
82
+ class ChaCha20Cipher(object):
83
+ """ChaCha20 (or XChaCha20) cipher object.
84
+ Do not create it directly. Use :py:func:`new` instead.
85
+
86
+ :var nonce: The nonce with length 8, 12 or 24 bytes
87
+ :vartype nonce: bytes
88
+ """
89
+
90
+ block_size = 1
91
+
92
+ def __init__(self, key, nonce):
93
+ """Initialize a ChaCha20/XChaCha20 cipher object
94
+
95
+ See also `new()` at the module level."""
96
+
97
+ self.nonce = _copy_bytes(None, None, nonce)
98
+
99
+ # XChaCha20 requires a key derivation with HChaCha20
100
+ # See 2.3 in https://tools.ietf.org/html/draft-arciszewski-xchacha-03
101
+ if len(nonce) == 24:
102
+ key = _HChaCha20(key, nonce[:16])
103
+ nonce = b'\x00' * 4 + nonce[16:]
104
+ self._name = "XChaCha20"
105
+ else:
106
+ self._name = "ChaCha20"
107
+ nonce = self.nonce
108
+
109
+ self._next = ("encrypt", "decrypt")
110
+
111
+ self._state = VoidPointer()
112
+ result = _raw_chacha20_lib.chacha20_init(
113
+ self._state.address_of(),
114
+ c_uint8_ptr(key),
115
+ c_size_t(len(key)),
116
+ nonce,
117
+ c_size_t(len(nonce)))
118
+ if result:
119
+ raise ValueError("Error %d instantiating a %s cipher" % (result,
120
+ self._name))
121
+ self._state = SmartPointer(self._state.get(),
122
+ _raw_chacha20_lib.chacha20_destroy)
123
+
124
+ def encrypt(self, plaintext, output=None):
125
+ """Encrypt a piece of data.
126
+
127
+ Args:
128
+ plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
129
+ Keyword Args:
130
+ output(bytes/bytearray/memoryview): The location where the ciphertext
131
+ is written to. If ``None``, the ciphertext is returned.
132
+ Returns:
133
+ If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
134
+ Otherwise, ``None``.
135
+ """
136
+
137
+ if "encrypt" not in self._next:
138
+ raise TypeError("Cipher object can only be used for decryption")
139
+ self._next = ("encrypt",)
140
+ return self._encrypt(plaintext, output)
141
+
142
+ def _encrypt(self, plaintext, output):
143
+ """Encrypt without FSM checks"""
144
+
145
+ if output is None:
146
+ ciphertext = create_string_buffer(len(plaintext))
147
+ else:
148
+ ciphertext = output
149
+
150
+ if not is_writeable_buffer(output):
151
+ raise TypeError("output must be a bytearray or a writeable memoryview")
152
+
153
+ if len(plaintext) != len(output):
154
+ raise ValueError("output must have the same length as the input"
155
+ " (%d bytes)" % len(plaintext))
156
+
157
+ result = _raw_chacha20_lib.chacha20_encrypt(
158
+ self._state.get(),
159
+ c_uint8_ptr(plaintext),
160
+ c_uint8_ptr(ciphertext),
161
+ c_size_t(len(plaintext)))
162
+ if result:
163
+ raise ValueError("Error %d while encrypting with %s" % (result, self._name))
164
+
165
+ if output is None:
166
+ return get_raw_buffer(ciphertext)
167
+ else:
168
+ return None
169
+
170
+ def decrypt(self, ciphertext, output=None):
171
+ """Decrypt a piece of data.
172
+
173
+ Args:
174
+ ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
175
+ Keyword Args:
176
+ output(bytes/bytearray/memoryview): The location where the plaintext
177
+ is written to. If ``None``, the plaintext is returned.
178
+ Returns:
179
+ If ``output`` is ``None``, the plaintext is returned as ``bytes``.
180
+ Otherwise, ``None``.
181
+ """
182
+
183
+ if "decrypt" not in self._next:
184
+ raise TypeError("Cipher object can only be used for encryption")
185
+ self._next = ("decrypt",)
186
+
187
+ try:
188
+ return self._encrypt(ciphertext, output)
189
+ except ValueError as e:
190
+ raise ValueError(str(e).replace("enc", "dec"))
191
+
192
+ def seek(self, position):
193
+ """Seek to a certain position in the key stream.
194
+
195
+ Args:
196
+ position (integer):
197
+ The absolute position within the key stream, in bytes.
198
+ """
199
+
200
+ position, offset = divmod(position, 64)
201
+ block_low = position & 0xFFFFFFFF
202
+ block_high = position >> 32
203
+
204
+ result = _raw_chacha20_lib.chacha20_seek(
205
+ self._state.get(),
206
+ c_ulong(block_high),
207
+ c_ulong(block_low),
208
+ offset
209
+ )
210
+ if result:
211
+ raise ValueError("Error %d while seeking with %s" % (result, self._name))
212
+
213
+
214
+ def _derive_Poly1305_key_pair(key, nonce):
215
+ """Derive a tuple (r, s, nonce) for a Poly1305 MAC.
216
+
217
+ If nonce is ``None``, a new 12-byte nonce is generated.
218
+ """
219
+
220
+ if len(key) != 32:
221
+ raise ValueError("Poly1305 with ChaCha20 requires a 32-byte key")
222
+
223
+ if nonce is None:
224
+ padded_nonce = nonce = get_random_bytes(12)
225
+ elif len(nonce) == 8:
226
+ # See RFC7538, 2.6: [...] ChaCha20 as specified here requires a 96-bit
227
+ # nonce. So if the provided nonce is only 64-bit, then the first 32
228
+ # bits of the nonce will be set to a constant number.
229
+ # This will usually be zero, but for protocols with multiple senders it may be
230
+ # different for each sender, but should be the same for all
231
+ # invocations of the function with the same key by a particular
232
+ # sender.
233
+ padded_nonce = b'\x00\x00\x00\x00' + nonce
234
+ elif len(nonce) == 12:
235
+ padded_nonce = nonce
236
+ else:
237
+ raise ValueError("Poly1305 with ChaCha20 requires an 8- or 12-byte nonce")
238
+
239
+ rs = new(key=key, nonce=padded_nonce).encrypt(b'\x00' * 32)
240
+ return rs[:16], rs[16:], nonce
241
+
242
+
243
+ def new(**kwargs):
244
+ """Create a new ChaCha20 or XChaCha20 cipher
245
+
246
+ Keyword Args:
247
+ key (bytes/bytearray/memoryview): The secret key to use.
248
+ It must be 32 bytes long.
249
+ nonce (bytes/bytearray/memoryview): A mandatory value that
250
+ must never be reused for any other encryption
251
+ done with this key.
252
+
253
+ For ChaCha20, it must be 8 or 12 bytes long.
254
+
255
+ For XChaCha20, it must be 24 bytes long.
256
+
257
+ If not provided, 8 bytes will be randomly generated
258
+ (you can find them back in the ``nonce`` attribute).
259
+
260
+ :Return: a :class:`Crypto.Cipher.ChaCha20.ChaCha20Cipher` object
261
+ """
262
+
263
+ try:
264
+ key = kwargs.pop("key")
265
+ except KeyError as e:
266
+ raise TypeError("Missing parameter %s" % e)
267
+
268
+ nonce = kwargs.pop("nonce", None)
269
+ if nonce is None:
270
+ nonce = get_random_bytes(8)
271
+
272
+ if len(key) != 32:
273
+ raise ValueError("ChaCha20/XChaCha20 key must be 32 bytes long")
274
+
275
+ if len(nonce) not in (8, 12, 24):
276
+ raise ValueError("Nonce must be 8/12 bytes(ChaCha20) or 24 bytes (XChaCha20)")
277
+
278
+ if kwargs:
279
+ raise TypeError("Unknown parameters: " + str(kwargs))
280
+
281
+ return ChaCha20Cipher(key, nonce)
282
+
283
+ # Size of a data block (in bytes)
284
+ block_size = 1
285
+
286
+ # Size of a key (in bytes)
287
+ key_size = 32
gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20.pyi ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, overload, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ def _HChaCha20(key: Buffer, nonce: Buffer) -> bytearray: ...
6
+
7
+ class ChaCha20Cipher:
8
+ block_size: int
9
+ nonce: bytes
10
+
11
+ def __init__(self, key: Buffer, nonce: Buffer) -> None: ...
12
+ @overload
13
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
14
+ @overload
15
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
16
+ @overload
17
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
18
+ @overload
19
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
20
+ def seek(self, position: int) -> None: ...
21
+
22
+ def new(key: Buffer, nonce: Optional[Buffer] = ...) -> ChaCha20Cipher: ...
23
+
24
+ block_size: int
25
+ key_size: int
gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20_Poly1305.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2018, Helder Eijs <[email protected]>
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions
8
+ # are met:
9
+ #
10
+ # 1. Redistributions of source code must retain the above copyright
11
+ # notice, this list of conditions and the following disclaimer.
12
+ # 2. Redistributions in binary form must reproduce the above copyright
13
+ # notice, this list of conditions and the following disclaimer in
14
+ # the documentation and/or other materials provided with the
15
+ # distribution.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21
+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
+ # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+ # ===================================================================
30
+
31
+ from binascii import unhexlify
32
+
33
+ from Crypto.Cipher import ChaCha20
34
+ from Crypto.Cipher.ChaCha20 import _HChaCha20
35
+ from Crypto.Hash import Poly1305, BLAKE2s
36
+
37
+ from Crypto.Random import get_random_bytes
38
+
39
+ from Crypto.Util.number import long_to_bytes
40
+ from Crypto.Util.py3compat import _copy_bytes, bord
41
+ from Crypto.Util._raw_api import is_buffer
42
+
43
+
44
+ def _enum(**enums):
45
+ return type('Enum', (), enums)
46
+
47
+
48
+ _CipherStatus = _enum(PROCESSING_AUTH_DATA=1,
49
+ PROCESSING_CIPHERTEXT=2,
50
+ PROCESSING_DONE=3)
51
+
52
+
53
+ class ChaCha20Poly1305Cipher(object):
54
+ """ChaCha20-Poly1305 and XChaCha20-Poly1305 cipher object.
55
+ Do not create it directly. Use :py:func:`new` instead.
56
+
57
+ :var nonce: The nonce with length 8, 12 or 24 bytes
58
+ :vartype nonce: byte string
59
+ """
60
+
61
+ def __init__(self, key, nonce):
62
+ """Initialize a ChaCha20-Poly1305 AEAD cipher object
63
+
64
+ See also `new()` at the module level."""
65
+
66
+ self._next = ("update", "encrypt", "decrypt", "digest",
67
+ "verify")
68
+
69
+ self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20)
70
+
71
+ self._cipher = ChaCha20.new(key=key, nonce=nonce)
72
+ self._cipher.seek(64) # Block counter starts at 1
73
+
74
+ self._len_aad = 0
75
+ self._len_ct = 0
76
+ self._mac_tag = None
77
+ self._status = _CipherStatus.PROCESSING_AUTH_DATA
78
+
79
+ def update(self, data):
80
+ """Protect the associated data.
81
+
82
+ Associated data (also known as *additional authenticated data* - AAD)
83
+ is the piece of the message that must stay in the clear, while
84
+ still allowing the receiver to verify its integrity.
85
+ An example is packet headers.
86
+
87
+ The associated data (possibly split into multiple segments) is
88
+ fed into :meth:`update` before any call to :meth:`decrypt` or :meth:`encrypt`.
89
+ If there is no associated data, :meth:`update` is not called.
90
+
91
+ :param bytes/bytearray/memoryview assoc_data:
92
+ A piece of associated data. There are no restrictions on its size.
93
+ """
94
+
95
+ if "update" not in self._next:
96
+ raise TypeError("update() method cannot be called")
97
+
98
+ self._len_aad += len(data)
99
+ self._authenticator.update(data)
100
+
101
+ def _pad_aad(self):
102
+
103
+ assert(self._status == _CipherStatus.PROCESSING_AUTH_DATA)
104
+ if self._len_aad & 0x0F:
105
+ self._authenticator.update(b'\x00' * (16 - (self._len_aad & 0x0F)))
106
+ self._status = _CipherStatus.PROCESSING_CIPHERTEXT
107
+
108
+ def encrypt(self, plaintext, output=None):
109
+ """Encrypt a piece of data.
110
+
111
+ Args:
112
+ plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
113
+ Keyword Args:
114
+ output(bytes/bytearray/memoryview): The location where the ciphertext
115
+ is written to. If ``None``, the ciphertext is returned.
116
+ Returns:
117
+ If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
118
+ Otherwise, ``None``.
119
+ """
120
+
121
+ if "encrypt" not in self._next:
122
+ raise TypeError("encrypt() method cannot be called")
123
+
124
+ if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
125
+ self._pad_aad()
126
+
127
+ self._next = ("encrypt", "digest")
128
+
129
+ result = self._cipher.encrypt(plaintext, output=output)
130
+ self._len_ct += len(plaintext)
131
+ if output is None:
132
+ self._authenticator.update(result)
133
+ else:
134
+ self._authenticator.update(output)
135
+ return result
136
+
137
+ def decrypt(self, ciphertext, output=None):
138
+ """Decrypt a piece of data.
139
+
140
+ Args:
141
+ ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
142
+ Keyword Args:
143
+ output(bytes/bytearray/memoryview): The location where the plaintext
144
+ is written to. If ``None``, the plaintext is returned.
145
+ Returns:
146
+ If ``output`` is ``None``, the plaintext is returned as ``bytes``.
147
+ Otherwise, ``None``.
148
+ """
149
+
150
+ if "decrypt" not in self._next:
151
+ raise TypeError("decrypt() method cannot be called")
152
+
153
+ if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
154
+ self._pad_aad()
155
+
156
+ self._next = ("decrypt", "verify")
157
+
158
+ self._len_ct += len(ciphertext)
159
+ self._authenticator.update(ciphertext)
160
+ return self._cipher.decrypt(ciphertext, output=output)
161
+
162
+ def _compute_mac(self):
163
+ """Finalize the cipher (if not done already) and return the MAC."""
164
+
165
+ if self._mac_tag:
166
+ assert(self._status == _CipherStatus.PROCESSING_DONE)
167
+ return self._mac_tag
168
+
169
+ assert(self._status != _CipherStatus.PROCESSING_DONE)
170
+
171
+ if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
172
+ self._pad_aad()
173
+
174
+ if self._len_ct & 0x0F:
175
+ self._authenticator.update(b'\x00' * (16 - (self._len_ct & 0x0F)))
176
+
177
+ self._status = _CipherStatus.PROCESSING_DONE
178
+
179
+ self._authenticator.update(long_to_bytes(self._len_aad, 8)[::-1])
180
+ self._authenticator.update(long_to_bytes(self._len_ct, 8)[::-1])
181
+ self._mac_tag = self._authenticator.digest()
182
+ return self._mac_tag
183
+
184
+ def digest(self):
185
+ """Compute the *binary* authentication tag (MAC).
186
+
187
+ :Return: the MAC tag, as 16 ``bytes``.
188
+ """
189
+
190
+ if "digest" not in self._next:
191
+ raise TypeError("digest() method cannot be called")
192
+ self._next = ("digest",)
193
+
194
+ return self._compute_mac()
195
+
196
+ def hexdigest(self):
197
+ """Compute the *printable* authentication tag (MAC).
198
+
199
+ This method is like :meth:`digest`.
200
+
201
+ :Return: the MAC tag, as a hexadecimal string.
202
+ """
203
+ return "".join(["%02x" % bord(x) for x in self.digest()])
204
+
205
+ def verify(self, received_mac_tag):
206
+ """Validate the *binary* authentication tag (MAC).
207
+
208
+ The receiver invokes this method at the very end, to
209
+ check if the associated data (if any) and the decrypted
210
+ messages are valid.
211
+
212
+ :param bytes/bytearray/memoryview received_mac_tag:
213
+ This is the 16-byte *binary* MAC, as received from the sender.
214
+ :Raises ValueError:
215
+ if the MAC does not match. The message has been tampered with
216
+ or the key is incorrect.
217
+ """
218
+
219
+ if "verify" not in self._next:
220
+ raise TypeError("verify() cannot be called"
221
+ " when encrypting a message")
222
+ self._next = ("verify",)
223
+
224
+ secret = get_random_bytes(16)
225
+
226
+ self._compute_mac()
227
+
228
+ mac1 = BLAKE2s.new(digest_bits=160, key=secret,
229
+ data=self._mac_tag)
230
+ mac2 = BLAKE2s.new(digest_bits=160, key=secret,
231
+ data=received_mac_tag)
232
+
233
+ if mac1.digest() != mac2.digest():
234
+ raise ValueError("MAC check failed")
235
+
236
+ def hexverify(self, hex_mac_tag):
237
+ """Validate the *printable* authentication tag (MAC).
238
+
239
+ This method is like :meth:`verify`.
240
+
241
+ :param string hex_mac_tag:
242
+ This is the *printable* MAC.
243
+ :Raises ValueError:
244
+ if the MAC does not match. The message has been tampered with
245
+ or the key is incorrect.
246
+ """
247
+
248
+ self.verify(unhexlify(hex_mac_tag))
249
+
250
+ def encrypt_and_digest(self, plaintext):
251
+ """Perform :meth:`encrypt` and :meth:`digest` in one step.
252
+
253
+ :param plaintext: The data to encrypt, of any size.
254
+ :type plaintext: bytes/bytearray/memoryview
255
+ :return: a tuple with two ``bytes`` objects:
256
+
257
+ - the ciphertext, of equal length as the plaintext
258
+ - the 16-byte MAC tag
259
+ """
260
+
261
+ return self.encrypt(plaintext), self.digest()
262
+
263
+ def decrypt_and_verify(self, ciphertext, received_mac_tag):
264
+ """Perform :meth:`decrypt` and :meth:`verify` in one step.
265
+
266
+ :param ciphertext: The piece of data to decrypt.
267
+ :type ciphertext: bytes/bytearray/memoryview
268
+ :param bytes received_mac_tag:
269
+ This is the 16-byte *binary* MAC, as received from the sender.
270
+ :return: the decrypted data (as ``bytes``)
271
+ :raises ValueError:
272
+ if the MAC does not match. The message has been tampered with
273
+ or the key is incorrect.
274
+ """
275
+
276
+ plaintext = self.decrypt(ciphertext)
277
+ self.verify(received_mac_tag)
278
+ return plaintext
279
+
280
+
281
+ def new(**kwargs):
282
+ """Create a new ChaCha20-Poly1305 or XChaCha20-Poly1305 AEAD cipher.
283
+
284
+ :keyword key: The secret key to use. It must be 32 bytes long.
285
+ :type key: byte string
286
+
287
+ :keyword nonce:
288
+ A value that must never be reused for any other encryption
289
+ done with this key.
290
+
291
+ For ChaCha20-Poly1305, it must be 8 or 12 bytes long.
292
+
293
+ For XChaCha20-Poly1305, it must be 24 bytes long.
294
+
295
+ If not provided, 12 ``bytes`` will be generated randomly
296
+ (you can find them back in the ``nonce`` attribute).
297
+ :type nonce: bytes, bytearray, memoryview
298
+
299
+ :Return: a :class:`Crypto.Cipher.ChaCha20.ChaCha20Poly1305Cipher` object
300
+ """
301
+
302
+ try:
303
+ key = kwargs.pop("key")
304
+ except KeyError as e:
305
+ raise TypeError("Missing parameter %s" % e)
306
+
307
+ self._len_ct += len(plaintext)
308
+
309
+ if len(key) != 32:
310
+ raise ValueError("Key must be 32 bytes long")
311
+
312
+ nonce = kwargs.pop("nonce", None)
313
+ if nonce is None:
314
+ nonce = get_random_bytes(12)
315
+
316
+ if len(nonce) in (8, 12):
317
+ chacha20_poly1305_nonce = nonce
318
+ elif len(nonce) == 24:
319
+ key = _HChaCha20(key, nonce[:16])
320
+ chacha20_poly1305_nonce = b'\x00\x00\x00\x00' + nonce[16:]
321
+ else:
322
+ raise ValueError("Nonce must be 8, 12 or 24 bytes long")
323
+
324
+ if not is_buffer(nonce):
325
+ raise TypeError("nonce must be bytes, bytearray or memoryview")
326
+
327
+ if kwargs:
328
+ raise TypeError("Unknown parameters: " + str(kwargs))
329
+
330
+ cipher = ChaCha20Poly1305Cipher(key, chacha20_poly1305_nonce)
331
+ cipher.nonce = _copy_bytes(None, None, nonce)
332
+ return cipher
333
+
334
+
335
+ # Size of a key (in bytes)
336
+ key_size = 32
gtm/lib/python3.12/site-packages/Crypto/Cipher/ChaCha20_Poly1305.pyi ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Tuple, overload, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ class ChaCha20Poly1305Cipher:
6
+ nonce: bytes
7
+
8
+ def __init__(self, key: Buffer, nonce: Buffer) -> None: ...
9
+ def update(self, data: Buffer) -> None: ...
10
+ @overload
11
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
12
+ @overload
13
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
14
+ @overload
15
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
16
+ @overload
17
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
18
+ def digest(self) -> bytes: ...
19
+ def hexdigest(self) -> str: ...
20
+ def verify(self, received_mac_tag: Buffer) -> None: ...
21
+ def hexverify(self, received_mac_tag: str) -> None: ...
22
+ def encrypt_and_digest(self, plaintext: Buffer) -> Tuple[bytes, bytes]: ...
23
+ def decrypt_and_verify(self, ciphertext: Buffer, received_mac_tag: Buffer) -> bytes: ...
24
+
25
+ def new(key: Buffer, nonce: Optional[Buffer] = ...) -> ChaCha20Poly1305Cipher: ...
26
+
27
+ block_size: int
28
+ key_size: int
gtm/lib/python3.12/site-packages/Crypto/Cipher/DES.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/DES.py : DES
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
+ """
23
+ Module's constants for the modes of operation supported with Single DES:
24
+
25
+ :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
26
+ :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
27
+ :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
28
+ :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
29
+ :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
30
+ :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
31
+ :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
32
+ """
33
+
34
+ import sys
35
+
36
+ from Crypto.Cipher import _create_cipher
37
+ from Crypto.Util.py3compat import byte_string
38
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
39
+ VoidPointer, SmartPointer,
40
+ c_size_t, c_uint8_ptr)
41
+
42
+ _raw_des_lib = load_pycryptodome_raw_lib(
43
+ "Crypto.Cipher._raw_des",
44
+ """
45
+ int DES_start_operation(const uint8_t key[],
46
+ size_t key_len,
47
+ void **pResult);
48
+ int DES_encrypt(const void *state,
49
+ const uint8_t *in,
50
+ uint8_t *out,
51
+ size_t data_len);
52
+ int DES_decrypt(const void *state,
53
+ const uint8_t *in,
54
+ uint8_t *out,
55
+ size_t data_len);
56
+ int DES_stop_operation(void *state);
57
+ """)
58
+
59
+
60
+ def _create_base_cipher(dict_parameters):
61
+ """This method instantiates and returns a handle to a low-level
62
+ base cipher. It will absorb named parameters in the process."""
63
+
64
+ try:
65
+ key = dict_parameters.pop("key")
66
+ except KeyError:
67
+ raise TypeError("Missing 'key' parameter")
68
+
69
+ if len(key) != key_size:
70
+ raise ValueError("Incorrect DES key length (%d bytes)" % len(key))
71
+
72
+ start_operation = _raw_des_lib.DES_start_operation
73
+ stop_operation = _raw_des_lib.DES_stop_operation
74
+
75
+ cipher = VoidPointer()
76
+ result = start_operation(c_uint8_ptr(key),
77
+ c_size_t(len(key)),
78
+ cipher.address_of())
79
+ if result:
80
+ raise ValueError("Error %X while instantiating the DES cipher"
81
+ % result)
82
+ return SmartPointer(cipher.get(), stop_operation)
83
+
84
+
85
+ def new(key, mode, *args, **kwargs):
86
+ """Create a new DES cipher.
87
+
88
+ :param key:
89
+ The secret key to use in the symmetric cipher.
90
+ It must be 8 byte long. The parity bits will be ignored.
91
+ :type key: bytes/bytearray/memoryview
92
+
93
+ :param mode:
94
+ The chaining mode to use for encryption or decryption.
95
+ :type mode: One of the supported ``MODE_*`` constants
96
+
97
+ :Keyword Arguments:
98
+ * **iv** (*byte string*) --
99
+ (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
100
+ and ``MODE_OPENPGP`` modes).
101
+
102
+ The initialization vector to use for encryption or decryption.
103
+
104
+ For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
105
+
106
+ For ``MODE_OPENPGP`` mode only,
107
+ it must be 8 bytes long for encryption
108
+ and 10 bytes for decryption (in the latter case, it is
109
+ actually the *encrypted* IV which was prefixed to the ciphertext).
110
+
111
+ If not provided, a random byte string is generated (you must then
112
+ read its value with the :attr:`iv` attribute).
113
+
114
+ * **nonce** (*byte string*) --
115
+ (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
116
+
117
+ A value that must never be reused for any other encryption done
118
+ with this key.
119
+
120
+ For ``MODE_EAX`` there are no
121
+ restrictions on its length (recommended: **16** bytes).
122
+
123
+ For ``MODE_CTR``, its length must be in the range **[0..7]**.
124
+
125
+ If not provided for ``MODE_EAX``, a random byte string is generated (you
126
+ can read it back via the ``nonce`` attribute).
127
+
128
+ * **segment_size** (*integer*) --
129
+ (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
130
+ are segmented in. It must be a multiple of 8.
131
+ If not specified, it will be assumed to be 8.
132
+
133
+ * **mac_len** : (*integer*) --
134
+ (Only ``MODE_EAX``)
135
+ Length of the authentication tag, in bytes.
136
+ It must be no longer than 8 (default).
137
+
138
+ * **initial_value** : (*integer*) --
139
+ (Only ``MODE_CTR``). The initial value for the counter within
140
+ the counter block. By default it is **0**.
141
+
142
+ :Return: a DES object, of the applicable mode.
143
+ """
144
+
145
+ return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
146
+
147
+ MODE_ECB = 1
148
+ MODE_CBC = 2
149
+ MODE_CFB = 3
150
+ MODE_OFB = 5
151
+ MODE_CTR = 6
152
+ MODE_OPENPGP = 7
153
+ MODE_EAX = 9
154
+
155
+ # Size of a data block (in bytes)
156
+ block_size = 8
157
+ # Size of a key (in bytes)
158
+ key_size = 8
gtm/lib/python3.12/site-packages/Crypto/Cipher/DES.pyi ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict, Iterable, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ from Crypto.Cipher._mode_ecb import EcbMode
6
+ from Crypto.Cipher._mode_cbc import CbcMode
7
+ from Crypto.Cipher._mode_cfb import CfbMode
8
+ from Crypto.Cipher._mode_ofb import OfbMode
9
+ from Crypto.Cipher._mode_ctr import CtrMode
10
+ from Crypto.Cipher._mode_openpgp import OpenPgpMode
11
+ from Crypto.Cipher._mode_eax import EaxMode
12
+
13
+ DESMode = int
14
+
15
+ MODE_ECB: DESMode
16
+ MODE_CBC: DESMode
17
+ MODE_CFB: DESMode
18
+ MODE_OFB: DESMode
19
+ MODE_CTR: DESMode
20
+ MODE_OPENPGP: DESMode
21
+ MODE_EAX: DESMode
22
+
23
+ def new(key: Buffer,
24
+ mode: DESMode,
25
+ iv : Optional[Buffer] = ...,
26
+ IV : Optional[Buffer] = ...,
27
+ nonce : Optional[Buffer] = ...,
28
+ segment_size : int = ...,
29
+ mac_len : int = ...,
30
+ initial_value : Union[int, Buffer] = ...,
31
+ counter : Dict = ...) -> \
32
+ Union[EcbMode, CbcMode, CfbMode, OfbMode, CtrMode, OpenPgpMode]: ...
33
+
34
+ block_size: int
35
+ key_size: int
gtm/lib/python3.12/site-packages/Crypto/Cipher/DES3.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/DES3.py : DES3
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
+ """
23
+ Module's constants for the modes of operation supported with Triple DES:
24
+
25
+ :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
26
+ :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
27
+ :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
28
+ :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
29
+ :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
30
+ :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
31
+ :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
32
+ """
33
+
34
+ import sys
35
+
36
+ from Crypto.Cipher import _create_cipher
37
+ from Crypto.Util.py3compat import byte_string, bchr, bord, bstr
38
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
39
+ VoidPointer, SmartPointer,
40
+ c_size_t)
41
+
42
+ _raw_des3_lib = load_pycryptodome_raw_lib(
43
+ "Crypto.Cipher._raw_des3",
44
+ """
45
+ int DES3_start_operation(const uint8_t key[],
46
+ size_t key_len,
47
+ void **pResult);
48
+ int DES3_encrypt(const void *state,
49
+ const uint8_t *in,
50
+ uint8_t *out,
51
+ size_t data_len);
52
+ int DES3_decrypt(const void *state,
53
+ const uint8_t *in,
54
+ uint8_t *out,
55
+ size_t data_len);
56
+ int DES3_stop_operation(void *state);
57
+ """)
58
+
59
+
60
+ def adjust_key_parity(key_in):
61
+ """Set the parity bits in a TDES key.
62
+
63
+ :param key_in: the TDES key whose bits need to be adjusted
64
+ :type key_in: byte string
65
+
66
+ :returns: a copy of ``key_in``, with the parity bits correctly set
67
+ :rtype: byte string
68
+
69
+ :raises ValueError: if the TDES key is not 16 or 24 bytes long
70
+ :raises ValueError: if the TDES key degenerates into Single DES
71
+ """
72
+
73
+ def parity_byte(key_byte):
74
+ parity = 1
75
+ for i in range(1, 8):
76
+ parity ^= (key_byte >> i) & 1
77
+ return (key_byte & 0xFE) | parity
78
+
79
+ if len(key_in) not in key_size:
80
+ raise ValueError("Not a valid TDES key")
81
+
82
+ key_out = b"".join([ bchr(parity_byte(bord(x))) for x in key_in ])
83
+
84
+ if key_out[:8] == key_out[8:16] or key_out[-16:-8] == key_out[-8:]:
85
+ raise ValueError("Triple DES key degenerates to single DES")
86
+
87
+ return key_out
88
+
89
+
90
+ def _create_base_cipher(dict_parameters):
91
+ """This method instantiates and returns a handle to a low-level base cipher.
92
+ It will absorb named parameters in the process."""
93
+
94
+ try:
95
+ key_in = dict_parameters.pop("key")
96
+ except KeyError:
97
+ raise TypeError("Missing 'key' parameter")
98
+
99
+ key = adjust_key_parity(bstr(key_in))
100
+
101
+ start_operation = _raw_des3_lib.DES3_start_operation
102
+ stop_operation = _raw_des3_lib.DES3_stop_operation
103
+
104
+ cipher = VoidPointer()
105
+ result = start_operation(key,
106
+ c_size_t(len(key)),
107
+ cipher.address_of())
108
+ if result:
109
+ raise ValueError("Error %X while instantiating the TDES cipher"
110
+ % result)
111
+ return SmartPointer(cipher.get(), stop_operation)
112
+
113
+
114
+ def new(key, mode, *args, **kwargs):
115
+ """Create a new Triple DES cipher.
116
+
117
+ :param key:
118
+ The secret key to use in the symmetric cipher.
119
+ It must be 16 or 24 byte long. The parity bits will be ignored.
120
+ :type key: bytes/bytearray/memoryview
121
+
122
+ :param mode:
123
+ The chaining mode to use for encryption or decryption.
124
+ :type mode: One of the supported ``MODE_*`` constants
125
+
126
+ :Keyword Arguments:
127
+ * **iv** (*bytes*, *bytearray*, *memoryview*) --
128
+ (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
129
+ and ``MODE_OPENPGP`` modes).
130
+
131
+ The initialization vector to use for encryption or decryption.
132
+
133
+ For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 8 bytes long.
134
+
135
+ For ``MODE_OPENPGP`` mode only,
136
+ it must be 8 bytes long for encryption
137
+ and 10 bytes for decryption (in the latter case, it is
138
+ actually the *encrypted* IV which was prefixed to the ciphertext).
139
+
140
+ If not provided, a random byte string is generated (you must then
141
+ read its value with the :attr:`iv` attribute).
142
+
143
+ * **nonce** (*bytes*, *bytearray*, *memoryview*) --
144
+ (Only applicable for ``MODE_EAX`` and ``MODE_CTR``).
145
+
146
+ A value that must never be reused for any other encryption done
147
+ with this key.
148
+
149
+ For ``MODE_EAX`` there are no
150
+ restrictions on its length (recommended: **16** bytes).
151
+
152
+ For ``MODE_CTR``, its length must be in the range **[0..7]**.
153
+
154
+ If not provided for ``MODE_EAX``, a random byte string is generated (you
155
+ can read it back via the ``nonce`` attribute).
156
+
157
+ * **segment_size** (*integer*) --
158
+ (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
159
+ are segmented in. It must be a multiple of 8.
160
+ If not specified, it will be assumed to be 8.
161
+
162
+ * **mac_len** : (*integer*) --
163
+ (Only ``MODE_EAX``)
164
+ Length of the authentication tag, in bytes.
165
+ It must be no longer than 8 (default).
166
+
167
+ * **initial_value** : (*integer*) --
168
+ (Only ``MODE_CTR``). The initial value for the counter within
169
+ the counter block. By default it is **0**.
170
+
171
+ :Return: a Triple DES object, of the applicable mode.
172
+ """
173
+
174
+ return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
175
+
176
+ MODE_ECB = 1
177
+ MODE_CBC = 2
178
+ MODE_CFB = 3
179
+ MODE_OFB = 5
180
+ MODE_CTR = 6
181
+ MODE_OPENPGP = 7
182
+ MODE_EAX = 9
183
+
184
+ # Size of a data block (in bytes)
185
+ block_size = 8
186
+ # Size of a key (in bytes)
187
+ key_size = (16, 24)
gtm/lib/python3.12/site-packages/Crypto/Cipher/DES3.pyi ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict, Tuple, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ from Crypto.Cipher._mode_ecb import EcbMode
6
+ from Crypto.Cipher._mode_cbc import CbcMode
7
+ from Crypto.Cipher._mode_cfb import CfbMode
8
+ from Crypto.Cipher._mode_ofb import OfbMode
9
+ from Crypto.Cipher._mode_ctr import CtrMode
10
+ from Crypto.Cipher._mode_openpgp import OpenPgpMode
11
+ from Crypto.Cipher._mode_eax import EaxMode
12
+
13
+ def adjust_key_parity(key_in: bytes) -> bytes: ...
14
+
15
+ DES3Mode = int
16
+
17
+ MODE_ECB: DES3Mode
18
+ MODE_CBC: DES3Mode
19
+ MODE_CFB: DES3Mode
20
+ MODE_OFB: DES3Mode
21
+ MODE_CTR: DES3Mode
22
+ MODE_OPENPGP: DES3Mode
23
+ MODE_EAX: DES3Mode
24
+
25
+ def new(key: Buffer,
26
+ mode: DES3Mode,
27
+ iv : Optional[Buffer] = ...,
28
+ IV : Optional[Buffer] = ...,
29
+ nonce : Optional[Buffer] = ...,
30
+ segment_size : int = ...,
31
+ mac_len : int = ...,
32
+ initial_value : Union[int, Buffer] = ...,
33
+ counter : Dict = ...) -> \
34
+ Union[EcbMode, CbcMode, CfbMode, OfbMode, CtrMode, OpenPgpMode]: ...
35
+
36
+ block_size: int
37
+ key_size: Tuple[int, int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_OAEP.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/PKCS1_OAEP.py : PKCS#1 OAEP
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
+
23
+ from Crypto.Signature.pss import MGF1
24
+ import Crypto.Hash.SHA1
25
+
26
+ from Crypto.Util.py3compat import _copy_bytes
27
+ import Crypto.Util.number
28
+ from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes
29
+ from Crypto.Util.strxor import strxor
30
+ from Crypto import Random
31
+ from ._pkcs1_oaep_decode import oaep_decode
32
+
33
+
34
+ class PKCS1OAEP_Cipher:
35
+ """Cipher object for PKCS#1 v1.5 OAEP.
36
+ Do not create directly: use :func:`new` instead."""
37
+
38
+ def __init__(self, key, hashAlgo, mgfunc, label, randfunc):
39
+ """Initialize this PKCS#1 OAEP cipher object.
40
+
41
+ :Parameters:
42
+ key : an RSA key object
43
+ If a private half is given, both encryption and decryption are possible.
44
+ If a public half is given, only encryption is possible.
45
+ hashAlgo : hash object
46
+ The hash function to use. This can be a module under `Crypto.Hash`
47
+ or an existing hash object created from any of such modules. If not specified,
48
+ `Crypto.Hash.SHA1` is used.
49
+ mgfunc : callable
50
+ A mask generation function that accepts two parameters: a string to
51
+ use as seed, and the lenth of the mask to generate, in bytes.
52
+ If not specified, the standard MGF1 consistent with ``hashAlgo`` is used (a safe choice).
53
+ label : bytes/bytearray/memoryview
54
+ A label to apply to this particular encryption. If not specified,
55
+ an empty string is used. Specifying a label does not improve
56
+ security.
57
+ randfunc : callable
58
+ A function that returns random bytes.
59
+
60
+ :attention: Modify the mask generation function only if you know what you are doing.
61
+ Sender and receiver must use the same one.
62
+ """
63
+ self._key = key
64
+
65
+ if hashAlgo:
66
+ self._hashObj = hashAlgo
67
+ else:
68
+ self._hashObj = Crypto.Hash.SHA1
69
+
70
+ if mgfunc:
71
+ self._mgf = mgfunc
72
+ else:
73
+ self._mgf = lambda x, y: MGF1(x, y, self._hashObj)
74
+
75
+ self._label = _copy_bytes(None, None, label)
76
+ self._randfunc = randfunc
77
+
78
+ def can_encrypt(self):
79
+ """Legacy function to check if you can call :meth:`encrypt`.
80
+
81
+ .. deprecated:: 3.0"""
82
+ return self._key.can_encrypt()
83
+
84
+ def can_decrypt(self):
85
+ """Legacy function to check if you can call :meth:`decrypt`.
86
+
87
+ .. deprecated:: 3.0"""
88
+ return self._key.can_decrypt()
89
+
90
+ def encrypt(self, message):
91
+ """Encrypt a message with PKCS#1 OAEP.
92
+
93
+ :param message:
94
+ The message to encrypt, also known as plaintext. It can be of
95
+ variable length, but not longer than the RSA modulus (in bytes)
96
+ minus 2, minus twice the hash output size.
97
+ For instance, if you use RSA 2048 and SHA-256, the longest message
98
+ you can encrypt is 190 byte long.
99
+ :type message: bytes/bytearray/memoryview
100
+
101
+ :returns: The ciphertext, as large as the RSA modulus.
102
+ :rtype: bytes
103
+
104
+ :raises ValueError:
105
+ if the message is too long.
106
+ """
107
+
108
+ # See 7.1.1 in RFC3447
109
+ modBits = Crypto.Util.number.size(self._key.n)
110
+ k = ceil_div(modBits, 8) # Convert from bits to bytes
111
+ hLen = self._hashObj.digest_size
112
+ mLen = len(message)
113
+
114
+ # Step 1b
115
+ ps_len = k - mLen - 2 * hLen - 2
116
+ if ps_len < 0:
117
+ raise ValueError("Plaintext is too long.")
118
+ # Step 2a
119
+ lHash = self._hashObj.new(self._label).digest()
120
+ # Step 2b
121
+ ps = b'\x00' * ps_len
122
+ # Step 2c
123
+ db = lHash + ps + b'\x01' + _copy_bytes(None, None, message)
124
+ # Step 2d
125
+ ros = self._randfunc(hLen)
126
+ # Step 2e
127
+ dbMask = self._mgf(ros, k-hLen-1)
128
+ # Step 2f
129
+ maskedDB = strxor(db, dbMask)
130
+ # Step 2g
131
+ seedMask = self._mgf(maskedDB, hLen)
132
+ # Step 2h
133
+ maskedSeed = strxor(ros, seedMask)
134
+ # Step 2i
135
+ em = b'\x00' + maskedSeed + maskedDB
136
+ # Step 3a (OS2IP)
137
+ em_int = bytes_to_long(em)
138
+ # Step 3b (RSAEP)
139
+ m_int = self._key._encrypt(em_int)
140
+ # Step 3c (I2OSP)
141
+ c = long_to_bytes(m_int, k)
142
+ return c
143
+
144
+ def decrypt(self, ciphertext):
145
+ """Decrypt a message with PKCS#1 OAEP.
146
+
147
+ :param ciphertext: The encrypted message.
148
+ :type ciphertext: bytes/bytearray/memoryview
149
+
150
+ :returns: The original message (plaintext).
151
+ :rtype: bytes
152
+
153
+ :raises ValueError:
154
+ if the ciphertext has the wrong length, or if decryption
155
+ fails the integrity check (in which case, the decryption
156
+ key is probably wrong).
157
+ :raises TypeError:
158
+ if the RSA key has no private half (i.e. you are trying
159
+ to decrypt using a public key).
160
+ """
161
+
162
+ # See 7.1.2 in RFC3447
163
+ modBits = Crypto.Util.number.size(self._key.n)
164
+ k = ceil_div(modBits, 8) # Convert from bits to bytes
165
+ hLen = self._hashObj.digest_size
166
+
167
+ # Step 1b and 1c
168
+ if len(ciphertext) != k or k < hLen+2:
169
+ raise ValueError("Ciphertext with incorrect length.")
170
+ # Step 2a (O2SIP)
171
+ ct_int = bytes_to_long(ciphertext)
172
+ # Step 2b (RSADP) and step 2c (I2OSP)
173
+ em = self._key._decrypt_to_bytes(ct_int)
174
+ # Step 3a
175
+ lHash = self._hashObj.new(self._label).digest()
176
+ # y must be 0, but we MUST NOT check it here in order not to
177
+ # allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143)
178
+ maskedSeed = em[1:hLen+1]
179
+ maskedDB = em[hLen+1:]
180
+ # Step 3c
181
+ seedMask = self._mgf(maskedDB, hLen)
182
+ # Step 3d
183
+ seed = strxor(maskedSeed, seedMask)
184
+ # Step 3e
185
+ dbMask = self._mgf(seed, k-hLen-1)
186
+ # Step 3f
187
+ db = strxor(maskedDB, dbMask)
188
+ # Step 3b + 3g
189
+ res = oaep_decode(em, lHash, db)
190
+ if res <= 0:
191
+ raise ValueError("Incorrect decryption.")
192
+ # Step 4
193
+ return db[res:]
194
+
195
+
196
+ def new(key, hashAlgo=None, mgfunc=None, label=b'', randfunc=None):
197
+ """Return a cipher object :class:`PKCS1OAEP_Cipher`
198
+ that can be used to perform PKCS#1 OAEP encryption or decryption.
199
+
200
+ :param key:
201
+ The key object to use to encrypt or decrypt the message.
202
+ Decryption is only possible with a private RSA key.
203
+ :type key: RSA key object
204
+
205
+ :param hashAlgo:
206
+ The hash function to use. This can be a module under `Crypto.Hash`
207
+ or an existing hash object created from any of such modules.
208
+ If not specified, `Crypto.Hash.SHA1` is used.
209
+ :type hashAlgo: hash object
210
+
211
+ :param mgfunc:
212
+ A mask generation function that accepts two parameters: a string to
213
+ use as seed, and the lenth of the mask to generate, in bytes.
214
+ If not specified, the standard MGF1 consistent with ``hashAlgo`` is used (a safe choice).
215
+ :type mgfunc: callable
216
+
217
+ :param label:
218
+ A label to apply to this particular encryption. If not specified,
219
+ an empty string is used. Specifying a label does not improve
220
+ security.
221
+ :type label: bytes/bytearray/memoryview
222
+
223
+ :param randfunc:
224
+ A function that returns random bytes.
225
+ The default is `Random.get_random_bytes`.
226
+ :type randfunc: callable
227
+ """
228
+
229
+ if randfunc is None:
230
+ randfunc = Random.get_random_bytes
231
+ return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label, randfunc)
gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_OAEP.pyi ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, Callable, Any, overload
2
+ from typing_extensions import Protocol
3
+
4
+ from Crypto.PublicKey.RSA import RsaKey
5
+
6
+ class HashLikeClass(Protocol):
7
+ digest_size : int
8
+ def new(self, data: Optional[bytes] = ...) -> Any: ...
9
+
10
+ class HashLikeModule(Protocol):
11
+ digest_size : int
12
+ @staticmethod
13
+ def new(data: Optional[bytes] = ...) -> Any: ...
14
+
15
+ HashLike = Union[HashLikeClass, HashLikeModule]
16
+
17
+ Buffer = Union[bytes, bytearray, memoryview]
18
+
19
+ class PKCS1OAEP_Cipher:
20
+ def __init__(self,
21
+ key: RsaKey,
22
+ hashAlgo: HashLike,
23
+ mgfunc: Callable[[bytes, int], bytes],
24
+ label: Buffer,
25
+ randfunc: Callable[[int], bytes]) -> None: ...
26
+ def can_encrypt(self) -> bool: ...
27
+ def can_decrypt(self) -> bool: ...
28
+ def encrypt(self, message: Buffer) -> bytes: ...
29
+ def decrypt(self, ciphertext: Buffer) -> bytes: ...
30
+
31
+ def new(key: RsaKey,
32
+ hashAlgo: Optional[HashLike] = ...,
33
+ mgfunc: Optional[Callable[[bytes, int], bytes]] = ...,
34
+ label: Optional[Buffer] = ...,
35
+ randfunc: Optional[Callable[[int], bytes]] = ...) -> PKCS1OAEP_Cipher: ...
gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_v1_5.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/PKCS1-v1_5.py : PKCS#1 v1.5
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
+
23
+ __all__ = ['new', 'PKCS115_Cipher']
24
+
25
+ from Crypto import Random
26
+ from Crypto.Util.number import bytes_to_long, long_to_bytes
27
+ from Crypto.Util.py3compat import bord, is_bytes, _copy_bytes
28
+ from ._pkcs1_oaep_decode import pkcs1_decode
29
+
30
+
31
+ class PKCS115_Cipher:
32
+ """This cipher can perform PKCS#1 v1.5 RSA encryption or decryption.
33
+ Do not instantiate directly. Use :func:`Crypto.Cipher.PKCS1_v1_5.new` instead."""
34
+
35
+ def __init__(self, key, randfunc):
36
+ """Initialize this PKCS#1 v1.5 cipher object.
37
+
38
+ :Parameters:
39
+ key : an RSA key object
40
+ If a private half is given, both encryption and decryption are possible.
41
+ If a public half is given, only encryption is possible.
42
+ randfunc : callable
43
+ Function that returns random bytes.
44
+ """
45
+
46
+ self._key = key
47
+ self._randfunc = randfunc
48
+
49
+ def can_encrypt(self):
50
+ """Return True if this cipher object can be used for encryption."""
51
+ return self._key.can_encrypt()
52
+
53
+ def can_decrypt(self):
54
+ """Return True if this cipher object can be used for decryption."""
55
+ return self._key.can_decrypt()
56
+
57
+ def encrypt(self, message):
58
+ """Produce the PKCS#1 v1.5 encryption of a message.
59
+
60
+ This function is named ``RSAES-PKCS1-V1_5-ENCRYPT``, and it is specified in
61
+ `section 7.2.1 of RFC8017
62
+ <https://tools.ietf.org/html/rfc8017#page-28>`_.
63
+
64
+ :param message:
65
+ The message to encrypt, also known as plaintext. It can be of
66
+ variable length, but not longer than the RSA modulus (in bytes) minus 11.
67
+ :type message: bytes/bytearray/memoryview
68
+
69
+ :Returns: A byte string, the ciphertext in which the message is encrypted.
70
+ It is as long as the RSA modulus (in bytes).
71
+
72
+ :Raises ValueError:
73
+ If the RSA key length is not sufficiently long to deal with the given
74
+ message.
75
+ """
76
+
77
+ # See 7.2.1 in RFC8017
78
+ k = self._key.size_in_bytes()
79
+ mLen = len(message)
80
+
81
+ # Step 1
82
+ if mLen > k - 11:
83
+ raise ValueError("Plaintext is too long.")
84
+ # Step 2a
85
+ ps = []
86
+ while len(ps) != k - mLen - 3:
87
+ new_byte = self._randfunc(1)
88
+ if bord(new_byte[0]) == 0x00:
89
+ continue
90
+ ps.append(new_byte)
91
+ ps = b"".join(ps)
92
+ # Step 2b
93
+ em = b'\x00\x02' + ps + b'\x00' + _copy_bytes(None, None, message)
94
+ # Step 3a (OS2IP)
95
+ em_int = bytes_to_long(em)
96
+ # Step 3b (RSAEP)
97
+ m_int = self._key._encrypt(em_int)
98
+ # Step 3c (I2OSP)
99
+ c = long_to_bytes(m_int, k)
100
+ return c
101
+
102
+ def decrypt(self, ciphertext, sentinel, expected_pt_len=0):
103
+ r"""Decrypt a PKCS#1 v1.5 ciphertext.
104
+
105
+ This is the function ``RSAES-PKCS1-V1_5-DECRYPT`` specified in
106
+ `section 7.2.2 of RFC8017
107
+ <https://tools.ietf.org/html/rfc8017#page-29>`_.
108
+
109
+ Args:
110
+ ciphertext (bytes/bytearray/memoryview):
111
+ The ciphertext that contains the message to recover.
112
+ sentinel (any type):
113
+ The object to return whenever an error is detected.
114
+ expected_pt_len (integer):
115
+ The length the plaintext is known to have, or 0 if unknown.
116
+
117
+ Returns (byte string):
118
+ It is either the original message or the ``sentinel`` (in case of an error).
119
+
120
+ .. warning::
121
+ PKCS#1 v1.5 decryption is intrinsically vulnerable to timing
122
+ attacks (see `Bleichenbacher's`__ attack).
123
+ **Use PKCS#1 OAEP instead**.
124
+
125
+ This implementation attempts to mitigate the risk
126
+ with some constant-time constructs.
127
+ However, they are not sufficient by themselves: the type of protocol you
128
+ implement and the way you handle errors make a big difference.
129
+
130
+ Specifically, you should make it very hard for the (malicious)
131
+ party that submitted the ciphertext to quickly understand if decryption
132
+ succeeded or not.
133
+
134
+ To this end, it is recommended that your protocol only encrypts
135
+ plaintexts of fixed length (``expected_pt_len``),
136
+ that ``sentinel`` is a random byte string of the same length,
137
+ and that processing continues for as long
138
+ as possible even if ``sentinel`` is returned (i.e. in case of
139
+ incorrect decryption).
140
+
141
+ .. __: https://dx.doi.org/10.1007/BFb0055716
142
+ """
143
+
144
+ # See 7.2.2 in RFC8017
145
+ k = self._key.size_in_bytes()
146
+
147
+ # Step 1
148
+ if len(ciphertext) != k:
149
+ raise ValueError("Ciphertext with incorrect length (not %d bytes)" % k)
150
+
151
+ # Step 2a (O2SIP)
152
+ ct_int = bytes_to_long(ciphertext)
153
+
154
+ # Step 2b (RSADP) and Step 2c (I2OSP)
155
+ em = self._key._decrypt_to_bytes(ct_int)
156
+
157
+ # Step 3 (not constant time when the sentinel is not a byte string)
158
+ output = bytes(bytearray(k))
159
+ if not is_bytes(sentinel) or len(sentinel) > k:
160
+ size = pkcs1_decode(em, b'', expected_pt_len, output)
161
+ if size < 0:
162
+ return sentinel
163
+ else:
164
+ return output[size:]
165
+
166
+ # Step 3 (somewhat constant time)
167
+ size = pkcs1_decode(em, sentinel, expected_pt_len, output)
168
+ return output[size:]
169
+
170
+
171
+ def new(key, randfunc=None):
172
+ """Create a cipher for performing PKCS#1 v1.5 encryption or decryption.
173
+
174
+ :param key:
175
+ The key to use to encrypt or decrypt the message. This is a `Crypto.PublicKey.RSA` object.
176
+ Decryption is only possible if *key* is a private RSA key.
177
+ :type key: RSA key object
178
+
179
+ :param randfunc:
180
+ Function that return random bytes.
181
+ The default is :func:`Crypto.Random.get_random_bytes`.
182
+ :type randfunc: callable
183
+
184
+ :returns: A cipher object `PKCS115_Cipher`.
185
+ """
186
+
187
+ if randfunc is None:
188
+ randfunc = Random.get_random_bytes
189
+ return PKCS115_Cipher(key, randfunc)
gtm/lib/python3.12/site-packages/Crypto/Cipher/PKCS1_v1_5.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union, Any, Optional, TypeVar
2
+
3
+ from Crypto.PublicKey.RSA import RsaKey
4
+
5
+ Buffer = Union[bytes, bytearray, memoryview]
6
+ T = TypeVar('T')
7
+
8
+ class PKCS115_Cipher:
9
+ def __init__(self,
10
+ key: RsaKey,
11
+ randfunc: Callable[[int], bytes]) -> None: ...
12
+ def can_encrypt(self) -> bool: ...
13
+ def can_decrypt(self) -> bool: ...
14
+ def encrypt(self, message: Buffer) -> bytes: ...
15
+ def decrypt(self, ciphertext: Buffer,
16
+ sentinel: T,
17
+ expected_pt_len: Optional[int] = ...) -> Union[bytes, T]: ...
18
+
19
+ def new(key: RsaKey,
20
+ randfunc: Optional[Callable[[int], bytes]] = ...) -> PKCS115_Cipher: ...
gtm/lib/python3.12/site-packages/Crypto/Cipher/Salsa20.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/Salsa20.py : Salsa20 stream cipher (http://cr.yp.to/snuffle.html)
4
+ #
5
+ # Contributed by Fabrizio Tarizzo <[email protected]>.
6
+ #
7
+ # ===================================================================
8
+ # The contents of this file are dedicated to the public domain. To
9
+ # the extent that dedication to the public domain is not available,
10
+ # everyone is granted a worldwide, perpetual, royalty-free,
11
+ # non-exclusive license to exercise all rights associated with the
12
+ # contents of this file for any purpose whatsoever.
13
+ # No rights are reserved.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19
+ # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20
+ # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ # ===================================================================
24
+
25
+ from Crypto.Util.py3compat import _copy_bytes
26
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
27
+ create_string_buffer,
28
+ get_raw_buffer, VoidPointer,
29
+ SmartPointer, c_size_t,
30
+ c_uint8_ptr, is_writeable_buffer)
31
+
32
+ from Crypto.Random import get_random_bytes
33
+
34
+ _raw_salsa20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._Salsa20",
35
+ """
36
+ int Salsa20_stream_init(uint8_t *key, size_t keylen,
37
+ uint8_t *nonce, size_t nonce_len,
38
+ void **pSalsaState);
39
+ int Salsa20_stream_destroy(void *salsaState);
40
+ int Salsa20_stream_encrypt(void *salsaState,
41
+ const uint8_t in[],
42
+ uint8_t out[], size_t len);
43
+ """)
44
+
45
+
46
+ class Salsa20Cipher:
47
+ """Salsa20 cipher object. Do not create it directly. Use :py:func:`new`
48
+ instead.
49
+
50
+ :var nonce: The nonce with length 8
51
+ :vartype nonce: byte string
52
+ """
53
+
54
+ def __init__(self, key, nonce):
55
+ """Initialize a Salsa20 cipher object
56
+
57
+ See also `new()` at the module level."""
58
+
59
+ if len(key) not in key_size:
60
+ raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key))
61
+
62
+ if len(nonce) != 8:
63
+ raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" %
64
+ len(nonce))
65
+
66
+ self.nonce = _copy_bytes(None, None, nonce)
67
+
68
+ self._state = VoidPointer()
69
+ result = _raw_salsa20_lib.Salsa20_stream_init(
70
+ c_uint8_ptr(key),
71
+ c_size_t(len(key)),
72
+ c_uint8_ptr(nonce),
73
+ c_size_t(len(nonce)),
74
+ self._state.address_of())
75
+ if result:
76
+ raise ValueError("Error %d instantiating a Salsa20 cipher")
77
+ self._state = SmartPointer(self._state.get(),
78
+ _raw_salsa20_lib.Salsa20_stream_destroy)
79
+
80
+ self.block_size = 1
81
+ self.key_size = len(key)
82
+
83
+ def encrypt(self, plaintext, output=None):
84
+ """Encrypt a piece of data.
85
+
86
+ Args:
87
+ plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
88
+ Keyword Args:
89
+ output(bytes/bytearray/memoryview): The location where the ciphertext
90
+ is written to. If ``None``, the ciphertext is returned.
91
+ Returns:
92
+ If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
93
+ Otherwise, ``None``.
94
+ """
95
+
96
+ if output is None:
97
+ ciphertext = create_string_buffer(len(plaintext))
98
+ else:
99
+ ciphertext = output
100
+
101
+ if not is_writeable_buffer(output):
102
+ raise TypeError("output must be a bytearray or a writeable memoryview")
103
+
104
+ if len(plaintext) != len(output):
105
+ raise ValueError("output must have the same length as the input"
106
+ " (%d bytes)" % len(plaintext))
107
+
108
+ result = _raw_salsa20_lib.Salsa20_stream_encrypt(
109
+ self._state.get(),
110
+ c_uint8_ptr(plaintext),
111
+ c_uint8_ptr(ciphertext),
112
+ c_size_t(len(plaintext)))
113
+ if result:
114
+ raise ValueError("Error %d while encrypting with Salsa20" % result)
115
+
116
+ if output is None:
117
+ return get_raw_buffer(ciphertext)
118
+ else:
119
+ return None
120
+
121
+ def decrypt(self, ciphertext, output=None):
122
+ """Decrypt a piece of data.
123
+
124
+ Args:
125
+ ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
126
+ Keyword Args:
127
+ output(bytes/bytearray/memoryview): The location where the plaintext
128
+ is written to. If ``None``, the plaintext is returned.
129
+ Returns:
130
+ If ``output`` is ``None``, the plaintext is returned as ``bytes``.
131
+ Otherwise, ``None``.
132
+ """
133
+
134
+ try:
135
+ return self.encrypt(ciphertext, output=output)
136
+ except ValueError as e:
137
+ raise ValueError(str(e).replace("enc", "dec"))
138
+
139
+
140
+ def new(key, nonce=None):
141
+ """Create a new Salsa20 cipher
142
+
143
+ :keyword key: The secret key to use. It must be 16 or 32 bytes long.
144
+ :type key: bytes/bytearray/memoryview
145
+
146
+ :keyword nonce:
147
+ A value that must never be reused for any other encryption
148
+ done with this key. It must be 8 bytes long.
149
+
150
+ If not provided, a random byte string will be generated (you can read
151
+ it back via the ``nonce`` attribute of the returned object).
152
+ :type nonce: bytes/bytearray/memoryview
153
+
154
+ :Return: a :class:`Crypto.Cipher.Salsa20.Salsa20Cipher` object
155
+ """
156
+
157
+ if nonce is None:
158
+ nonce = get_random_bytes(8)
159
+
160
+ return Salsa20Cipher(key, nonce)
161
+
162
+ # Size of a data block (in bytes)
163
+ block_size = 1
164
+
165
+ # Size of a key (in bytes)
166
+ key_size = (16, 32)
167
+
gtm/lib/python3.12/site-packages/Crypto/Cipher/Salsa20.pyi ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Tuple, Optional, overload, Optional
2
+
3
+ Buffer = bytes|bytearray|memoryview
4
+
5
+ class Salsa20Cipher:
6
+ nonce: bytes
7
+ block_size: int
8
+ key_size: int
9
+
10
+ def __init__(self,
11
+ key: Buffer,
12
+ nonce: Buffer) -> None: ...
13
+ @overload
14
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
15
+ @overload
16
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
17
+ @overload
18
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
19
+ @overload
20
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
21
+
22
+ def new(key: Buffer, nonce: Optional[Buffer] = ...) -> Salsa20Cipher: ...
23
+
24
+ block_size: int
25
+ key_size: Tuple[int, int]
26
+
gtm/lib/python3.12/site-packages/Crypto/Cipher/_ARC4.abi3.so ADDED
Binary file (33.6 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/_EKSBlowfish.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2019, Legrandin <[email protected]>
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions
8
+ # are met:
9
+ #
10
+ # 1. Redistributions of source code must retain the above copyright
11
+ # notice, this list of conditions and the following disclaimer.
12
+ # 2. Redistributions in binary form must reproduce the above copyright
13
+ # notice, this list of conditions and the following disclaimer in
14
+ # the documentation and/or other materials provided with the
15
+ # distribution.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21
+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
+ # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+ # ===================================================================
30
+
31
+ import sys
32
+
33
+ from Crypto.Cipher import _create_cipher
34
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
35
+ VoidPointer, SmartPointer, c_size_t,
36
+ c_uint8_ptr, c_uint)
37
+
38
+ _raw_blowfish_lib = load_pycryptodome_raw_lib(
39
+ "Crypto.Cipher._raw_eksblowfish",
40
+ """
41
+ int EKSBlowfish_start_operation(const uint8_t key[],
42
+ size_t key_len,
43
+ const uint8_t salt[16],
44
+ size_t salt_len,
45
+ unsigned cost,
46
+ unsigned invert,
47
+ void **pResult);
48
+ int EKSBlowfish_encrypt(const void *state,
49
+ const uint8_t *in,
50
+ uint8_t *out,
51
+ size_t data_len);
52
+ int EKSBlowfish_decrypt(const void *state,
53
+ const uint8_t *in,
54
+ uint8_t *out,
55
+ size_t data_len);
56
+ int EKSBlowfish_stop_operation(void *state);
57
+ """
58
+ )
59
+
60
+
61
+ def _create_base_cipher(dict_parameters):
62
+ """This method instantiates and returns a smart pointer to
63
+ a low-level base cipher. It will absorb named parameters in
64
+ the process."""
65
+
66
+ try:
67
+ key = dict_parameters.pop("key")
68
+ salt = dict_parameters.pop("salt")
69
+ cost = dict_parameters.pop("cost")
70
+ except KeyError as e:
71
+ raise TypeError("Missing EKSBlowfish parameter: " + str(e))
72
+ invert = dict_parameters.pop("invert", True)
73
+
74
+ if len(key) not in key_size:
75
+ raise ValueError("Incorrect EKSBlowfish key length (%d bytes)" % len(key))
76
+
77
+ start_operation = _raw_blowfish_lib.EKSBlowfish_start_operation
78
+ stop_operation = _raw_blowfish_lib.EKSBlowfish_stop_operation
79
+
80
+ void_p = VoidPointer()
81
+ result = start_operation(c_uint8_ptr(key),
82
+ c_size_t(len(key)),
83
+ c_uint8_ptr(salt),
84
+ c_size_t(len(salt)),
85
+ c_uint(cost),
86
+ c_uint(int(invert)),
87
+ void_p.address_of())
88
+ if result:
89
+ raise ValueError("Error %X while instantiating the EKSBlowfish cipher"
90
+ % result)
91
+ return SmartPointer(void_p.get(), stop_operation)
92
+
93
+
94
+ def new(key, mode, salt, cost, invert):
95
+ """Create a new EKSBlowfish cipher
96
+
97
+ Args:
98
+
99
+ key (bytes, bytearray, memoryview):
100
+ The secret key to use in the symmetric cipher.
101
+ Its length can vary from 0 to 72 bytes.
102
+
103
+ mode (one of the supported ``MODE_*`` constants):
104
+ The chaining mode to use for encryption or decryption.
105
+
106
+ salt (bytes, bytearray, memoryview):
107
+ The salt that bcrypt uses to thwart rainbow table attacks
108
+
109
+ cost (integer):
110
+ The complexity factor in bcrypt
111
+
112
+ invert (bool):
113
+ If ``False``, in the inner loop use ``ExpandKey`` first over the salt
114
+ and then over the key, as defined in
115
+ the `original bcrypt specification <https://www.usenix.org/legacy/events/usenix99/provos/provos_html/node4.html>`_.
116
+ If ``True``, reverse the order, as in the first implementation of
117
+ `bcrypt` in OpenBSD.
118
+
119
+ :Return: an EKSBlowfish object
120
+ """
121
+
122
+ kwargs = { 'salt':salt, 'cost':cost, 'invert':invert }
123
+ return _create_cipher(sys.modules[__name__], key, mode, **kwargs)
124
+
125
+
126
+ MODE_ECB = 1
127
+
128
+ # Size of a data block (in bytes)
129
+ block_size = 8
130
+ # Size of a key (in bytes)
131
+ key_size = range(0, 72 + 1)
gtm/lib/python3.12/site-packages/Crypto/Cipher/_EKSBlowfish.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Iterable
2
+
3
+ from Crypto.Cipher._mode_ecb import EcbMode
4
+
5
+ MODE_ECB: int
6
+
7
+ Buffer = Union[bytes, bytearray, memoryview]
8
+
9
+ def new(key: Buffer,
10
+ mode: int,
11
+ salt: Buffer,
12
+ cost: int) -> EcbMode: ...
13
+
14
+ block_size: int
15
+ key_size: Iterable[int]
gtm/lib/python3.12/site-packages/Crypto/Cipher/_Salsa20.abi3.so ADDED
Binary file (34.1 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__init__.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # A block cipher is instantiated as a combination of:
3
+ # 1. A base cipher (such as AES)
4
+ # 2. A mode of operation (such as CBC)
5
+ #
6
+ # Both items are implemented as C modules.
7
+ #
8
+ # The API of #1 is (replace "AES" with the name of the actual cipher):
9
+ # - AES_start_operaion(key) --> base_cipher_state
10
+ # - AES_encrypt(base_cipher_state, in, out, length)
11
+ # - AES_decrypt(base_cipher_state, in, out, length)
12
+ # - AES_stop_operation(base_cipher_state)
13
+ #
14
+ # Where base_cipher_state is AES_State, a struct with BlockBase (set of
15
+ # pointers to encrypt/decrypt/stop) followed by cipher-specific data.
16
+ #
17
+ # The API of #2 is (replace "CBC" with the name of the actual mode):
18
+ # - CBC_start_operation(base_cipher_state) --> mode_state
19
+ # - CBC_encrypt(mode_state, in, out, length)
20
+ # - CBC_decrypt(mode_state, in, out, length)
21
+ # - CBC_stop_operation(mode_state)
22
+ #
23
+ # where mode_state is a a pointer to base_cipher_state plus mode-specific data.
24
+
25
+ import os
26
+
27
+ from Crypto.Cipher._mode_ecb import _create_ecb_cipher
28
+ from Crypto.Cipher._mode_cbc import _create_cbc_cipher
29
+ from Crypto.Cipher._mode_cfb import _create_cfb_cipher
30
+ from Crypto.Cipher._mode_ofb import _create_ofb_cipher
31
+ from Crypto.Cipher._mode_ctr import _create_ctr_cipher
32
+ from Crypto.Cipher._mode_openpgp import _create_openpgp_cipher
33
+ from Crypto.Cipher._mode_ccm import _create_ccm_cipher
34
+ from Crypto.Cipher._mode_eax import _create_eax_cipher
35
+ from Crypto.Cipher._mode_siv import _create_siv_cipher
36
+ from Crypto.Cipher._mode_gcm import _create_gcm_cipher
37
+ from Crypto.Cipher._mode_ocb import _create_ocb_cipher
38
+
39
+ _modes = { 1:_create_ecb_cipher,
40
+ 2:_create_cbc_cipher,
41
+ 3:_create_cfb_cipher,
42
+ 5:_create_ofb_cipher,
43
+ 6:_create_ctr_cipher,
44
+ 7:_create_openpgp_cipher,
45
+ 9:_create_eax_cipher
46
+ }
47
+
48
+ _extra_modes = { 8:_create_ccm_cipher,
49
+ 10:_create_siv_cipher,
50
+ 11:_create_gcm_cipher,
51
+ 12:_create_ocb_cipher
52
+ }
53
+
54
+ def _create_cipher(factory, key, mode, *args, **kwargs):
55
+
56
+ kwargs["key"] = key
57
+
58
+ modes = dict(_modes)
59
+ if kwargs.pop("add_aes_modes", False):
60
+ modes.update(_extra_modes)
61
+ if not mode in modes:
62
+ raise ValueError("Mode not supported")
63
+
64
+ if args:
65
+ if mode in (8, 9, 10, 11, 12):
66
+ if len(args) > 1:
67
+ raise TypeError("Too many arguments for this mode")
68
+ kwargs["nonce"] = args[0]
69
+ elif mode in (2, 3, 5, 7):
70
+ if len(args) > 1:
71
+ raise TypeError("Too many arguments for this mode")
72
+ kwargs["IV"] = args[0]
73
+ elif mode == 6:
74
+ if len(args) > 0:
75
+ raise TypeError("Too many arguments for this mode")
76
+ elif mode == 1:
77
+ raise TypeError("IV is not meaningful for the ECB mode")
78
+
79
+ return modes[mode](factory, **kwargs)
gtm/lib/python3.12/site-packages/Crypto/Cipher/__init__.pyi ADDED
File without changes
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/AES.cpython-312.pyc ADDED
Binary file (8.19 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ARC2.cpython-312.pyc ADDED
Binary file (6.63 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ARC4.cpython-312.pyc ADDED
Binary file (4.87 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/Blowfish.cpython-312.pyc ADDED
Binary file (5.65 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/CAST.cpython-312.pyc ADDED
Binary file (5.76 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ChaCha20.cpython-312.pyc ADDED
Binary file (9.98 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/ChaCha20_Poly1305.cpython-312.pyc ADDED
Binary file (13.4 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/DES.cpython-312.pyc ADDED
Binary file (5.63 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/DES3.cpython-312.pyc ADDED
Binary file (6.99 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/PKCS1_OAEP.cpython-312.pyc ADDED
Binary file (8.94 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/PKCS1_v1_5.cpython-312.pyc ADDED
Binary file (7.05 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/Salsa20.cpython-312.pyc ADDED
Binary file (5.98 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/_EKSBlowfish.cpython-312.pyc ADDED
Binary file (4.39 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.16 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/_mode_cbc.cpython-312.pyc ADDED
Binary file (9.63 kB). View file
 
gtm/lib/python3.12/site-packages/Crypto/Cipher/__pycache__/_mode_ccm.cpython-312.pyc ADDED
Binary file (24.7 kB). View file