ZTWHHH commited on
Commit
315a130
·
verified ·
1 Parent(s): 876cf05

Add files using upload-large-folder tool

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 +2 -0
  2. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/AES.pyi +156 -0
  3. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ARC2.py +175 -0
  4. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ARC2.pyi +35 -0
  5. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ARC4.pyi +16 -0
  6. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/CAST.py +159 -0
  7. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ChaCha20.py +287 -0
  8. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ChaCha20.pyi +25 -0
  9. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ChaCha20_Poly1305.pyi +28 -0
  10. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/DES.py +158 -0
  11. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/DES.pyi +35 -0
  12. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/DES3.pyi +37 -0
  13. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/PKCS1_OAEP.pyi +35 -0
  14. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/PKCS1_v1_5.py +189 -0
  15. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_ARC4.abi3.so +0 -0
  16. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_EKSBlowfish.py +131 -0
  17. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_EKSBlowfish.pyi +15 -0
  18. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_Salsa20.abi3.so +0 -0
  19. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/__init__.py +79 -0
  20. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_cbc.pyi +25 -0
  21. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ccm.py +650 -0
  22. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ccm.pyi +47 -0
  23. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_cfb.pyi +26 -0
  24. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ctr.py +393 -0
  25. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ctr.pyi +27 -0
  26. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_eax.pyi +45 -0
  27. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ecb.pyi +19 -0
  28. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_gcm.py +620 -0
  29. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ocb.pyi +36 -0
  30. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ofb.py +282 -0
  31. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ofb.pyi +25 -0
  32. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_openpgp.py +206 -0
  33. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_openpgp.pyi +20 -0
  34. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_siv.py +392 -0
  35. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_pkcs1_decode.abi3.so +0 -0
  36. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_pkcs1_oaep_decode.py +41 -0
  37. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_aesni.abi3.so +3 -0
  38. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_arc2.abi3.so +0 -0
  39. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_cfb.abi3.so +0 -0
  40. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_ctr.abi3.so +0 -0
  41. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_des.abi3.so +0 -0
  42. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_des3.abi3.so +0 -0
  43. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_ecb.abi3.so +0 -0
  44. minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_ocb.abi3.so +0 -0
  45. minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/RIPEMD.cpython-310.pyc +0 -0
  46. minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/SHA3_384.cpython-310.pyc +0 -0
  47. minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/TurboSHAKE128.cpython-310.pyc +0 -0
  48. minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/__init__.cpython-310.pyc +0 -0
  49. minigpt2/lib/python3.10/site-packages/Crypto/Util/Counter.py +79 -0
  50. minigpt2/lib/python3.10/site-packages/Crypto/Util/Padding.py +108 -0
.gitattributes CHANGED
@@ -1346,3 +1346,5 @@ minigpt2/lib/python3.10/site-packages/ray/data/__pycache__/dataset.cpython-310.p
1346
  minigpt2/lib/python3.10/site-packages/ray/data/__pycache__/read_api.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1347
  llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1348
  llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
1346
  minigpt2/lib/python3.10/site-packages/ray/data/__pycache__/read_api.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1347
  llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1348
  llava/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1349
+ minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_aesni.abi3.so filter=lfs diff=lfs merge=lfs -text
1350
+ minigpt2/lib/python3.10/site-packages/imageio/plugins/__pycache__/_tifffile.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
minigpt2/lib/python3.10/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]
minigpt2/lib/python3.10/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)
minigpt2/lib/python3.10/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]
minigpt2/lib/python3.10/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]
minigpt2/lib/python3.10/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)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/ChaCha20.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
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
minigpt2/lib/python3.10/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
minigpt2/lib/python3.10/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
minigpt2/lib/python3.10/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
minigpt2/lib/python3.10/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
minigpt2/lib/python3.10/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]
minigpt2/lib/python3.10/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: ...
minigpt2/lib/python3.10/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)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_ARC4.abi3.so ADDED
Binary file (21 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_EKSBlowfish.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2019, Legrandin <helderijs@gmail.com>
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)
minigpt2/lib/python3.10/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]
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_Salsa20.abi3.so ADDED
Binary file (27 kB). View file
 
minigpt2/lib/python3.10/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)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_cbc.pyi ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, overload
2
+
3
+ from Crypto.Util._raw_api import SmartPointer
4
+
5
+ Buffer = Union[bytes, bytearray, memoryview]
6
+
7
+ __all__ = ['CbcMode']
8
+
9
+ class CbcMode(object):
10
+ block_size: int
11
+ iv: Buffer
12
+ IV: Buffer
13
+
14
+ def __init__(self,
15
+ block_cipher: SmartPointer,
16
+ iv: Buffer) -> None: ...
17
+ @overload
18
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
19
+ @overload
20
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
21
+ @overload
22
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
23
+ @overload
24
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
25
+
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ccm.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
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
+ """
32
+ Counter with CBC-MAC (CCM) mode.
33
+ """
34
+
35
+ __all__ = ['CcmMode']
36
+
37
+ import struct
38
+ from binascii import unhexlify
39
+
40
+ from Crypto.Util.py3compat import (byte_string, bord,
41
+ _copy_bytes)
42
+ from Crypto.Util._raw_api import is_writeable_buffer
43
+
44
+ from Crypto.Util.strxor import strxor
45
+ from Crypto.Util.number import long_to_bytes
46
+
47
+ from Crypto.Hash import BLAKE2s
48
+ from Crypto.Random import get_random_bytes
49
+
50
+
51
+ def enum(**enums):
52
+ return type('Enum', (), enums)
53
+
54
+ MacStatus = enum(NOT_STARTED=0, PROCESSING_AUTH_DATA=1, PROCESSING_PLAINTEXT=2)
55
+
56
+
57
+ class CcmMode(object):
58
+ """Counter with CBC-MAC (CCM).
59
+
60
+ This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
61
+ It provides both confidentiality and authenticity.
62
+
63
+ The header of the message may be left in the clear, if needed, and it will
64
+ still be subject to authentication. The decryption step tells the receiver
65
+ if the message comes from a source that really knowns the secret key.
66
+ Additionally, decryption detects if any part of the message - including the
67
+ header - has been modified or corrupted.
68
+
69
+ This mode requires a nonce. The nonce shall never repeat for two
70
+ different messages encrypted with the same key, but it does not need
71
+ to be random.
72
+ Note that there is a trade-off between the size of the nonce and the
73
+ maximum size of a single message you can encrypt.
74
+
75
+ It is important to use a large nonce if the key is reused across several
76
+ messages and the nonce is chosen randomly.
77
+
78
+ It is acceptable to us a short nonce if the key is only used a few times or
79
+ if the nonce is taken from a counter.
80
+
81
+ The following table shows the trade-off when the nonce is chosen at
82
+ random. The column on the left shows how many messages it takes
83
+ for the keystream to repeat **on average**. In practice, you will want to
84
+ stop using the key way before that.
85
+
86
+ +--------------------+---------------+-------------------+
87
+ | Avg. # of messages | nonce | Max. message |
88
+ | before keystream | size | size |
89
+ | repeats | (bytes) | (bytes) |
90
+ +====================+===============+===================+
91
+ | 2^52 | 13 | 64K |
92
+ +--------------------+---------------+-------------------+
93
+ | 2^48 | 12 | 16M |
94
+ +--------------------+---------------+-------------------+
95
+ | 2^44 | 11 | 4G |
96
+ +--------------------+---------------+-------------------+
97
+ | 2^40 | 10 | 1T |
98
+ +--------------------+---------------+-------------------+
99
+ | 2^36 | 9 | 64P |
100
+ +--------------------+---------------+-------------------+
101
+ | 2^32 | 8 | 16E |
102
+ +--------------------+---------------+-------------------+
103
+
104
+ This mode is only available for ciphers that operate on 128 bits blocks
105
+ (e.g. AES but not TDES).
106
+
107
+ See `NIST SP800-38C`_ or RFC3610_.
108
+
109
+ .. _`NIST SP800-38C`: http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf
110
+ .. _RFC3610: https://tools.ietf.org/html/rfc3610
111
+ .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
112
+
113
+ :undocumented: __init__
114
+ """
115
+
116
+ def __init__(self, factory, key, nonce, mac_len, msg_len, assoc_len,
117
+ cipher_params):
118
+
119
+ self.block_size = factory.block_size
120
+ """The block size of the underlying cipher, in bytes."""
121
+
122
+ self.nonce = _copy_bytes(None, None, nonce)
123
+ """The nonce used for this cipher instance"""
124
+
125
+ self._factory = factory
126
+ self._key = _copy_bytes(None, None, key)
127
+ self._mac_len = mac_len
128
+ self._msg_len = msg_len
129
+ self._assoc_len = assoc_len
130
+ self._cipher_params = cipher_params
131
+
132
+ self._mac_tag = None # Cache for MAC tag
133
+
134
+ if self.block_size != 16:
135
+ raise ValueError("CCM mode is only available for ciphers"
136
+ " that operate on 128 bits blocks")
137
+
138
+ # MAC tag length (Tlen)
139
+ if mac_len not in (4, 6, 8, 10, 12, 14, 16):
140
+ raise ValueError("Parameter 'mac_len' must be even"
141
+ " and in the range 4..16 (not %d)" % mac_len)
142
+
143
+ # Nonce value
144
+ if not (nonce and 7 <= len(nonce) <= 13):
145
+ raise ValueError("Length of parameter 'nonce' must be"
146
+ " in the range 7..13 bytes")
147
+
148
+ # Create MAC object (the tag will be the last block
149
+ # bytes worth of ciphertext)
150
+ self._mac = self._factory.new(key,
151
+ factory.MODE_CBC,
152
+ iv=b'\x00' * 16,
153
+ **cipher_params)
154
+ self._mac_status = MacStatus.NOT_STARTED
155
+ self._t = None
156
+
157
+ # Allowed transitions after initialization
158
+ self._next = ["update", "encrypt", "decrypt",
159
+ "digest", "verify"]
160
+
161
+ # Cumulative lengths
162
+ self._cumul_assoc_len = 0
163
+ self._cumul_msg_len = 0
164
+
165
+ # Cache for unaligned associated data/plaintext.
166
+ # This is a list with byte strings, but when the MAC starts,
167
+ # it will become a binary string no longer than the block size.
168
+ self._cache = []
169
+
170
+ # Start CTR cipher, by formatting the counter (A.3)
171
+ q = 15 - len(nonce) # length of Q, the encoded message length
172
+ self._cipher = self._factory.new(key,
173
+ self._factory.MODE_CTR,
174
+ nonce=struct.pack("B", q - 1) + self.nonce,
175
+ **cipher_params)
176
+
177
+ # S_0, step 6 in 6.1 for j=0
178
+ self._s_0 = self._cipher.encrypt(b'\x00' * 16)
179
+
180
+ # Try to start the MAC
181
+ if None not in (assoc_len, msg_len):
182
+ self._start_mac()
183
+
184
+ def _start_mac(self):
185
+
186
+ assert(self._mac_status == MacStatus.NOT_STARTED)
187
+ assert(None not in (self._assoc_len, self._msg_len))
188
+ assert(isinstance(self._cache, list))
189
+
190
+ # Formatting control information and nonce (A.2.1)
191
+ q = 15 - len(self.nonce) # length of Q, the encoded message length
192
+ flags = (64 * (self._assoc_len > 0) + 8 * ((self._mac_len - 2) // 2) +
193
+ (q - 1))
194
+ b_0 = struct.pack("B", flags) + self.nonce + long_to_bytes(self._msg_len, q)
195
+
196
+ # Formatting associated data (A.2.2)
197
+ # Encoded 'a' is concatenated with the associated data 'A'
198
+ assoc_len_encoded = b''
199
+ if self._assoc_len > 0:
200
+ if self._assoc_len < (2 ** 16 - 2 ** 8):
201
+ enc_size = 2
202
+ elif self._assoc_len < (2 ** 32):
203
+ assoc_len_encoded = b'\xFF\xFE'
204
+ enc_size = 4
205
+ else:
206
+ assoc_len_encoded = b'\xFF\xFF'
207
+ enc_size = 8
208
+ assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size)
209
+
210
+ # b_0 and assoc_len_encoded must be processed first
211
+ self._cache.insert(0, b_0)
212
+ self._cache.insert(1, assoc_len_encoded)
213
+
214
+ # Process all the data cached so far
215
+ first_data_to_mac = b"".join(self._cache)
216
+ self._cache = b""
217
+ self._mac_status = MacStatus.PROCESSING_AUTH_DATA
218
+ self._update(first_data_to_mac)
219
+
220
+ def _pad_cache_and_update(self):
221
+
222
+ assert(self._mac_status != MacStatus.NOT_STARTED)
223
+ assert(len(self._cache) < self.block_size)
224
+
225
+ # Associated data is concatenated with the least number
226
+ # of zero bytes (possibly none) to reach alignment to
227
+ # the 16 byte boundary (A.2.3)
228
+ len_cache = len(self._cache)
229
+ if len_cache > 0:
230
+ self._update(b'\x00' * (self.block_size - len_cache))
231
+
232
+ def update(self, assoc_data):
233
+ """Protect associated data
234
+
235
+ If there is any associated data, the caller has to invoke
236
+ this function one or more times, before using
237
+ ``decrypt`` or ``encrypt``.
238
+
239
+ By *associated data* it is meant any data (e.g. packet headers) that
240
+ will not be encrypted and will be transmitted in the clear.
241
+ However, the receiver is still able to detect any modification to it.
242
+ In CCM, the *associated data* is also called
243
+ *additional authenticated data* (AAD).
244
+
245
+ If there is no associated data, this method must not be called.
246
+
247
+ The caller may split associated data in segments of any size, and
248
+ invoke this method multiple times, each time with the next segment.
249
+
250
+ :Parameters:
251
+ assoc_data : bytes/bytearray/memoryview
252
+ A piece of associated data. There are no restrictions on its size.
253
+ """
254
+
255
+ if "update" not in self._next:
256
+ raise TypeError("update() can only be called"
257
+ " immediately after initialization")
258
+
259
+ self._next = ["update", "encrypt", "decrypt",
260
+ "digest", "verify"]
261
+
262
+ self._cumul_assoc_len += len(assoc_data)
263
+ if self._assoc_len is not None and \
264
+ self._cumul_assoc_len > self._assoc_len:
265
+ raise ValueError("Associated data is too long")
266
+
267
+ self._update(assoc_data)
268
+ return self
269
+
270
+ def _update(self, assoc_data_pt=b""):
271
+ """Update the MAC with associated data or plaintext
272
+ (without FSM checks)"""
273
+
274
+ # If MAC has not started yet, we just park the data into a list.
275
+ # If the data is mutable, we create a copy and store that instead.
276
+ if self._mac_status == MacStatus.NOT_STARTED:
277
+ if is_writeable_buffer(assoc_data_pt):
278
+ assoc_data_pt = _copy_bytes(None, None, assoc_data_pt)
279
+ self._cache.append(assoc_data_pt)
280
+ return
281
+
282
+ assert(len(self._cache) < self.block_size)
283
+
284
+ if len(self._cache) > 0:
285
+ filler = min(self.block_size - len(self._cache),
286
+ len(assoc_data_pt))
287
+ self._cache += _copy_bytes(None, filler, assoc_data_pt)
288
+ assoc_data_pt = _copy_bytes(filler, None, assoc_data_pt)
289
+
290
+ if len(self._cache) < self.block_size:
291
+ return
292
+
293
+ # The cache is exactly one block
294
+ self._t = self._mac.encrypt(self._cache)
295
+ self._cache = b""
296
+
297
+ update_len = len(assoc_data_pt) // self.block_size * self.block_size
298
+ self._cache = _copy_bytes(update_len, None, assoc_data_pt)
299
+ if update_len > 0:
300
+ self._t = self._mac.encrypt(assoc_data_pt[:update_len])[-16:]
301
+
302
+ def encrypt(self, plaintext, output=None):
303
+ """Encrypt data with the key set at initialization.
304
+
305
+ A cipher object is stateful: once you have encrypted a message
306
+ you cannot encrypt (or decrypt) another message using the same
307
+ object.
308
+
309
+ This method can be called only **once** if ``msg_len`` was
310
+ not passed at initialization.
311
+
312
+ If ``msg_len`` was given, the data to encrypt can be broken
313
+ up in two or more pieces and `encrypt` can be called
314
+ multiple times.
315
+
316
+ That is, the statement:
317
+
318
+ >>> c.encrypt(a) + c.encrypt(b)
319
+
320
+ is equivalent to:
321
+
322
+ >>> c.encrypt(a+b)
323
+
324
+ This function does not add any padding to the plaintext.
325
+
326
+ :Parameters:
327
+ plaintext : bytes/bytearray/memoryview
328
+ The piece of data to encrypt.
329
+ It can be of any length.
330
+ :Keywords:
331
+ output : bytearray/memoryview
332
+ The location where the ciphertext must be written to.
333
+ If ``None``, the ciphertext is returned.
334
+ :Return:
335
+ If ``output`` is ``None``, the ciphertext as ``bytes``.
336
+ Otherwise, ``None``.
337
+ """
338
+
339
+ if "encrypt" not in self._next:
340
+ raise TypeError("encrypt() can only be called after"
341
+ " initialization or an update()")
342
+ self._next = ["encrypt", "digest"]
343
+
344
+ # No more associated data allowed from now
345
+ if self._assoc_len is None:
346
+ assert(isinstance(self._cache, list))
347
+ self._assoc_len = sum([len(x) for x in self._cache])
348
+ if self._msg_len is not None:
349
+ self._start_mac()
350
+ else:
351
+ if self._cumul_assoc_len < self._assoc_len:
352
+ raise ValueError("Associated data is too short")
353
+
354
+ # Only once piece of plaintext accepted if message length was
355
+ # not declared in advance
356
+ if self._msg_len is None:
357
+ self._msg_len = len(plaintext)
358
+ self._start_mac()
359
+ self._next = ["digest"]
360
+
361
+ self._cumul_msg_len += len(plaintext)
362
+ if self._cumul_msg_len > self._msg_len:
363
+ raise ValueError("Message is too long")
364
+
365
+ if self._mac_status == MacStatus.PROCESSING_AUTH_DATA:
366
+ # Associated data is concatenated with the least number
367
+ # of zero bytes (possibly none) to reach alignment to
368
+ # the 16 byte boundary (A.2.3)
369
+ self._pad_cache_and_update()
370
+ self._mac_status = MacStatus.PROCESSING_PLAINTEXT
371
+
372
+ self._update(plaintext)
373
+ return self._cipher.encrypt(plaintext, output=output)
374
+
375
+ def decrypt(self, ciphertext, output=None):
376
+ """Decrypt data with the key set at initialization.
377
+
378
+ A cipher object is stateful: once you have decrypted a message
379
+ you cannot decrypt (or encrypt) another message with the same
380
+ object.
381
+
382
+ This method can be called only **once** if ``msg_len`` was
383
+ not passed at initialization.
384
+
385
+ If ``msg_len`` was given, the data to decrypt can be
386
+ broken up in two or more pieces and `decrypt` can be
387
+ called multiple times.
388
+
389
+ That is, the statement:
390
+
391
+ >>> c.decrypt(a) + c.decrypt(b)
392
+
393
+ is equivalent to:
394
+
395
+ >>> c.decrypt(a+b)
396
+
397
+ This function does not remove any padding from the plaintext.
398
+
399
+ :Parameters:
400
+ ciphertext : bytes/bytearray/memoryview
401
+ The piece of data to decrypt.
402
+ It can be of any length.
403
+ :Keywords:
404
+ output : bytearray/memoryview
405
+ The location where the plaintext must be written to.
406
+ If ``None``, the plaintext is returned.
407
+ :Return:
408
+ If ``output`` is ``None``, the plaintext as ``bytes``.
409
+ Otherwise, ``None``.
410
+ """
411
+
412
+ if "decrypt" not in self._next:
413
+ raise TypeError("decrypt() can only be called"
414
+ " after initialization or an update()")
415
+ self._next = ["decrypt", "verify"]
416
+
417
+ # No more associated data allowed from now
418
+ if self._assoc_len is None:
419
+ assert(isinstance(self._cache, list))
420
+ self._assoc_len = sum([len(x) for x in self._cache])
421
+ if self._msg_len is not None:
422
+ self._start_mac()
423
+ else:
424
+ if self._cumul_assoc_len < self._assoc_len:
425
+ raise ValueError("Associated data is too short")
426
+
427
+ # Only once piece of ciphertext accepted if message length was
428
+ # not declared in advance
429
+ if self._msg_len is None:
430
+ self._msg_len = len(ciphertext)
431
+ self._start_mac()
432
+ self._next = ["verify"]
433
+
434
+ self._cumul_msg_len += len(ciphertext)
435
+ if self._cumul_msg_len > self._msg_len:
436
+ raise ValueError("Message is too long")
437
+
438
+ if self._mac_status == MacStatus.PROCESSING_AUTH_DATA:
439
+ # Associated data is concatenated with the least number
440
+ # of zero bytes (possibly none) to reach alignment to
441
+ # the 16 byte boundary (A.2.3)
442
+ self._pad_cache_and_update()
443
+ self._mac_status = MacStatus.PROCESSING_PLAINTEXT
444
+
445
+ # Encrypt is equivalent to decrypt with the CTR mode
446
+ plaintext = self._cipher.encrypt(ciphertext, output=output)
447
+ if output is None:
448
+ self._update(plaintext)
449
+ else:
450
+ self._update(output)
451
+ return plaintext
452
+
453
+ def digest(self):
454
+ """Compute the *binary* MAC tag.
455
+
456
+ The caller invokes this function at the very end.
457
+
458
+ This method returns the MAC that shall be sent to the receiver,
459
+ together with the ciphertext.
460
+
461
+ :Return: the MAC, as a byte string.
462
+ """
463
+
464
+ if "digest" not in self._next:
465
+ raise TypeError("digest() cannot be called when decrypting"
466
+ " or validating a message")
467
+ self._next = ["digest"]
468
+ return self._digest()
469
+
470
+ def _digest(self):
471
+ if self._mac_tag:
472
+ return self._mac_tag
473
+
474
+ if self._assoc_len is None:
475
+ assert(isinstance(self._cache, list))
476
+ self._assoc_len = sum([len(x) for x in self._cache])
477
+ if self._msg_len is not None:
478
+ self._start_mac()
479
+ else:
480
+ if self._cumul_assoc_len < self._assoc_len:
481
+ raise ValueError("Associated data is too short")
482
+
483
+ if self._msg_len is None:
484
+ self._msg_len = 0
485
+ self._start_mac()
486
+
487
+ if self._cumul_msg_len != self._msg_len:
488
+ raise ValueError("Message is too short")
489
+
490
+ # Both associated data and payload are concatenated with the least
491
+ # number of zero bytes (possibly none) that align it to the
492
+ # 16 byte boundary (A.2.2 and A.2.3)
493
+ self._pad_cache_and_update()
494
+
495
+ # Step 8 in 6.1 (T xor MSB_Tlen(S_0))
496
+ self._mac_tag = strxor(self._t, self._s_0)[:self._mac_len]
497
+
498
+ return self._mac_tag
499
+
500
+ def hexdigest(self):
501
+ """Compute the *printable* MAC tag.
502
+
503
+ This method is like `digest`.
504
+
505
+ :Return: the MAC, as a hexadecimal string.
506
+ """
507
+ return "".join(["%02x" % bord(x) for x in self.digest()])
508
+
509
+ def verify(self, received_mac_tag):
510
+ """Validate the *binary* MAC tag.
511
+
512
+ The caller invokes this function at the very end.
513
+
514
+ This method checks if the decrypted message is indeed valid
515
+ (that is, if the key is correct) and it has not been
516
+ tampered with while in transit.
517
+
518
+ :Parameters:
519
+ received_mac_tag : bytes/bytearray/memoryview
520
+ This is the *binary* MAC, as received from the sender.
521
+ :Raises ValueError:
522
+ if the MAC does not match. The message has been tampered with
523
+ or the key is incorrect.
524
+ """
525
+
526
+ if "verify" not in self._next:
527
+ raise TypeError("verify() cannot be called"
528
+ " when encrypting a message")
529
+ self._next = ["verify"]
530
+
531
+ self._digest()
532
+ secret = get_random_bytes(16)
533
+
534
+ mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
535
+ mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
536
+
537
+ if mac1.digest() != mac2.digest():
538
+ raise ValueError("MAC check failed")
539
+
540
+ def hexverify(self, hex_mac_tag):
541
+ """Validate the *printable* MAC tag.
542
+
543
+ This method is like `verify`.
544
+
545
+ :Parameters:
546
+ hex_mac_tag : string
547
+ This is the *printable* MAC, as received from the sender.
548
+ :Raises ValueError:
549
+ if the MAC does not match. The message has been tampered with
550
+ or the key is incorrect.
551
+ """
552
+
553
+ self.verify(unhexlify(hex_mac_tag))
554
+
555
+ def encrypt_and_digest(self, plaintext, output=None):
556
+ """Perform encrypt() and digest() in one step.
557
+
558
+ :Parameters:
559
+ plaintext : bytes/bytearray/memoryview
560
+ The piece of data to encrypt.
561
+ :Keywords:
562
+ output : bytearray/memoryview
563
+ The location where the ciphertext must be written to.
564
+ If ``None``, the ciphertext is returned.
565
+ :Return:
566
+ a tuple with two items:
567
+
568
+ - the ciphertext, as ``bytes``
569
+ - the MAC tag, as ``bytes``
570
+
571
+ The first item becomes ``None`` when the ``output`` parameter
572
+ specified a location for the result.
573
+ """
574
+
575
+ return self.encrypt(plaintext, output=output), self.digest()
576
+
577
+ def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
578
+ """Perform decrypt() and verify() in one step.
579
+
580
+ :Parameters:
581
+ ciphertext : bytes/bytearray/memoryview
582
+ The piece of data to decrypt.
583
+ received_mac_tag : bytes/bytearray/memoryview
584
+ This is the *binary* MAC, as received from the sender.
585
+ :Keywords:
586
+ output : bytearray/memoryview
587
+ The location where the plaintext must be written to.
588
+ If ``None``, the plaintext is returned.
589
+ :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
590
+ parameter specified a location for the result.
591
+ :Raises ValueError:
592
+ if the MAC does not match. The message has been tampered with
593
+ or the key is incorrect.
594
+ """
595
+
596
+ plaintext = self.decrypt(ciphertext, output=output)
597
+ self.verify(received_mac_tag)
598
+ return plaintext
599
+
600
+
601
+ def _create_ccm_cipher(factory, **kwargs):
602
+ """Create a new block cipher, configured in CCM mode.
603
+
604
+ :Parameters:
605
+ factory : module
606
+ A symmetric cipher module from `Crypto.Cipher` (like
607
+ `Crypto.Cipher.AES`).
608
+
609
+ :Keywords:
610
+ key : bytes/bytearray/memoryview
611
+ The secret key to use in the symmetric cipher.
612
+
613
+ nonce : bytes/bytearray/memoryview
614
+ A value that must never be reused for any other encryption.
615
+
616
+ Its length must be in the range ``[7..13]``.
617
+ 11 or 12 bytes are reasonable values in general. Bear in
618
+ mind that with CCM there is a trade-off between nonce length and
619
+ maximum message size.
620
+
621
+ If not specified, a 11 byte long random string is used.
622
+
623
+ mac_len : integer
624
+ Length of the MAC, in bytes. It must be even and in
625
+ the range ``[4..16]``. The default is 16.
626
+
627
+ msg_len : integer
628
+ Length of the message to (de)cipher.
629
+ If not specified, ``encrypt`` or ``decrypt`` may only be called once.
630
+
631
+ assoc_len : integer
632
+ Length of the associated data.
633
+ If not specified, all data is internally buffered.
634
+ """
635
+
636
+ try:
637
+ key = key = kwargs.pop("key")
638
+ except KeyError as e:
639
+ raise TypeError("Missing parameter: " + str(e))
640
+
641
+ nonce = kwargs.pop("nonce", None) # N
642
+ if nonce is None:
643
+ nonce = get_random_bytes(11)
644
+ mac_len = kwargs.pop("mac_len", factory.block_size)
645
+ msg_len = kwargs.pop("msg_len", None) # p
646
+ assoc_len = kwargs.pop("assoc_len", None) # a
647
+ cipher_params = dict(kwargs)
648
+
649
+ return CcmMode(factory, key, nonce, mac_len, msg_len,
650
+ assoc_len, cipher_params)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ccm.pyi ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import ModuleType
2
+ from typing import Union, overload, Dict, Tuple, Optional
3
+
4
+ Buffer = Union[bytes, bytearray, memoryview]
5
+
6
+ __all__ = ['CcmMode']
7
+
8
+ class CcmMode(object):
9
+ block_size: int
10
+ nonce: bytes
11
+
12
+ def __init__(self,
13
+ factory: ModuleType,
14
+ key: Buffer,
15
+ nonce: Buffer,
16
+ mac_len: int,
17
+ msg_len: int,
18
+ assoc_len: int,
19
+ cipher_params: Dict) -> None: ...
20
+
21
+ def update(self, assoc_data: Buffer) -> CcmMode: ...
22
+
23
+ @overload
24
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
25
+ @overload
26
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
27
+ @overload
28
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
29
+ @overload
30
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
31
+
32
+ def digest(self) -> bytes: ...
33
+ def hexdigest(self) -> str: ...
34
+ def verify(self, received_mac_tag: Buffer) -> None: ...
35
+ def hexverify(self, hex_mac_tag: str) -> None: ...
36
+
37
+ @overload
38
+ def encrypt_and_digest(self,
39
+ plaintext: Buffer) -> Tuple[bytes, bytes]: ...
40
+ @overload
41
+ def encrypt_and_digest(self,
42
+ plaintext: Buffer,
43
+ output: Buffer) -> Tuple[None, bytes]: ...
44
+ def decrypt_and_verify(self,
45
+ ciphertext: Buffer,
46
+ received_mac_tag: Buffer,
47
+ output: Optional[Union[bytearray, memoryview]] = ...) -> bytes: ...
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_cfb.pyi ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, overload
2
+
3
+ from Crypto.Util._raw_api import SmartPointer
4
+
5
+ Buffer = Union[bytes, bytearray, memoryview]
6
+
7
+ __all__ = ['CfbMode']
8
+
9
+
10
+ class CfbMode(object):
11
+ block_size: int
12
+ iv: Buffer
13
+ IV: Buffer
14
+
15
+ def __init__(self,
16
+ block_cipher: SmartPointer,
17
+ iv: Buffer,
18
+ segment_size: int) -> None: ...
19
+ @overload
20
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
21
+ @overload
22
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
23
+ @overload
24
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
25
+ @overload
26
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ctr.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/mode_ctr.py : CTR mode
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
+ """
24
+ Counter (CTR) mode.
25
+ """
26
+
27
+ __all__ = ['CtrMode']
28
+
29
+ import struct
30
+
31
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
32
+ create_string_buffer, get_raw_buffer,
33
+ SmartPointer, c_size_t, c_uint8_ptr,
34
+ is_writeable_buffer)
35
+
36
+ from Crypto.Random import get_random_bytes
37
+ from Crypto.Util.py3compat import _copy_bytes, is_native_int
38
+ from Crypto.Util.number import long_to_bytes
39
+
40
+ raw_ctr_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ctr", """
41
+ int CTR_start_operation(void *cipher,
42
+ uint8_t initialCounterBlock[],
43
+ size_t initialCounterBlock_len,
44
+ size_t prefix_len,
45
+ unsigned counter_len,
46
+ unsigned littleEndian,
47
+ void **pResult);
48
+ int CTR_encrypt(void *ctrState,
49
+ const uint8_t *in,
50
+ uint8_t *out,
51
+ size_t data_len);
52
+ int CTR_decrypt(void *ctrState,
53
+ const uint8_t *in,
54
+ uint8_t *out,
55
+ size_t data_len);
56
+ int CTR_stop_operation(void *ctrState);"""
57
+ )
58
+
59
+
60
+ class CtrMode(object):
61
+ """*CounTeR (CTR)* mode.
62
+
63
+ This mode is very similar to ECB, in that
64
+ encryption of one block is done independently of all other blocks.
65
+
66
+ Unlike ECB, the block *position* contributes to the encryption
67
+ and no information leaks about symbol frequency.
68
+
69
+ Each message block is associated to a *counter* which
70
+ must be unique across all messages that get encrypted
71
+ with the same key (not just within the same message).
72
+ The counter is as big as the block size.
73
+
74
+ Counters can be generated in several ways. The most
75
+ straightword one is to choose an *initial counter block*
76
+ (which can be made public, similarly to the *IV* for the
77
+ other modes) and increment its lowest **m** bits by one
78
+ (modulo *2^m*) for each block. In most cases, **m** is
79
+ chosen to be half the block size.
80
+
81
+ See `NIST SP800-38A`_, Section 6.5 (for the mode) and
82
+ Appendix B (for how to manage the *initial counter block*).
83
+
84
+ .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
85
+
86
+ :undocumented: __init__
87
+ """
88
+
89
+ def __init__(self, block_cipher, initial_counter_block,
90
+ prefix_len, counter_len, little_endian):
91
+ """Create a new block cipher, configured in CTR mode.
92
+
93
+ :Parameters:
94
+ block_cipher : C pointer
95
+ A smart pointer to the low-level block cipher instance.
96
+
97
+ initial_counter_block : bytes/bytearray/memoryview
98
+ The initial plaintext to use to generate the key stream.
99
+
100
+ It is as large as the cipher block, and it embeds
101
+ the initial value of the counter.
102
+
103
+ This value must not be reused.
104
+ It shall contain a nonce or a random component.
105
+ Reusing the *initial counter block* for encryptions
106
+ performed with the same key compromises confidentiality.
107
+
108
+ prefix_len : integer
109
+ The amount of bytes at the beginning of the counter block
110
+ that never change.
111
+
112
+ counter_len : integer
113
+ The length in bytes of the counter embedded in the counter
114
+ block.
115
+
116
+ little_endian : boolean
117
+ True if the counter in the counter block is an integer encoded
118
+ in little endian mode. If False, it is big endian.
119
+ """
120
+
121
+ if len(initial_counter_block) == prefix_len + counter_len:
122
+ self.nonce = _copy_bytes(None, prefix_len, initial_counter_block)
123
+ """Nonce; not available if there is a fixed suffix"""
124
+
125
+ self._state = VoidPointer()
126
+ result = raw_ctr_lib.CTR_start_operation(block_cipher.get(),
127
+ c_uint8_ptr(initial_counter_block),
128
+ c_size_t(len(initial_counter_block)),
129
+ c_size_t(prefix_len),
130
+ counter_len,
131
+ little_endian,
132
+ self._state.address_of())
133
+ if result:
134
+ raise ValueError("Error %X while instantiating the CTR mode"
135
+ % result)
136
+
137
+ # Ensure that object disposal of this Python object will (eventually)
138
+ # free the memory allocated by the raw library for the cipher mode
139
+ self._state = SmartPointer(self._state.get(),
140
+ raw_ctr_lib.CTR_stop_operation)
141
+
142
+ # Memory allocated for the underlying block cipher is now owed
143
+ # by the cipher mode
144
+ block_cipher.release()
145
+
146
+ self.block_size = len(initial_counter_block)
147
+ """The block size of the underlying cipher, in bytes."""
148
+
149
+ self._next = ["encrypt", "decrypt"]
150
+
151
+ def encrypt(self, plaintext, output=None):
152
+ """Encrypt data with the key and the parameters set at initialization.
153
+
154
+ A cipher object is stateful: once you have encrypted a message
155
+ you cannot encrypt (or decrypt) another message using the same
156
+ object.
157
+
158
+ The data to encrypt can be broken up in two or
159
+ more pieces and `encrypt` can be called multiple times.
160
+
161
+ That is, the statement:
162
+
163
+ >>> c.encrypt(a) + c.encrypt(b)
164
+
165
+ is equivalent to:
166
+
167
+ >>> c.encrypt(a+b)
168
+
169
+ This function does not add any padding to the plaintext.
170
+
171
+ :Parameters:
172
+ plaintext : bytes/bytearray/memoryview
173
+ The piece of data to encrypt.
174
+ It can be of any length.
175
+ :Keywords:
176
+ output : bytearray/memoryview
177
+ The location where the ciphertext must be written to.
178
+ If ``None``, the ciphertext is returned.
179
+ :Return:
180
+ If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
181
+ Otherwise, ``None``.
182
+ """
183
+
184
+ if "encrypt" not in self._next:
185
+ raise TypeError("encrypt() cannot be called after decrypt()")
186
+ self._next = ["encrypt"]
187
+
188
+ if output is None:
189
+ ciphertext = create_string_buffer(len(plaintext))
190
+ else:
191
+ ciphertext = output
192
+
193
+ if not is_writeable_buffer(output):
194
+ raise TypeError("output must be a bytearray or a writeable memoryview")
195
+
196
+ if len(plaintext) != len(output):
197
+ raise ValueError("output must have the same length as the input"
198
+ " (%d bytes)" % len(plaintext))
199
+
200
+ result = raw_ctr_lib.CTR_encrypt(self._state.get(),
201
+ c_uint8_ptr(plaintext),
202
+ c_uint8_ptr(ciphertext),
203
+ c_size_t(len(plaintext)))
204
+ if result:
205
+ if result == 0x60002:
206
+ raise OverflowError("The counter has wrapped around in"
207
+ " CTR mode")
208
+ raise ValueError("Error %X while encrypting in CTR mode" % result)
209
+
210
+ if output is None:
211
+ return get_raw_buffer(ciphertext)
212
+ else:
213
+ return None
214
+
215
+ def decrypt(self, ciphertext, output=None):
216
+ """Decrypt data with the key and the parameters set at initialization.
217
+
218
+ A cipher object is stateful: once you have decrypted a message
219
+ you cannot decrypt (or encrypt) another message with the same
220
+ object.
221
+
222
+ The data to decrypt can be broken up in two or
223
+ more pieces and `decrypt` can be called multiple times.
224
+
225
+ That is, the statement:
226
+
227
+ >>> c.decrypt(a) + c.decrypt(b)
228
+
229
+ is equivalent to:
230
+
231
+ >>> c.decrypt(a+b)
232
+
233
+ This function does not remove any padding from the plaintext.
234
+
235
+ :Parameters:
236
+ ciphertext : bytes/bytearray/memoryview
237
+ The piece of data to decrypt.
238
+ It can be of any length.
239
+ :Keywords:
240
+ output : bytearray/memoryview
241
+ The location where the plaintext must be written to.
242
+ If ``None``, the plaintext is returned.
243
+ :Return:
244
+ If ``output`` is ``None``, the plaintext is returned as ``bytes``.
245
+ Otherwise, ``None``.
246
+ """
247
+
248
+ if "decrypt" not in self._next:
249
+ raise TypeError("decrypt() cannot be called after encrypt()")
250
+ self._next = ["decrypt"]
251
+
252
+ if output is None:
253
+ plaintext = create_string_buffer(len(ciphertext))
254
+ else:
255
+ plaintext = output
256
+
257
+ if not is_writeable_buffer(output):
258
+ raise TypeError("output must be a bytearray or a writeable memoryview")
259
+
260
+ if len(ciphertext) != len(output):
261
+ raise ValueError("output must have the same length as the input"
262
+ " (%d bytes)" % len(plaintext))
263
+
264
+ result = raw_ctr_lib.CTR_decrypt(self._state.get(),
265
+ c_uint8_ptr(ciphertext),
266
+ c_uint8_ptr(plaintext),
267
+ c_size_t(len(ciphertext)))
268
+ if result:
269
+ if result == 0x60002:
270
+ raise OverflowError("The counter has wrapped around in"
271
+ " CTR mode")
272
+ raise ValueError("Error %X while decrypting in CTR mode" % result)
273
+
274
+ if output is None:
275
+ return get_raw_buffer(plaintext)
276
+ else:
277
+ return None
278
+
279
+
280
+ def _create_ctr_cipher(factory, **kwargs):
281
+ """Instantiate a cipher object that performs CTR encryption/decryption.
282
+
283
+ :Parameters:
284
+ factory : module
285
+ The underlying block cipher, a module from ``Crypto.Cipher``.
286
+
287
+ :Keywords:
288
+ nonce : bytes/bytearray/memoryview
289
+ The fixed part at the beginning of the counter block - the rest is
290
+ the counter number that gets increased when processing the next block.
291
+ The nonce must be such that no two messages are encrypted under the
292
+ same key and the same nonce.
293
+
294
+ The nonce must be shorter than the block size (it can have
295
+ zero length; the counter is then as long as the block).
296
+
297
+ If this parameter is not present, a random nonce will be created with
298
+ length equal to half the block size. No random nonce shorter than
299
+ 64 bits will be created though - you must really think through all
300
+ security consequences of using such a short block size.
301
+
302
+ initial_value : posive integer or bytes/bytearray/memoryview
303
+ The initial value for the counter. If not present, the cipher will
304
+ start counting from 0. The value is incremented by one for each block.
305
+ The counter number is encoded in big endian mode.
306
+
307
+ counter : object
308
+ Instance of ``Crypto.Util.Counter``, which allows full customization
309
+ of the counter block. This parameter is incompatible to both ``nonce``
310
+ and ``initial_value``.
311
+
312
+ Any other keyword will be passed to the underlying block cipher.
313
+ See the relevant documentation for details (at least ``key`` will need
314
+ to be present).
315
+ """
316
+
317
+ cipher_state = factory._create_base_cipher(kwargs)
318
+
319
+ counter = kwargs.pop("counter", None)
320
+ nonce = kwargs.pop("nonce", None)
321
+ initial_value = kwargs.pop("initial_value", None)
322
+ if kwargs:
323
+ raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs))
324
+
325
+ if counter is not None and (nonce, initial_value) != (None, None):
326
+ raise TypeError("'counter' and 'nonce'/'initial_value'"
327
+ " are mutually exclusive")
328
+
329
+ if counter is None:
330
+ # Crypto.Util.Counter is not used
331
+ if nonce is None:
332
+ if factory.block_size < 16:
333
+ raise TypeError("Impossible to create a safe nonce for short"
334
+ " block sizes")
335
+ nonce = get_random_bytes(factory.block_size // 2)
336
+ else:
337
+ if len(nonce) >= factory.block_size:
338
+ raise ValueError("Nonce is too long")
339
+
340
+ # What is not nonce is counter
341
+ counter_len = factory.block_size - len(nonce)
342
+
343
+ if initial_value is None:
344
+ initial_value = 0
345
+
346
+ if is_native_int(initial_value):
347
+ if (1 << (counter_len * 8)) - 1 < initial_value:
348
+ raise ValueError("Initial counter value is too large")
349
+ initial_counter_block = nonce + long_to_bytes(initial_value, counter_len)
350
+ else:
351
+ if len(initial_value) != counter_len:
352
+ raise ValueError("Incorrect length for counter byte string (%d bytes, expected %d)" %
353
+ (len(initial_value), counter_len))
354
+ initial_counter_block = nonce + initial_value
355
+
356
+ return CtrMode(cipher_state,
357
+ initial_counter_block,
358
+ len(nonce), # prefix
359
+ counter_len,
360
+ False) # little_endian
361
+
362
+ # Crypto.Util.Counter is used
363
+
364
+ # 'counter' used to be a callable object, but now it is
365
+ # just a dictionary for backward compatibility.
366
+ _counter = dict(counter)
367
+ try:
368
+ counter_len = _counter.pop("counter_len")
369
+ prefix = _counter.pop("prefix")
370
+ suffix = _counter.pop("suffix")
371
+ initial_value = _counter.pop("initial_value")
372
+ little_endian = _counter.pop("little_endian")
373
+ except KeyError:
374
+ raise TypeError("Incorrect counter object"
375
+ " (use Crypto.Util.Counter.new)")
376
+
377
+ # Compute initial counter block
378
+ words = []
379
+ while initial_value > 0:
380
+ words.append(struct.pack('B', initial_value & 255))
381
+ initial_value >>= 8
382
+ words += [b'\x00'] * max(0, counter_len - len(words))
383
+ if not little_endian:
384
+ words.reverse()
385
+ initial_counter_block = prefix + b"".join(words) + suffix
386
+
387
+ if len(initial_counter_block) != factory.block_size:
388
+ raise ValueError("Size of the counter block (%d bytes) must match"
389
+ " block size (%d)" % (len(initial_counter_block),
390
+ factory.block_size))
391
+
392
+ return CtrMode(cipher_state, initial_counter_block,
393
+ len(prefix), counter_len, little_endian)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ctr.pyi ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, overload
2
+
3
+ from Crypto.Util._raw_api import SmartPointer
4
+
5
+ Buffer = Union[bytes, bytearray, memoryview]
6
+
7
+ __all__ = ['CtrMode']
8
+
9
+ class CtrMode(object):
10
+ block_size: int
11
+ nonce: bytes
12
+
13
+ def __init__(self,
14
+ block_cipher: SmartPointer,
15
+ initial_counter_block: Buffer,
16
+ prefix_len: int,
17
+ counter_len: int,
18
+ little_endian: bool) -> None: ...
19
+ @overload
20
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
21
+ @overload
22
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
23
+ @overload
24
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
25
+ @overload
26
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
27
+
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_eax.pyi ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import ModuleType
2
+ from typing import Any, Union, Tuple, Dict, overload, Optional
3
+
4
+ Buffer = Union[bytes, bytearray, memoryview]
5
+
6
+ __all__ = ['EaxMode']
7
+
8
+ class EaxMode(object):
9
+ block_size: int
10
+ nonce: bytes
11
+
12
+ def __init__(self,
13
+ factory: ModuleType,
14
+ key: Buffer,
15
+ nonce: Buffer,
16
+ mac_len: int,
17
+ cipher_params: Dict) -> None: ...
18
+
19
+ def update(self, assoc_data: Buffer) -> EaxMode: ...
20
+
21
+ @overload
22
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
23
+ @overload
24
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
25
+ @overload
26
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
27
+ @overload
28
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
29
+
30
+ def digest(self) -> bytes: ...
31
+ def hexdigest(self) -> str: ...
32
+ def verify(self, received_mac_tag: Buffer) -> None: ...
33
+ def hexverify(self, hex_mac_tag: str) -> None: ...
34
+
35
+ @overload
36
+ def encrypt_and_digest(self,
37
+ plaintext: Buffer) -> Tuple[bytes, bytes]: ...
38
+ @overload
39
+ def encrypt_and_digest(self,
40
+ plaintext: Buffer,
41
+ output: Buffer) -> Tuple[None, bytes]: ...
42
+ def decrypt_and_verify(self,
43
+ ciphertext: Buffer,
44
+ received_mac_tag: Buffer,
45
+ output: Optional[Union[bytearray, memoryview]] = ...) -> bytes: ...
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ecb.pyi ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, overload
2
+
3
+ from Crypto.Util._raw_api import SmartPointer
4
+
5
+ Buffer = Union[bytes, bytearray, memoryview]
6
+
7
+ __all__ = [ 'EcbMode' ]
8
+
9
+ class EcbMode(object):
10
+ def __init__(self, block_cipher: SmartPointer) -> None: ...
11
+ @overload
12
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
13
+ @overload
14
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
15
+ @overload
16
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
17
+ @overload
18
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
19
+
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_gcm.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
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
+ """
32
+ Galois/Counter Mode (GCM).
33
+ """
34
+
35
+ __all__ = ['GcmMode']
36
+
37
+ from binascii import unhexlify
38
+
39
+ from Crypto.Util.py3compat import bord, _copy_bytes
40
+
41
+ from Crypto.Util._raw_api import is_buffer
42
+
43
+ from Crypto.Util.number import long_to_bytes, bytes_to_long
44
+ from Crypto.Hash import BLAKE2s
45
+ from Crypto.Random import get_random_bytes
46
+
47
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
48
+ create_string_buffer, get_raw_buffer,
49
+ SmartPointer, c_size_t, c_uint8_ptr)
50
+
51
+ from Crypto.Util import _cpu_features
52
+
53
+
54
+ # C API by module implementing GHASH
55
+ _ghash_api_template = """
56
+ int ghash_%imp%(uint8_t y_out[16],
57
+ const uint8_t block_data[],
58
+ size_t len,
59
+ const uint8_t y_in[16],
60
+ const void *exp_key);
61
+ int ghash_expand_%imp%(const uint8_t h[16],
62
+ void **ghash_tables);
63
+ int ghash_destroy_%imp%(void *ghash_tables);
64
+ """
65
+
66
+ def _build_impl(lib, postfix):
67
+ from collections import namedtuple
68
+
69
+ funcs = ( "ghash", "ghash_expand", "ghash_destroy" )
70
+ GHASH_Imp = namedtuple('_GHash_Imp', funcs)
71
+ try:
72
+ imp_funcs = [ getattr(lib, x + "_" + postfix) for x in funcs ]
73
+ except AttributeError: # Make sphinx stop complaining with its mocklib
74
+ imp_funcs = [ None ] * 3
75
+ params = dict(zip(funcs, imp_funcs))
76
+ return GHASH_Imp(**params)
77
+
78
+
79
+ def _get_ghash_portable():
80
+ api = _ghash_api_template.replace("%imp%", "portable")
81
+ lib = load_pycryptodome_raw_lib("Crypto.Hash._ghash_portable", api)
82
+ result = _build_impl(lib, "portable")
83
+ return result
84
+ _ghash_portable = _get_ghash_portable()
85
+
86
+
87
+ def _get_ghash_clmul():
88
+ """Return None if CLMUL implementation is not available"""
89
+
90
+ if not _cpu_features.have_clmul():
91
+ return None
92
+ try:
93
+ api = _ghash_api_template.replace("%imp%", "clmul")
94
+ lib = load_pycryptodome_raw_lib("Crypto.Hash._ghash_clmul", api)
95
+ result = _build_impl(lib, "clmul")
96
+ except OSError:
97
+ result = None
98
+ return result
99
+ _ghash_clmul = _get_ghash_clmul()
100
+
101
+
102
+ class _GHASH(object):
103
+ """GHASH function defined in NIST SP 800-38D, Algorithm 2.
104
+
105
+ If X_1, X_2, .. X_m are the blocks of input data, the function
106
+ computes:
107
+
108
+ X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
109
+
110
+ in the Galois field GF(2^256) using the reducing polynomial
111
+ (x^128 + x^7 + x^2 + x + 1).
112
+ """
113
+
114
+ def __init__(self, subkey, ghash_c):
115
+ assert len(subkey) == 16
116
+
117
+ self.ghash_c = ghash_c
118
+
119
+ self._exp_key = VoidPointer()
120
+ result = ghash_c.ghash_expand(c_uint8_ptr(subkey),
121
+ self._exp_key.address_of())
122
+ if result:
123
+ raise ValueError("Error %d while expanding the GHASH key" % result)
124
+
125
+ self._exp_key = SmartPointer(self._exp_key.get(),
126
+ ghash_c.ghash_destroy)
127
+
128
+ # create_string_buffer always returns a string of zeroes
129
+ self._last_y = create_string_buffer(16)
130
+
131
+ def update(self, block_data):
132
+ assert len(block_data) % 16 == 0
133
+
134
+ result = self.ghash_c.ghash(self._last_y,
135
+ c_uint8_ptr(block_data),
136
+ c_size_t(len(block_data)),
137
+ self._last_y,
138
+ self._exp_key.get())
139
+ if result:
140
+ raise ValueError("Error %d while updating GHASH" % result)
141
+
142
+ return self
143
+
144
+ def digest(self):
145
+ return get_raw_buffer(self._last_y)
146
+
147
+
148
+ def enum(**enums):
149
+ return type('Enum', (), enums)
150
+
151
+
152
+ MacStatus = enum(PROCESSING_AUTH_DATA=1, PROCESSING_CIPHERTEXT=2)
153
+
154
+
155
+ class GcmMode(object):
156
+ """Galois Counter Mode (GCM).
157
+
158
+ This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
159
+ It provides both confidentiality and authenticity.
160
+
161
+ The header of the message may be left in the clear, if needed, and it will
162
+ still be subject to authentication. The decryption step tells the receiver
163
+ if the message comes from a source that really knowns the secret key.
164
+ Additionally, decryption detects if any part of the message - including the
165
+ header - has been modified or corrupted.
166
+
167
+ This mode requires a *nonce*.
168
+
169
+ This mode is only available for ciphers that operate on 128 bits blocks
170
+ (e.g. AES but not TDES).
171
+
172
+ See `NIST SP800-38D`_.
173
+
174
+ .. _`NIST SP800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
175
+ .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
176
+
177
+ :undocumented: __init__
178
+ """
179
+
180
+ def __init__(self, factory, key, nonce, mac_len, cipher_params, ghash_c):
181
+
182
+ self.block_size = factory.block_size
183
+ if self.block_size != 16:
184
+ raise ValueError("GCM mode is only available for ciphers"
185
+ " that operate on 128 bits blocks")
186
+
187
+ if len(nonce) == 0:
188
+ raise ValueError("Nonce cannot be empty")
189
+
190
+ if not is_buffer(nonce):
191
+ raise TypeError("Nonce must be bytes, bytearray or memoryview")
192
+
193
+ # See NIST SP 800 38D, 5.2.1.1
194
+ if len(nonce) > 2**64 - 1:
195
+ raise ValueError("Nonce exceeds maximum length")
196
+
197
+
198
+ self.nonce = _copy_bytes(None, None, nonce)
199
+ """Nonce"""
200
+
201
+ self._factory = factory
202
+ self._key = _copy_bytes(None, None, key)
203
+ self._tag = None # Cache for MAC tag
204
+
205
+ self._mac_len = mac_len
206
+ if not (4 <= mac_len <= 16):
207
+ raise ValueError("Parameter 'mac_len' must be in the range 4..16")
208
+
209
+ # Allowed transitions after initialization
210
+ self._next = ["update", "encrypt", "decrypt",
211
+ "digest", "verify"]
212
+
213
+ self._no_more_assoc_data = False
214
+
215
+ # Length of associated data
216
+ self._auth_len = 0
217
+
218
+ # Length of the ciphertext or plaintext
219
+ self._msg_len = 0
220
+
221
+ # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
222
+ # See also Algorithm 5 (decryption)
223
+ hash_subkey = factory.new(key,
224
+ self._factory.MODE_ECB,
225
+ **cipher_params
226
+ ).encrypt(b'\x00' * 16)
227
+
228
+ # Step 2 - Compute J0
229
+ if len(self.nonce) == 12:
230
+ j0 = self.nonce + b"\x00\x00\x00\x01"
231
+ else:
232
+ fill = (16 - (len(self.nonce) % 16)) % 16 + 8
233
+ ghash_in = (self.nonce +
234
+ b'\x00' * fill +
235
+ long_to_bytes(8 * len(self.nonce), 8))
236
+ j0 = _GHASH(hash_subkey, ghash_c).update(ghash_in).digest()
237
+
238
+ # Step 3 - Prepare GCTR cipher for encryption/decryption
239
+ nonce_ctr = j0[:12]
240
+ iv_ctr = (bytes_to_long(j0) + 1) & 0xFFFFFFFF
241
+ self._cipher = factory.new(key,
242
+ self._factory.MODE_CTR,
243
+ initial_value=iv_ctr,
244
+ nonce=nonce_ctr,
245
+ **cipher_params)
246
+
247
+ # Step 5 - Bootstrat GHASH
248
+ self._signer = _GHASH(hash_subkey, ghash_c)
249
+
250
+ # Step 6 - Prepare GCTR cipher for GMAC
251
+ self._tag_cipher = factory.new(key,
252
+ self._factory.MODE_CTR,
253
+ initial_value=j0,
254
+ nonce=b"",
255
+ **cipher_params)
256
+
257
+ # Cache for data to authenticate
258
+ self._cache = b""
259
+
260
+ self._status = MacStatus.PROCESSING_AUTH_DATA
261
+
262
+ def update(self, assoc_data):
263
+ """Protect associated data
264
+
265
+ If there is any associated data, the caller has to invoke
266
+ this function one or more times, before using
267
+ ``decrypt`` or ``encrypt``.
268
+
269
+ By *associated data* it is meant any data (e.g. packet headers) that
270
+ will not be encrypted and will be transmitted in the clear.
271
+ However, the receiver is still able to detect any modification to it.
272
+ In GCM, the *associated data* is also called
273
+ *additional authenticated data* (AAD).
274
+
275
+ If there is no associated data, this method must not be called.
276
+
277
+ The caller may split associated data in segments of any size, and
278
+ invoke this method multiple times, each time with the next segment.
279
+
280
+ :Parameters:
281
+ assoc_data : bytes/bytearray/memoryview
282
+ A piece of associated data. There are no restrictions on its size.
283
+ """
284
+
285
+ if "update" not in self._next:
286
+ raise TypeError("update() can only be called"
287
+ " immediately after initialization")
288
+
289
+ self._next = ["update", "encrypt", "decrypt",
290
+ "digest", "verify"]
291
+
292
+ self._update(assoc_data)
293
+ self._auth_len += len(assoc_data)
294
+
295
+ # See NIST SP 800 38D, 5.2.1.1
296
+ if self._auth_len > 2**64 - 1:
297
+ raise ValueError("Additional Authenticated Data exceeds maximum length")
298
+
299
+ return self
300
+
301
+ def _update(self, data):
302
+ assert(len(self._cache) < 16)
303
+
304
+ if len(self._cache) > 0:
305
+ filler = min(16 - len(self._cache), len(data))
306
+ self._cache += _copy_bytes(None, filler, data)
307
+ data = data[filler:]
308
+
309
+ if len(self._cache) < 16:
310
+ return
311
+
312
+ # The cache is exactly one block
313
+ self._signer.update(self._cache)
314
+ self._cache = b""
315
+
316
+ update_len = len(data) // 16 * 16
317
+ self._cache = _copy_bytes(update_len, None, data)
318
+ if update_len > 0:
319
+ self._signer.update(data[:update_len])
320
+
321
+ def _pad_cache_and_update(self):
322
+ assert(len(self._cache) < 16)
323
+
324
+ # The authenticated data A is concatenated to the minimum
325
+ # number of zero bytes (possibly none) such that the
326
+ # - ciphertext C is aligned to the 16 byte boundary.
327
+ # See step 5 in section 7.1
328
+ # - ciphertext C is aligned to the 16 byte boundary.
329
+ # See step 6 in section 7.2
330
+ len_cache = len(self._cache)
331
+ if len_cache > 0:
332
+ self._update(b'\x00' * (16 - len_cache))
333
+
334
+ def encrypt(self, plaintext, output=None):
335
+ """Encrypt data with the key and the parameters set at initialization.
336
+
337
+ A cipher object is stateful: once you have encrypted a message
338
+ you cannot encrypt (or decrypt) another message using the same
339
+ object.
340
+
341
+ The data to encrypt can be broken up in two or
342
+ more pieces and `encrypt` can be called multiple times.
343
+
344
+ That is, the statement:
345
+
346
+ >>> c.encrypt(a) + c.encrypt(b)
347
+
348
+ is equivalent to:
349
+
350
+ >>> c.encrypt(a+b)
351
+
352
+ This function does not add any padding to the plaintext.
353
+
354
+ :Parameters:
355
+ plaintext : bytes/bytearray/memoryview
356
+ The piece of data to encrypt.
357
+ It can be of any length.
358
+ :Keywords:
359
+ output : bytearray/memoryview
360
+ The location where the ciphertext must be written to.
361
+ If ``None``, the ciphertext is returned.
362
+ :Return:
363
+ If ``output`` is ``None``, the ciphertext as ``bytes``.
364
+ Otherwise, ``None``.
365
+ """
366
+
367
+ if "encrypt" not in self._next:
368
+ raise TypeError("encrypt() can only be called after"
369
+ " initialization or an update()")
370
+ self._next = ["encrypt", "digest"]
371
+
372
+ ciphertext = self._cipher.encrypt(plaintext, output=output)
373
+
374
+ if self._status == MacStatus.PROCESSING_AUTH_DATA:
375
+ self._pad_cache_and_update()
376
+ self._status = MacStatus.PROCESSING_CIPHERTEXT
377
+
378
+ self._update(ciphertext if output is None else output)
379
+ self._msg_len += len(plaintext)
380
+
381
+ # See NIST SP 800 38D, 5.2.1.1
382
+ if self._msg_len > 2**39 - 256:
383
+ raise ValueError("Plaintext exceeds maximum length")
384
+
385
+ return ciphertext
386
+
387
+ def decrypt(self, ciphertext, output=None):
388
+ """Decrypt data with the key and the parameters set at initialization.
389
+
390
+ A cipher object is stateful: once you have decrypted a message
391
+ you cannot decrypt (or encrypt) another message with the same
392
+ object.
393
+
394
+ The data to decrypt can be broken up in two or
395
+ more pieces and `decrypt` can be called multiple times.
396
+
397
+ That is, the statement:
398
+
399
+ >>> c.decrypt(a) + c.decrypt(b)
400
+
401
+ is equivalent to:
402
+
403
+ >>> c.decrypt(a+b)
404
+
405
+ This function does not remove any padding from the plaintext.
406
+
407
+ :Parameters:
408
+ ciphertext : bytes/bytearray/memoryview
409
+ The piece of data to decrypt.
410
+ It can be of any length.
411
+ :Keywords:
412
+ output : bytearray/memoryview
413
+ The location where the plaintext must be written to.
414
+ If ``None``, the plaintext is returned.
415
+ :Return:
416
+ If ``output`` is ``None``, the plaintext as ``bytes``.
417
+ Otherwise, ``None``.
418
+ """
419
+
420
+ if "decrypt" not in self._next:
421
+ raise TypeError("decrypt() can only be called"
422
+ " after initialization or an update()")
423
+ self._next = ["decrypt", "verify"]
424
+
425
+ if self._status == MacStatus.PROCESSING_AUTH_DATA:
426
+ self._pad_cache_and_update()
427
+ self._status = MacStatus.PROCESSING_CIPHERTEXT
428
+
429
+ self._update(ciphertext)
430
+ self._msg_len += len(ciphertext)
431
+
432
+ return self._cipher.decrypt(ciphertext, output=output)
433
+
434
+ def digest(self):
435
+ """Compute the *binary* MAC tag in an AEAD mode.
436
+
437
+ The caller invokes this function at the very end.
438
+
439
+ This method returns the MAC that shall be sent to the receiver,
440
+ together with the ciphertext.
441
+
442
+ :Return: the MAC, as a byte string.
443
+ """
444
+
445
+ if "digest" not in self._next:
446
+ raise TypeError("digest() cannot be called when decrypting"
447
+ " or validating a message")
448
+ self._next = ["digest"]
449
+
450
+ return self._compute_mac()
451
+
452
+ def _compute_mac(self):
453
+ """Compute MAC without any FSM checks."""
454
+
455
+ if self._tag:
456
+ return self._tag
457
+
458
+ # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S
459
+ self._pad_cache_and_update()
460
+ self._update(long_to_bytes(8 * self._auth_len, 8))
461
+ self._update(long_to_bytes(8 * self._msg_len, 8))
462
+ s_tag = self._signer.digest()
463
+
464
+ # Step 6 - Compute T
465
+ self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len]
466
+
467
+ return self._tag
468
+
469
+ def hexdigest(self):
470
+ """Compute the *printable* MAC tag.
471
+
472
+ This method is like `digest`.
473
+
474
+ :Return: the MAC, as a hexadecimal string.
475
+ """
476
+ return "".join(["%02x" % bord(x) for x in self.digest()])
477
+
478
+ def verify(self, received_mac_tag):
479
+ """Validate the *binary* MAC tag.
480
+
481
+ The caller invokes this function at the very end.
482
+
483
+ This method checks if the decrypted message is indeed valid
484
+ (that is, if the key is correct) and it has not been
485
+ tampered with while in transit.
486
+
487
+ :Parameters:
488
+ received_mac_tag : bytes/bytearray/memoryview
489
+ This is the *binary* MAC, as received from the sender.
490
+ :Raises ValueError:
491
+ if the MAC does not match. The message has been tampered with
492
+ or the key is incorrect.
493
+ """
494
+
495
+ if "verify" not in self._next:
496
+ raise TypeError("verify() cannot be called"
497
+ " when encrypting a message")
498
+ self._next = ["verify"]
499
+
500
+ secret = get_random_bytes(16)
501
+
502
+ mac1 = BLAKE2s.new(digest_bits=160, key=secret,
503
+ data=self._compute_mac())
504
+ mac2 = BLAKE2s.new(digest_bits=160, key=secret,
505
+ data=received_mac_tag)
506
+
507
+ if mac1.digest() != mac2.digest():
508
+ raise ValueError("MAC check failed")
509
+
510
+ def hexverify(self, hex_mac_tag):
511
+ """Validate the *printable* MAC tag.
512
+
513
+ This method is like `verify`.
514
+
515
+ :Parameters:
516
+ hex_mac_tag : string
517
+ This is the *printable* MAC, as received from the sender.
518
+ :Raises ValueError:
519
+ if the MAC does not match. The message has been tampered with
520
+ or the key is incorrect.
521
+ """
522
+
523
+ self.verify(unhexlify(hex_mac_tag))
524
+
525
+ def encrypt_and_digest(self, plaintext, output=None):
526
+ """Perform encrypt() and digest() in one step.
527
+
528
+ :Parameters:
529
+ plaintext : bytes/bytearray/memoryview
530
+ The piece of data to encrypt.
531
+ :Keywords:
532
+ output : bytearray/memoryview
533
+ The location where the ciphertext must be written to.
534
+ If ``None``, the ciphertext is returned.
535
+ :Return:
536
+ a tuple with two items:
537
+
538
+ - the ciphertext, as ``bytes``
539
+ - the MAC tag, as ``bytes``
540
+
541
+ The first item becomes ``None`` when the ``output`` parameter
542
+ specified a location for the result.
543
+ """
544
+
545
+ return self.encrypt(plaintext, output=output), self.digest()
546
+
547
+ def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
548
+ """Perform decrypt() and verify() in one step.
549
+
550
+ :Parameters:
551
+ ciphertext : bytes/bytearray/memoryview
552
+ The piece of data to decrypt.
553
+ received_mac_tag : byte string
554
+ This is the *binary* MAC, as received from the sender.
555
+ :Keywords:
556
+ output : bytearray/memoryview
557
+ The location where the plaintext must be written to.
558
+ If ``None``, the plaintext is returned.
559
+ :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
560
+ parameter specified a location for the result.
561
+ :Raises ValueError:
562
+ if the MAC does not match. The message has been tampered with
563
+ or the key is incorrect.
564
+ """
565
+
566
+ plaintext = self.decrypt(ciphertext, output=output)
567
+ self.verify(received_mac_tag)
568
+ return plaintext
569
+
570
+
571
+ def _create_gcm_cipher(factory, **kwargs):
572
+ """Create a new block cipher, configured in Galois Counter Mode (GCM).
573
+
574
+ :Parameters:
575
+ factory : module
576
+ A block cipher module, taken from `Crypto.Cipher`.
577
+ The cipher must have block length of 16 bytes.
578
+ GCM has been only defined for `Crypto.Cipher.AES`.
579
+
580
+ :Keywords:
581
+ key : bytes/bytearray/memoryview
582
+ The secret key to use in the symmetric cipher.
583
+ It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
584
+ or 32 (e.g. *AES-256*) bytes long.
585
+
586
+ nonce : bytes/bytearray/memoryview
587
+ A value that must never be reused for any other encryption.
588
+
589
+ There are no restrictions on its length,
590
+ but it is recommended to use at least 16 bytes.
591
+
592
+ The nonce shall never repeat for two
593
+ different messages encrypted with the same key,
594
+ but it does not need to be random.
595
+
596
+ If not provided, a 16 byte nonce will be randomly created.
597
+
598
+ mac_len : integer
599
+ Length of the MAC, in bytes.
600
+ It must be no larger than 16 bytes (which is the default).
601
+ """
602
+
603
+ try:
604
+ key = kwargs.pop("key")
605
+ except KeyError as e:
606
+ raise TypeError("Missing parameter:" + str(e))
607
+
608
+ nonce = kwargs.pop("nonce", None)
609
+ if nonce is None:
610
+ nonce = get_random_bytes(16)
611
+ mac_len = kwargs.pop("mac_len", 16)
612
+
613
+ # Not documented - only used for testing
614
+ use_clmul = kwargs.pop("use_clmul", True)
615
+ if use_clmul and _ghash_clmul:
616
+ ghash_c = _ghash_clmul
617
+ else:
618
+ ghash_c = _ghash_portable
619
+
620
+ return GcmMode(factory, key, nonce, mac_len, kwargs, ghash_c)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ocb.pyi ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import ModuleType
2
+ from typing import Union, Any, Optional, Tuple, Dict, overload
3
+
4
+ Buffer = Union[bytes, bytearray, memoryview]
5
+
6
+ class OcbMode(object):
7
+ block_size: int
8
+ nonce: Buffer
9
+
10
+ def __init__(self,
11
+ factory: ModuleType,
12
+ nonce: Buffer,
13
+ mac_len: int,
14
+ cipher_params: Dict) -> None: ...
15
+
16
+ def update(self, assoc_data: Buffer) -> OcbMode: ...
17
+
18
+ @overload
19
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
20
+ @overload
21
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
22
+ @overload
23
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
24
+ @overload
25
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
26
+
27
+ def digest(self) -> bytes: ...
28
+ def hexdigest(self) -> str: ...
29
+ def verify(self, received_mac_tag: Buffer) -> None: ...
30
+ def hexverify(self, hex_mac_tag: str) -> None: ...
31
+
32
+ def encrypt_and_digest(self,
33
+ plaintext: Buffer) -> Tuple[bytes, bytes]: ...
34
+ def decrypt_and_verify(self,
35
+ ciphertext: Buffer,
36
+ received_mac_tag: Buffer) -> bytes: ...
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ofb.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Cipher/mode_ofb.py : OFB mode
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
+ """
24
+ Output Feedback (CFB) mode.
25
+ """
26
+
27
+ __all__ = ['OfbMode']
28
+
29
+ from Crypto.Util.py3compat import _copy_bytes
30
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
31
+ create_string_buffer, get_raw_buffer,
32
+ SmartPointer, c_size_t, c_uint8_ptr,
33
+ is_writeable_buffer)
34
+
35
+ from Crypto.Random import get_random_bytes
36
+
37
+ raw_ofb_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ofb", """
38
+ int OFB_start_operation(void *cipher,
39
+ const uint8_t iv[],
40
+ size_t iv_len,
41
+ void **pResult);
42
+ int OFB_encrypt(void *ofbState,
43
+ const uint8_t *in,
44
+ uint8_t *out,
45
+ size_t data_len);
46
+ int OFB_decrypt(void *ofbState,
47
+ const uint8_t *in,
48
+ uint8_t *out,
49
+ size_t data_len);
50
+ int OFB_stop_operation(void *state);
51
+ """
52
+ )
53
+
54
+
55
+ class OfbMode(object):
56
+ """*Output FeedBack (OFB)*.
57
+
58
+ This mode is very similar to CBC, but it
59
+ transforms the underlying block cipher into a stream cipher.
60
+
61
+ The keystream is the iterated block encryption of the
62
+ previous ciphertext block.
63
+
64
+ An Initialization Vector (*IV*) is required.
65
+
66
+ See `NIST SP800-38A`_ , Section 6.4.
67
+
68
+ .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
69
+
70
+ :undocumented: __init__
71
+ """
72
+
73
+ def __init__(self, block_cipher, iv):
74
+ """Create a new block cipher, configured in OFB mode.
75
+
76
+ :Parameters:
77
+ block_cipher : C pointer
78
+ A smart pointer to the low-level block cipher instance.
79
+
80
+ iv : bytes/bytearray/memoryview
81
+ The initialization vector to use for encryption or decryption.
82
+ It is as long as the cipher block.
83
+
84
+ **The IV must be a nonce, to to be reused for any other
85
+ message**. It shall be a nonce or a random value.
86
+
87
+ Reusing the *IV* for encryptions performed with the same key
88
+ compromises confidentiality.
89
+ """
90
+
91
+ self._state = VoidPointer()
92
+ result = raw_ofb_lib.OFB_start_operation(block_cipher.get(),
93
+ c_uint8_ptr(iv),
94
+ c_size_t(len(iv)),
95
+ self._state.address_of())
96
+ if result:
97
+ raise ValueError("Error %d while instantiating the OFB mode"
98
+ % result)
99
+
100
+ # Ensure that object disposal of this Python object will (eventually)
101
+ # free the memory allocated by the raw library for the cipher mode
102
+ self._state = SmartPointer(self._state.get(),
103
+ raw_ofb_lib.OFB_stop_operation)
104
+
105
+ # Memory allocated for the underlying block cipher is now owed
106
+ # by the cipher mode
107
+ block_cipher.release()
108
+
109
+ self.block_size = len(iv)
110
+ """The block size of the underlying cipher, in bytes."""
111
+
112
+ self.iv = _copy_bytes(None, None, iv)
113
+ """The Initialization Vector originally used to create the object.
114
+ The value does not change."""
115
+
116
+ self.IV = self.iv
117
+ """Alias for `iv`"""
118
+
119
+ self._next = ["encrypt", "decrypt"]
120
+
121
+ def encrypt(self, plaintext, output=None):
122
+ """Encrypt data with the key and the parameters set at initialization.
123
+
124
+ A cipher object is stateful: once you have encrypted a message
125
+ you cannot encrypt (or decrypt) another message using the same
126
+ object.
127
+
128
+ The data to encrypt can be broken up in two or
129
+ more pieces and `encrypt` can be called multiple times.
130
+
131
+ That is, the statement:
132
+
133
+ >>> c.encrypt(a) + c.encrypt(b)
134
+
135
+ is equivalent to:
136
+
137
+ >>> c.encrypt(a+b)
138
+
139
+ This function does not add any padding to the plaintext.
140
+
141
+ :Parameters:
142
+ plaintext : bytes/bytearray/memoryview
143
+ The piece of data to encrypt.
144
+ It can be of any length.
145
+ :Keywords:
146
+ output : bytearray/memoryview
147
+ The location where the ciphertext must be written to.
148
+ If ``None``, the ciphertext is returned.
149
+ :Return:
150
+ If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
151
+ Otherwise, ``None``.
152
+ """
153
+
154
+ if "encrypt" not in self._next:
155
+ raise TypeError("encrypt() cannot be called after decrypt()")
156
+ self._next = ["encrypt"]
157
+
158
+ if output is None:
159
+ ciphertext = create_string_buffer(len(plaintext))
160
+ else:
161
+ ciphertext = output
162
+
163
+ if not is_writeable_buffer(output):
164
+ raise TypeError("output must be a bytearray or a writeable memoryview")
165
+
166
+ if len(plaintext) != len(output):
167
+ raise ValueError("output must have the same length as the input"
168
+ " (%d bytes)" % len(plaintext))
169
+
170
+ result = raw_ofb_lib.OFB_encrypt(self._state.get(),
171
+ c_uint8_ptr(plaintext),
172
+ c_uint8_ptr(ciphertext),
173
+ c_size_t(len(plaintext)))
174
+ if result:
175
+ raise ValueError("Error %d while encrypting in OFB mode" % result)
176
+
177
+ if output is None:
178
+ return get_raw_buffer(ciphertext)
179
+ else:
180
+ return None
181
+
182
+ def decrypt(self, ciphertext, output=None):
183
+ """Decrypt data with the key and the parameters set at initialization.
184
+
185
+ A cipher object is stateful: once you have decrypted a message
186
+ you cannot decrypt (or encrypt) another message with the same
187
+ object.
188
+
189
+ The data to decrypt can be broken up in two or
190
+ more pieces and `decrypt` can be called multiple times.
191
+
192
+ That is, the statement:
193
+
194
+ >>> c.decrypt(a) + c.decrypt(b)
195
+
196
+ is equivalent to:
197
+
198
+ >>> c.decrypt(a+b)
199
+
200
+ This function does not remove any padding from the plaintext.
201
+
202
+ :Parameters:
203
+ ciphertext : bytes/bytearray/memoryview
204
+ The piece of data to decrypt.
205
+ It can be of any length.
206
+ :Keywords:
207
+ output : bytearray/memoryview
208
+ The location where the plaintext is written to.
209
+ If ``None``, the plaintext is returned.
210
+ :Return:
211
+ If ``output`` is ``None``, the plaintext is returned as ``bytes``.
212
+ Otherwise, ``None``.
213
+ """
214
+
215
+ if "decrypt" not in self._next:
216
+ raise TypeError("decrypt() cannot be called after encrypt()")
217
+ self._next = ["decrypt"]
218
+
219
+ if output is None:
220
+ plaintext = create_string_buffer(len(ciphertext))
221
+ else:
222
+ plaintext = output
223
+
224
+ if not is_writeable_buffer(output):
225
+ raise TypeError("output must be a bytearray or a writeable memoryview")
226
+
227
+ if len(ciphertext) != len(output):
228
+ raise ValueError("output must have the same length as the input"
229
+ " (%d bytes)" % len(plaintext))
230
+
231
+ result = raw_ofb_lib.OFB_decrypt(self._state.get(),
232
+ c_uint8_ptr(ciphertext),
233
+ c_uint8_ptr(plaintext),
234
+ c_size_t(len(ciphertext)))
235
+ if result:
236
+ raise ValueError("Error %d while decrypting in OFB mode" % result)
237
+
238
+ if output is None:
239
+ return get_raw_buffer(plaintext)
240
+ else:
241
+ return None
242
+
243
+
244
+ def _create_ofb_cipher(factory, **kwargs):
245
+ """Instantiate a cipher object that performs OFB encryption/decryption.
246
+
247
+ :Parameters:
248
+ factory : module
249
+ The underlying block cipher, a module from ``Crypto.Cipher``.
250
+
251
+ :Keywords:
252
+ iv : bytes/bytearray/memoryview
253
+ The IV to use for OFB.
254
+
255
+ IV : bytes/bytearray/memoryview
256
+ Alias for ``iv``.
257
+
258
+ Any other keyword will be passed to the underlying block cipher.
259
+ See the relevant documentation for details (at least ``key`` will need
260
+ to be present).
261
+ """
262
+
263
+ cipher_state = factory._create_base_cipher(kwargs)
264
+ iv = kwargs.pop("IV", None)
265
+ IV = kwargs.pop("iv", None)
266
+
267
+ if (None, None) == (iv, IV):
268
+ iv = get_random_bytes(factory.block_size)
269
+ if iv is not None:
270
+ if IV is not None:
271
+ raise TypeError("You must either use 'iv' or 'IV', not both")
272
+ else:
273
+ iv = IV
274
+
275
+ if len(iv) != factory.block_size:
276
+ raise ValueError("Incorrect IV length (it must be %d bytes long)" %
277
+ factory.block_size)
278
+
279
+ if kwargs:
280
+ raise TypeError("Unknown parameters for OFB: %s" % str(kwargs))
281
+
282
+ return OfbMode(cipher_state, iv)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_ofb.pyi ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, overload
2
+
3
+ from Crypto.Util._raw_api import SmartPointer
4
+
5
+ Buffer = Union[bytes, bytearray, memoryview]
6
+
7
+ __all__ = ['OfbMode']
8
+
9
+ class OfbMode(object):
10
+ block_size: int
11
+ iv: Buffer
12
+ IV: Buffer
13
+
14
+ def __init__(self,
15
+ block_cipher: SmartPointer,
16
+ iv: Buffer) -> None: ...
17
+ @overload
18
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
19
+ @overload
20
+ def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
21
+ @overload
22
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
23
+ @overload
24
+ def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
25
+
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_openpgp.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
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
+ """
32
+ OpenPGP mode.
33
+ """
34
+
35
+ __all__ = ['OpenPgpMode']
36
+
37
+ from Crypto.Util.py3compat import _copy_bytes
38
+ from Crypto.Random import get_random_bytes
39
+
40
+ class OpenPgpMode(object):
41
+ """OpenPGP mode.
42
+
43
+ This mode is a variant of CFB, and it is only used in PGP and
44
+ OpenPGP_ applications. If in doubt, use another mode.
45
+
46
+ An Initialization Vector (*IV*) is required.
47
+
48
+ Unlike CFB, the *encrypted* IV (not the IV itself) is
49
+ transmitted to the receiver.
50
+
51
+ The IV is a random data block. For legacy reasons, two of its bytes are
52
+ duplicated to act as a checksum for the correctness of the key, which is now
53
+ known to be insecure and is ignored. The encrypted IV is therefore 2 bytes
54
+ longer than the clean IV.
55
+
56
+ .. _OpenPGP: http://tools.ietf.org/html/rfc4880
57
+
58
+ :undocumented: __init__
59
+ """
60
+
61
+ def __init__(self, factory, key, iv, cipher_params):
62
+
63
+ #: The block size of the underlying cipher, in bytes.
64
+ self.block_size = factory.block_size
65
+
66
+ self._done_first_block = False # True after the first encryption
67
+
68
+ # Instantiate a temporary cipher to process the IV
69
+ IV_cipher = factory.new(
70
+ key,
71
+ factory.MODE_CFB,
72
+ IV=b'\x00' * self.block_size,
73
+ segment_size=self.block_size * 8,
74
+ **cipher_params)
75
+
76
+ iv = _copy_bytes(None, None, iv)
77
+
78
+ # The cipher will be used for...
79
+ if len(iv) == self.block_size:
80
+ # ... encryption
81
+ self._encrypted_IV = IV_cipher.encrypt(iv + iv[-2:])
82
+ elif len(iv) == self.block_size + 2:
83
+ # ... decryption
84
+ self._encrypted_IV = iv
85
+ # Last two bytes are for a deprecated "quick check" feature that
86
+ # should not be used. (https://eprint.iacr.org/2005/033)
87
+ iv = IV_cipher.decrypt(iv)[:-2]
88
+ else:
89
+ raise ValueError("Length of IV must be %d or %d bytes"
90
+ " for MODE_OPENPGP"
91
+ % (self.block_size, self.block_size + 2))
92
+
93
+ self.iv = self.IV = iv
94
+
95
+ # Instantiate the cipher for the real PGP data
96
+ self._cipher = factory.new(
97
+ key,
98
+ factory.MODE_CFB,
99
+ IV=self._encrypted_IV[-self.block_size:],
100
+ segment_size=self.block_size * 8,
101
+ **cipher_params)
102
+
103
+ def encrypt(self, plaintext):
104
+ """Encrypt data with the key and the parameters set at initialization.
105
+
106
+ A cipher object is stateful: once you have encrypted a message
107
+ you cannot encrypt (or decrypt) another message using the same
108
+ object.
109
+
110
+ The data to encrypt can be broken up in two or
111
+ more pieces and `encrypt` can be called multiple times.
112
+
113
+ That is, the statement:
114
+
115
+ >>> c.encrypt(a) + c.encrypt(b)
116
+
117
+ is equivalent to:
118
+
119
+ >>> c.encrypt(a+b)
120
+
121
+ This function does not add any padding to the plaintext.
122
+
123
+ :Parameters:
124
+ plaintext : bytes/bytearray/memoryview
125
+ The piece of data to encrypt.
126
+
127
+ :Return:
128
+ the encrypted data, as a byte string.
129
+ It is as long as *plaintext* with one exception:
130
+ when encrypting the first message chunk,
131
+ the encypted IV is prepended to the returned ciphertext.
132
+ """
133
+
134
+ res = self._cipher.encrypt(plaintext)
135
+ if not self._done_first_block:
136
+ res = self._encrypted_IV + res
137
+ self._done_first_block = True
138
+ return res
139
+
140
+ def decrypt(self, ciphertext):
141
+ """Decrypt data with the key and the parameters set at initialization.
142
+
143
+ A cipher object is stateful: once you have decrypted a message
144
+ you cannot decrypt (or encrypt) another message with the same
145
+ object.
146
+
147
+ The data to decrypt can be broken up in two or
148
+ more pieces and `decrypt` can be called multiple times.
149
+
150
+ That is, the statement:
151
+
152
+ >>> c.decrypt(a) + c.decrypt(b)
153
+
154
+ is equivalent to:
155
+
156
+ >>> c.decrypt(a+b)
157
+
158
+ This function does not remove any padding from the plaintext.
159
+
160
+ :Parameters:
161
+ ciphertext : bytes/bytearray/memoryview
162
+ The piece of data to decrypt.
163
+
164
+ :Return: the decrypted data (byte string).
165
+ """
166
+
167
+ return self._cipher.decrypt(ciphertext)
168
+
169
+
170
+ def _create_openpgp_cipher(factory, **kwargs):
171
+ """Create a new block cipher, configured in OpenPGP mode.
172
+
173
+ :Parameters:
174
+ factory : module
175
+ The module.
176
+
177
+ :Keywords:
178
+ key : bytes/bytearray/memoryview
179
+ The secret key to use in the symmetric cipher.
180
+
181
+ IV : bytes/bytearray/memoryview
182
+ The initialization vector to use for encryption or decryption.
183
+
184
+ For encryption, the IV must be as long as the cipher block size.
185
+
186
+ For decryption, it must be 2 bytes longer (it is actually the
187
+ *encrypted* IV which was prefixed to the ciphertext).
188
+ """
189
+
190
+ iv = kwargs.pop("IV", None)
191
+ IV = kwargs.pop("iv", None)
192
+
193
+ if (None, None) == (iv, IV):
194
+ iv = get_random_bytes(factory.block_size)
195
+ if iv is not None:
196
+ if IV is not None:
197
+ raise TypeError("You must either use 'iv' or 'IV', not both")
198
+ else:
199
+ iv = IV
200
+
201
+ try:
202
+ key = kwargs.pop("key")
203
+ except KeyError as e:
204
+ raise TypeError("Missing component: " + str(e))
205
+
206
+ return OpenPgpMode(factory, key, iv, kwargs)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_openpgp.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import ModuleType
2
+ from typing import Union, Dict
3
+
4
+ Buffer = Union[bytes, bytearray, memoryview]
5
+
6
+ __all__ = ['OpenPgpMode']
7
+
8
+ class OpenPgpMode(object):
9
+ block_size: int
10
+ iv: Union[bytes, bytearray, memoryview]
11
+ IV: Union[bytes, bytearray, memoryview]
12
+
13
+ def __init__(self,
14
+ factory: ModuleType,
15
+ key: Buffer,
16
+ iv: Buffer,
17
+ cipher_params: Dict) -> None: ...
18
+ def encrypt(self, plaintext: Buffer) -> bytes: ...
19
+ def decrypt(self, plaintext: Buffer) -> bytes: ...
20
+
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_mode_siv.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===================================================================
2
+ #
3
+ # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
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
+ """
32
+ Synthetic Initialization Vector (SIV) mode.
33
+ """
34
+
35
+ __all__ = ['SivMode']
36
+
37
+ from binascii import hexlify, unhexlify
38
+
39
+ from Crypto.Util.py3compat import bord, _copy_bytes
40
+
41
+ from Crypto.Util._raw_api import is_buffer
42
+
43
+ from Crypto.Util.number import long_to_bytes, bytes_to_long
44
+ from Crypto.Protocol.KDF import _S2V
45
+ from Crypto.Hash import BLAKE2s
46
+ from Crypto.Random import get_random_bytes
47
+
48
+
49
+ class SivMode(object):
50
+ """Synthetic Initialization Vector (SIV).
51
+
52
+ This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
53
+ It provides both confidentiality and authenticity.
54
+
55
+ The header of the message may be left in the clear, if needed, and it will
56
+ still be subject to authentication. The decryption step tells the receiver
57
+ if the message comes from a source that really knowns the secret key.
58
+ Additionally, decryption detects if any part of the message - including the
59
+ header - has been modified or corrupted.
60
+
61
+ Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
62
+ nonce is not catastrophic for the confidentiality of the message. The only
63
+ effect is that an attacker can tell when the same plaintext (and same
64
+ associated data) is protected with the same key.
65
+
66
+ The length of the MAC is fixed to the block size of the underlying cipher.
67
+ The key size is twice the length of the key of the underlying cipher.
68
+
69
+ This mode is only available for AES ciphers.
70
+
71
+ +--------------------+---------------+-------------------+
72
+ | Cipher | SIV MAC size | SIV key length |
73
+ | | (bytes) | (bytes) |
74
+ +====================+===============+===================+
75
+ | AES-128 | 16 | 32 |
76
+ +--------------------+---------------+-------------------+
77
+ | AES-192 | 16 | 48 |
78
+ +--------------------+---------------+-------------------+
79
+ | AES-256 | 16 | 64 |
80
+ +--------------------+---------------+-------------------+
81
+
82
+ See `RFC5297`_ and the `original paper`__.
83
+
84
+ .. _RFC5297: https://tools.ietf.org/html/rfc5297
85
+ .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
86
+ .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf
87
+
88
+ :undocumented: __init__
89
+ """
90
+
91
+ def __init__(self, factory, key, nonce, kwargs):
92
+
93
+ self.block_size = factory.block_size
94
+ """The block size of the underlying cipher, in bytes."""
95
+
96
+ self._factory = factory
97
+
98
+ self._cipher_params = kwargs
99
+
100
+ if len(key) not in (32, 48, 64):
101
+ raise ValueError("Incorrect key length (%d bytes)" % len(key))
102
+
103
+ if nonce is not None:
104
+ if not is_buffer(nonce):
105
+ raise TypeError("When provided, the nonce must be bytes, bytearray or memoryview")
106
+
107
+ if len(nonce) == 0:
108
+ raise ValueError("When provided, the nonce must be non-empty")
109
+
110
+ self.nonce = _copy_bytes(None, None, nonce)
111
+ """Public attribute is only available in case of non-deterministic
112
+ encryption."""
113
+
114
+ subkey_size = len(key) // 2
115
+
116
+ self._mac_tag = None # Cache for MAC tag
117
+ self._kdf = _S2V(key[:subkey_size],
118
+ ciphermod=factory,
119
+ cipher_params=self._cipher_params)
120
+ self._subkey_cipher = key[subkey_size:]
121
+
122
+ # Purely for the purpose of verifying that cipher_params are OK
123
+ factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)
124
+
125
+ # Allowed transitions after initialization
126
+ self._next = ["update", "encrypt", "decrypt",
127
+ "digest", "verify"]
128
+
129
+ def _create_ctr_cipher(self, v):
130
+ """Create a new CTR cipher from V in SIV mode"""
131
+
132
+ v_int = bytes_to_long(v)
133
+ q = v_int & 0xFFFFFFFFFFFFFFFF7FFFFFFF7FFFFFFF
134
+ return self._factory.new(
135
+ self._subkey_cipher,
136
+ self._factory.MODE_CTR,
137
+ initial_value=q,
138
+ nonce=b"",
139
+ **self._cipher_params)
140
+
141
+ def update(self, component):
142
+ """Protect one associated data component
143
+
144
+ For SIV, the associated data is a sequence (*vector*) of non-empty
145
+ byte strings (*components*).
146
+
147
+ This method consumes the next component. It must be called
148
+ once for each of the components that constitue the associated data.
149
+
150
+ Note that the components have clear boundaries, so that:
151
+
152
+ >>> cipher.update(b"builtin")
153
+ >>> cipher.update(b"securely")
154
+
155
+ is not equivalent to:
156
+
157
+ >>> cipher.update(b"built")
158
+ >>> cipher.update(b"insecurely")
159
+
160
+ If there is no associated data, this method must not be called.
161
+
162
+ :Parameters:
163
+ component : bytes/bytearray/memoryview
164
+ The next associated data component.
165
+ """
166
+
167
+ if "update" not in self._next:
168
+ raise TypeError("update() can only be called"
169
+ " immediately after initialization")
170
+
171
+ self._next = ["update", "encrypt", "decrypt",
172
+ "digest", "verify"]
173
+
174
+ return self._kdf.update(component)
175
+
176
+ def encrypt(self, plaintext):
177
+ """
178
+ For SIV, encryption and MAC authentication must take place at the same
179
+ point. This method shall not be used.
180
+
181
+ Use `encrypt_and_digest` instead.
182
+ """
183
+
184
+ raise TypeError("encrypt() not allowed for SIV mode."
185
+ " Use encrypt_and_digest() instead.")
186
+
187
+ def decrypt(self, ciphertext):
188
+ """
189
+ For SIV, decryption and verification must take place at the same
190
+ point. This method shall not be used.
191
+
192
+ Use `decrypt_and_verify` instead.
193
+ """
194
+
195
+ raise TypeError("decrypt() not allowed for SIV mode."
196
+ " Use decrypt_and_verify() instead.")
197
+
198
+ def digest(self):
199
+ """Compute the *binary* MAC tag.
200
+
201
+ The caller invokes this function at the very end.
202
+
203
+ This method returns the MAC that shall be sent to the receiver,
204
+ together with the ciphertext.
205
+
206
+ :Return: the MAC, as a byte string.
207
+ """
208
+
209
+ if "digest" not in self._next:
210
+ raise TypeError("digest() cannot be called when decrypting"
211
+ " or validating a message")
212
+ self._next = ["digest"]
213
+ if self._mac_tag is None:
214
+ self._mac_tag = self._kdf.derive()
215
+ return self._mac_tag
216
+
217
+ def hexdigest(self):
218
+ """Compute the *printable* MAC tag.
219
+
220
+ This method is like `digest`.
221
+
222
+ :Return: the MAC, as a hexadecimal string.
223
+ """
224
+ return "".join(["%02x" % bord(x) for x in self.digest()])
225
+
226
+ def verify(self, received_mac_tag):
227
+ """Validate the *binary* MAC tag.
228
+
229
+ The caller invokes this function at the very end.
230
+
231
+ This method checks if the decrypted message is indeed valid
232
+ (that is, if the key is correct) and it has not been
233
+ tampered with while in transit.
234
+
235
+ :Parameters:
236
+ received_mac_tag : bytes/bytearray/memoryview
237
+ This is the *binary* MAC, as received from the sender.
238
+ :Raises ValueError:
239
+ if the MAC does not match. The message has been tampered with
240
+ or the key is incorrect.
241
+ """
242
+
243
+ if "verify" not in self._next:
244
+ raise TypeError("verify() cannot be called"
245
+ " when encrypting a message")
246
+ self._next = ["verify"]
247
+
248
+ if self._mac_tag is None:
249
+ self._mac_tag = self._kdf.derive()
250
+
251
+ secret = get_random_bytes(16)
252
+
253
+ mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
254
+ mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
255
+
256
+ if mac1.digest() != mac2.digest():
257
+ raise ValueError("MAC check failed")
258
+
259
+ def hexverify(self, hex_mac_tag):
260
+ """Validate the *printable* MAC tag.
261
+
262
+ This method is like `verify`.
263
+
264
+ :Parameters:
265
+ hex_mac_tag : string
266
+ This is the *printable* MAC, as received from the sender.
267
+ :Raises ValueError:
268
+ if the MAC does not match. The message has been tampered with
269
+ or the key is incorrect.
270
+ """
271
+
272
+ self.verify(unhexlify(hex_mac_tag))
273
+
274
+ def encrypt_and_digest(self, plaintext, output=None):
275
+ """Perform encrypt() and digest() in one step.
276
+
277
+ :Parameters:
278
+ plaintext : bytes/bytearray/memoryview
279
+ The piece of data to encrypt.
280
+ :Keywords:
281
+ output : bytearray/memoryview
282
+ The location where the ciphertext must be written to.
283
+ If ``None``, the ciphertext is returned.
284
+ :Return:
285
+ a tuple with two items:
286
+
287
+ - the ciphertext, as ``bytes``
288
+ - the MAC tag, as ``bytes``
289
+
290
+ The first item becomes ``None`` when the ``output`` parameter
291
+ specified a location for the result.
292
+ """
293
+
294
+ if "encrypt" not in self._next:
295
+ raise TypeError("encrypt() can only be called after"
296
+ " initialization or an update()")
297
+
298
+ self._next = ["digest"]
299
+
300
+ # Compute V (MAC)
301
+ if hasattr(self, 'nonce'):
302
+ self._kdf.update(self.nonce)
303
+ self._kdf.update(plaintext)
304
+ self._mac_tag = self._kdf.derive()
305
+
306
+ cipher = self._create_ctr_cipher(self._mac_tag)
307
+
308
+ return cipher.encrypt(plaintext, output=output), self._mac_tag
309
+
310
+ def decrypt_and_verify(self, ciphertext, mac_tag, output=None):
311
+ """Perform decryption and verification in one step.
312
+
313
+ A cipher object is stateful: once you have decrypted a message
314
+ you cannot decrypt (or encrypt) another message with the same
315
+ object.
316
+
317
+ You cannot reuse an object for encrypting
318
+ or decrypting other data with the same key.
319
+
320
+ This function does not remove any padding from the plaintext.
321
+
322
+ :Parameters:
323
+ ciphertext : bytes/bytearray/memoryview
324
+ The piece of data to decrypt.
325
+ It can be of any length.
326
+ mac_tag : bytes/bytearray/memoryview
327
+ This is the *binary* MAC, as received from the sender.
328
+ :Keywords:
329
+ output : bytearray/memoryview
330
+ The location where the plaintext must be written to.
331
+ If ``None``, the plaintext is returned.
332
+ :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
333
+ parameter specified a location for the result.
334
+ :Raises ValueError:
335
+ if the MAC does not match. The message has been tampered with
336
+ or the key is incorrect.
337
+ """
338
+
339
+ if "decrypt" not in self._next:
340
+ raise TypeError("decrypt() can only be called"
341
+ " after initialization or an update()")
342
+ self._next = ["verify"]
343
+
344
+ # Take the MAC and start the cipher for decryption
345
+ self._cipher = self._create_ctr_cipher(mac_tag)
346
+
347
+ plaintext = self._cipher.decrypt(ciphertext, output=output)
348
+
349
+ if hasattr(self, 'nonce'):
350
+ self._kdf.update(self.nonce)
351
+ self._kdf.update(plaintext if output is None else output)
352
+ self.verify(mac_tag)
353
+
354
+ return plaintext
355
+
356
+
357
+ def _create_siv_cipher(factory, **kwargs):
358
+ """Create a new block cipher, configured in
359
+ Synthetic Initializaton Vector (SIV) mode.
360
+
361
+ :Parameters:
362
+
363
+ factory : object
364
+ A symmetric cipher module from `Crypto.Cipher`
365
+ (like `Crypto.Cipher.AES`).
366
+
367
+ :Keywords:
368
+
369
+ key : bytes/bytearray/memoryview
370
+ The secret key to use in the symmetric cipher.
371
+ It must be 32, 48 or 64 bytes long.
372
+ If AES is the chosen cipher, the variants *AES-128*,
373
+ *AES-192* and or *AES-256* will be used internally.
374
+
375
+ nonce : bytes/bytearray/memoryview
376
+ For deterministic encryption, it is not present.
377
+
378
+ Otherwise, it is a value that must never be reused
379
+ for encrypting message under this key.
380
+
381
+ There are no restrictions on its length,
382
+ but it is recommended to use at least 16 bytes.
383
+ """
384
+
385
+ try:
386
+ key = kwargs.pop("key")
387
+ except KeyError as e:
388
+ raise TypeError("Missing parameter: " + str(e))
389
+
390
+ nonce = kwargs.pop("nonce", None)
391
+
392
+ return SivMode(factory, key, nonce, kwargs)
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_pkcs1_decode.abi3.so ADDED
Binary file (56.5 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_pkcs1_oaep_decode.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, c_size_t,
2
+ c_uint8_ptr)
3
+
4
+
5
+ _raw_pkcs1_decode = load_pycryptodome_raw_lib("Crypto.Cipher._pkcs1_decode",
6
+ """
7
+ int pkcs1_decode(const uint8_t *em, size_t len_em,
8
+ const uint8_t *sentinel, size_t len_sentinel,
9
+ size_t expected_pt_len,
10
+ uint8_t *output);
11
+
12
+ int oaep_decode(const uint8_t *em,
13
+ size_t em_len,
14
+ const uint8_t *lHash,
15
+ size_t hLen,
16
+ const uint8_t *db,
17
+ size_t db_len);
18
+ """)
19
+
20
+
21
+ def pkcs1_decode(em, sentinel, expected_pt_len, output):
22
+ if len(em) != len(output):
23
+ raise ValueError("Incorrect output length")
24
+
25
+ ret = _raw_pkcs1_decode.pkcs1_decode(c_uint8_ptr(em),
26
+ c_size_t(len(em)),
27
+ c_uint8_ptr(sentinel),
28
+ c_size_t(len(sentinel)),
29
+ c_size_t(expected_pt_len),
30
+ c_uint8_ptr(output))
31
+ return ret
32
+
33
+
34
+ def oaep_decode(em, lHash, db):
35
+ ret = _raw_pkcs1_decode.oaep_decode(c_uint8_ptr(em),
36
+ c_size_t(len(em)),
37
+ c_uint8_ptr(lHash),
38
+ c_size_t(len(lHash)),
39
+ c_uint8_ptr(db),
40
+ c_size_t(len(db)))
41
+ return ret
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_aesni.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fd3c232c2ea188c6d6cc78a3527376ac6691ffe04c95ac420e6c5aa5bbc6b54
3
+ size 106384
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_arc2.abi3.so ADDED
Binary file (46.5 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_cfb.abi3.so ADDED
Binary file (26.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_ctr.abi3.so ADDED
Binary file (31.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_des.abi3.so ADDED
Binary file (71.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_des3.abi3.so ADDED
Binary file (72.5 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_ecb.abi3.so ADDED
Binary file (19 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Cipher/_raw_ocb.abi3.so ADDED
Binary file (45.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/RIPEMD.cpython-310.pyc ADDED
Binary file (316 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/SHA3_384.cpython-310.pyc ADDED
Binary file (4.83 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/TurboSHAKE128.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Hash/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
minigpt2/lib/python3.10/site-packages/Crypto/Util/Counter.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: ascii -*-
2
+ #
3
+ # Util/Counter.py : Fast counter for use with CTR-mode ciphers
4
+ #
5
+ # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
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
+ def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, allow_wraparound=False):
26
+ """Create a stateful counter block function suitable for CTR encryption modes.
27
+
28
+ Each call to the function returns the next counter block.
29
+ Each counter block is made up by three parts:
30
+
31
+ +------+--------------+-------+
32
+ |prefix| counter value|postfix|
33
+ +------+--------------+-------+
34
+
35
+ The counter value is incremented by 1 at each call.
36
+
37
+ Args:
38
+ nbits (integer):
39
+ Length of the desired counter value, in bits. It must be a multiple of 8.
40
+ prefix (byte string):
41
+ The constant prefix of the counter block. By default, no prefix is
42
+ used.
43
+ suffix (byte string):
44
+ The constant postfix of the counter block. By default, no suffix is
45
+ used.
46
+ initial_value (integer):
47
+ The initial value of the counter. Default value is 1.
48
+ Its length in bits must not exceed the argument ``nbits``.
49
+ little_endian (boolean):
50
+ If ``True``, the counter number will be encoded in little endian format.
51
+ If ``False`` (default), in big endian format.
52
+ allow_wraparound (boolean):
53
+ This parameter is ignored.
54
+ An ``OverflowError`` exception is always raised when the counter wraps
55
+ around to zero.
56
+ Returns:
57
+ An object that can be passed with the :data:`counter` parameter to a CTR mode
58
+ cipher.
59
+
60
+ It must hold that *len(prefix) + nbits//8 + len(suffix)* matches the
61
+ block size of the underlying block cipher.
62
+ """
63
+
64
+ if (nbits % 8) != 0:
65
+ raise ValueError("'nbits' must be a multiple of 8")
66
+
67
+ iv_bl = initial_value.bit_length()
68
+ if iv_bl > nbits:
69
+ raise ValueError("Initial value takes %d bits but it is longer than "
70
+ "the counter (%d bits)" %
71
+ (iv_bl, nbits))
72
+
73
+ # Ignore wraparound
74
+ return {"counter_len": nbits // 8,
75
+ "prefix": prefix,
76
+ "suffix": suffix,
77
+ "initial_value": initial_value,
78
+ "little_endian": little_endian
79
+ }
minigpt2/lib/python3.10/site-packages/Crypto/Util/Padding.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Util/Padding.py : Functions to manage padding
3
+ #
4
+ # ===================================================================
5
+ #
6
+ # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
7
+ # All rights reserved.
8
+ #
9
+ # Redistribution and use in source and binary forms, with or without
10
+ # modification, are permitted provided that the following conditions
11
+ # are met:
12
+ #
13
+ # 1. Redistributions of source code must retain the above copyright
14
+ # notice, this list of conditions and the following disclaimer.
15
+ # 2. Redistributions in binary form must reproduce the above copyright
16
+ # notice, this list of conditions and the following disclaimer in
17
+ # the documentation and/or other materials provided with the
18
+ # distribution.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24
+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30
+ # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31
+ # POSSIBILITY OF SUCH DAMAGE.
32
+ # ===================================================================
33
+
34
+ __all__ = [ 'pad', 'unpad' ]
35
+
36
+ from Crypto.Util.py3compat import *
37
+
38
+
39
+ def pad(data_to_pad, block_size, style='pkcs7'):
40
+ """Apply standard padding.
41
+
42
+ Args:
43
+ data_to_pad (byte string):
44
+ The data that needs to be padded.
45
+ block_size (integer):
46
+ The block boundary to use for padding. The output length is guaranteed
47
+ to be a multiple of :data:`block_size`.
48
+ style (string):
49
+ Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*.
50
+
51
+ Return:
52
+ byte string : the original data with the appropriate padding added at the end.
53
+ """
54
+
55
+ padding_len = block_size-len(data_to_pad)%block_size
56
+ if style == 'pkcs7':
57
+ padding = bchr(padding_len)*padding_len
58
+ elif style == 'x923':
59
+ padding = bchr(0)*(padding_len-1) + bchr(padding_len)
60
+ elif style == 'iso7816':
61
+ padding = bchr(128) + bchr(0)*(padding_len-1)
62
+ else:
63
+ raise ValueError("Unknown padding style")
64
+ return data_to_pad + padding
65
+
66
+
67
+ def unpad(padded_data, block_size, style='pkcs7'):
68
+ """Remove standard padding.
69
+
70
+ Args:
71
+ padded_data (byte string):
72
+ A piece of data with padding that needs to be stripped.
73
+ block_size (integer):
74
+ The block boundary to use for padding. The input length
75
+ must be a multiple of :data:`block_size`.
76
+ style (string):
77
+ Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*.
78
+ Return:
79
+ byte string : data without padding.
80
+ Raises:
81
+ ValueError: if the padding is incorrect.
82
+ """
83
+
84
+ pdata_len = len(padded_data)
85
+ if pdata_len == 0:
86
+ raise ValueError("Zero-length input cannot be unpadded")
87
+ if pdata_len % block_size:
88
+ raise ValueError("Input data is not padded")
89
+ if style in ('pkcs7', 'x923'):
90
+ padding_len = bord(padded_data[-1])
91
+ if padding_len<1 or padding_len>min(block_size, pdata_len):
92
+ raise ValueError("Padding is incorrect.")
93
+ if style == 'pkcs7':
94
+ if padded_data[-padding_len:]!=bchr(padding_len)*padding_len:
95
+ raise ValueError("PKCS#7 padding is incorrect.")
96
+ else:
97
+ if padded_data[-padding_len:-1]!=bchr(0)*(padding_len-1):
98
+ raise ValueError("ANSI X.923 padding is incorrect.")
99
+ elif style == 'iso7816':
100
+ padding_len = pdata_len - padded_data.rfind(bchr(128))
101
+ if padding_len<1 or padding_len>min(block_size, pdata_len):
102
+ raise ValueError("Padding is incorrect.")
103
+ if padding_len>1 and padded_data[1-padding_len:]!=bchr(0)*(padding_len-1):
104
+ raise ValueError("ISO 7816-4 padding is incorrect.")
105
+ else:
106
+ raise ValueError("Unknown padding style")
107
+ return padded_data[:-padding_len]
108
+