diff options
Diffstat (limited to 'frozen_deps/Cryptodome')
153 files changed, 1867 insertions, 769 deletions
diff --git a/frozen_deps/Cryptodome/Cipher/AES.py b/frozen_deps/Cryptodome/Cipher/AES.py index 566a207..402a3d7 100644 --- a/frozen_deps/Cryptodome/Cipher/AES.py +++ b/frozen_deps/Cryptodome/Cipher/AES.py @@ -19,21 +19,6 @@ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== -""" -Module's constants for the modes of operation supported with AES: - -:var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>` -:var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>` -:var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>` -:var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>` -:var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>` -:var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>` -:var MODE_CCM: :ref:`Counter with CBC-MAC (CCM) Mode <ccm_mode>` -:var MODE_EAX: :ref:`EAX Mode <eax_mode>` -:var MODE_GCM: :ref:`Galois Counter Mode (GCM) <gcm_mode>` -:var MODE_SIV: :ref:`Syntethic Initialization Vector (SIV) <siv_mode>` -:var MODE_OCB: :ref:`Offset Code Book (OCB) <ocb_mode>` -""" import sys @@ -45,6 +30,18 @@ from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, from Cryptodome.Util import _cpu_features from Cryptodome.Random import get_random_bytes +MODE_ECB = 1 #: Electronic Code Book (:ref:`ecb_mode`) +MODE_CBC = 2 #: Cipher-Block Chaining (:ref:`cbc_mode`) +MODE_CFB = 3 #: Cipher Feedback (:ref:`cfb_mode`) +MODE_OFB = 5 #: Output Feedback (:ref:`ofb_mode`) +MODE_CTR = 6 #: Counter mode (:ref:`ctr_mode`) +MODE_OPENPGP = 7 #: OpenPGP mode (:ref:`openpgp_mode`) +MODE_CCM = 8 #: Counter with CBC-MAC (:ref:`ccm_mode`) +MODE_EAX = 9 #: :ref:`eax_mode` +MODE_SIV = 10 #: Synthetic Initialization Vector (:ref:`siv_mode`) +MODE_GCM = 11 #: Galois Counter Mode (:ref:`gcm_mode`) +MODE_OCB = 12 #: Offset Code Book (:ref:`ocb_mode`) + _cproto = """ int AES_start_operation(const uint8_t key[], @@ -130,120 +127,107 @@ def _derive_Poly1305_key_pair(key, nonce): def new(key, mode, *args, **kwargs): """Create a new AES cipher. - :param key: + Args: + key(bytes/bytearray/memoryview): The secret key to use in the symmetric cipher. - It must be 16, 24 or 32 bytes long (respectively for *AES-128*, - *AES-192* or *AES-256*). + It must be 16 (*AES-128)*, 24 (*AES-192*) or 32 (*AES-256*) bytes long. For ``MODE_SIV`` only, it doubles to 32, 48, or 64 bytes. - :type key: bytes/bytearray/memoryview - - :param mode: + mode (a ``MODE_*`` constant): The chaining mode to use for encryption or decryption. If in doubt, use ``MODE_EAX``. - :type mode: One of the supported ``MODE_*`` constants - :Keyword Arguments: - * **iv** (*bytes*, *bytearray*, *memoryview*) -- - (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``, - and ``MODE_OPENPGP`` modes). + Keyword Args: + iv (bytes/bytearray/memoryview): + (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``, + and ``MODE_OPENPGP`` modes). - The initialization vector to use for encryption or decryption. + The initialization vector to use for encryption or decryption. - For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 16 bytes long. + For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 16 bytes long. - For ``MODE_OPENPGP`` mode only, - it must be 16 bytes long for encryption - and 18 bytes for decryption (in the latter case, it is - actually the *encrypted* IV which was prefixed to the ciphertext). + For ``MODE_OPENPGP`` mode only, + it must be 16 bytes long for encryption + and 18 bytes for decryption (in the latter case, it is + actually the *encrypted* IV which was prefixed to the ciphertext). - If not provided, a random byte string is generated (you must then - read its value with the :attr:`iv` attribute). + If not provided, a random byte string is generated (you must then + read its value with the :attr:`iv` attribute). - * **nonce** (*bytes*, *bytearray*, *memoryview*) -- - (Only applicable for ``MODE_CCM``, ``MODE_EAX``, ``MODE_GCM``, - ``MODE_SIV``, ``MODE_OCB``, and ``MODE_CTR``). + nonce (bytes/bytearray/memoryview): + (Only applicable for ``MODE_CCM``, ``MODE_EAX``, ``MODE_GCM``, + ``MODE_SIV``, ``MODE_OCB``, and ``MODE_CTR``). - A value that must never be reused for any other encryption done - with this key (except possibly for ``MODE_SIV``, see below). + A value that must never be reused for any other encryption done + with this key (except possibly for ``MODE_SIV``, see below). - For ``MODE_EAX``, ``MODE_GCM`` and ``MODE_SIV`` there are no - restrictions on its length (recommended: **16** bytes). + For ``MODE_EAX``, ``MODE_GCM`` and ``MODE_SIV`` there are no + restrictions on its length (recommended: **16** bytes). - For ``MODE_CCM``, its length must be in the range **[7..13]**. - Bear in mind that with CCM there is a trade-off between nonce - length and maximum message size. Recommendation: **11** bytes. + For ``MODE_CCM``, its length must be in the range **[7..13]**. + Bear in mind that with CCM there is a trade-off between nonce + length and maximum message size. Recommendation: **11** bytes. - For ``MODE_OCB``, its length must be in the range **[1..15]** - (recommended: **15**). + For ``MODE_OCB``, its length must be in the range **[1..15]** + (recommended: **15**). - For ``MODE_CTR``, its length must be in the range **[0..15]** - (recommended: **8**). + For ``MODE_CTR``, its length must be in the range **[0..15]** + (recommended: **8**). - For ``MODE_SIV``, the nonce is optional, if it is not specified, - then no nonce is being used, which renders the encryption - deterministic. + For ``MODE_SIV``, the nonce is optional, if it is not specified, + then no nonce is being used, which renders the encryption + deterministic. - If not provided, for modes other than ``MODE_SIV```, a random - byte string of the recommended length is used (you must then - read its value with the :attr:`nonce` attribute). + If not provided, for modes other than ``MODE_SIV``, a random + byte string of the recommended length is used (you must then + read its value with the :attr:`nonce` attribute). - * **segment_size** (*integer*) -- - (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext - are segmented in. It must be a multiple of 8. - If not specified, it will be assumed to be 8. + segment_size (integer): + (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext + are segmented in. It must be a multiple of 8. + If not specified, it will be assumed to be 8. - * **mac_len** : (*integer*) -- - (Only ``MODE_EAX``, ``MODE_GCM``, ``MODE_OCB``, ``MODE_CCM``) - Length of the authentication tag, in bytes. + mac_len (integer): + (Only ``MODE_EAX``, ``MODE_GCM``, ``MODE_OCB``, ``MODE_CCM``) + Length of the authentication tag, in bytes. - It must be even and in the range **[4..16]**. - The recommended value (and the default, if not specified) is **16**. + It must be even and in the range **[4..16]**. + The recommended value (and the default, if not specified) is **16**. - * **msg_len** : (*integer*) -- - (Only ``MODE_CCM``). Length of the message to (de)cipher. - If not specified, ``encrypt`` must be called with the entire message. - Similarly, ``decrypt`` can only be called once. + msg_len (integer): + (Only ``MODE_CCM``). Length of the message to (de)cipher. + If not specified, ``encrypt`` must be called with the entire message. + Similarly, ``decrypt`` can only be called once. - * **assoc_len** : (*integer*) -- - (Only ``MODE_CCM``). Length of the associated data. - If not specified, all associated data is buffered internally, - which may represent a problem for very large messages. + assoc_len (integer): + (Only ``MODE_CCM``). Length of the associated data. + If not specified, all associated data is buffered internally, + which may represent a problem for very large messages. - * **initial_value** : (*integer* or *bytes/bytearray/memoryview*) -- - (Only ``MODE_CTR``). - The initial value for the counter. If not present, the cipher will - start counting from 0. The value is incremented by one for each block. - The counter number is encoded in big endian mode. + initial_value (integer or bytes/bytearray/memoryview): + (Only ``MODE_CTR``). + The initial value for the counter. If not present, the cipher will + start counting from 0. The value is incremented by one for each block. + The counter number is encoded in big endian mode. - * **counter** : (*object*) -- - Instance of ``Cryptodome.Util.Counter``, which allows full customization - of the counter block. This parameter is incompatible to both ``nonce`` - and ``initial_value``. + counter (object): + (Only ``MODE_CTR``). + Instance of ``Cryptodome.Util.Counter``, which allows full customization + of the counter block. This parameter is incompatible to both ``nonce`` + and ``initial_value``. - * **use_aesni** : (*boolean*) -- - Use Intel AES-NI hardware extensions (default: use if available). + use_aesni: (boolean): + Use Intel AES-NI hardware extensions (default: use if available). - :Return: an AES object, of the applicable mode. + Returns: + an AES object, of the applicable mode. """ kwargs["add_aes_modes"] = True return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs) -MODE_ECB = 1 -MODE_CBC = 2 -MODE_CFB = 3 -MODE_OFB = 5 -MODE_CTR = 6 -MODE_OPENPGP = 7 -MODE_CCM = 8 -MODE_EAX = 9 -MODE_SIV = 10 -MODE_GCM = 11 -MODE_OCB = 12 - # Size of a data block (in bytes) block_size = 16 # Size of a key (in bytes) diff --git a/frozen_deps/Cryptodome/Cipher/AES.pyi b/frozen_deps/Cryptodome/Cipher/AES.pyi index c150efb..3f07b65 100644 --- a/frozen_deps/Cryptodome/Cipher/AES.pyi +++ b/frozen_deps/Cryptodome/Cipher/AES.pyi @@ -1,4 +1,7 @@ -from typing import Union, Tuple, Optional, Dict +from typing import Dict, Optional, Tuple, Union, overload +from typing_extensions import Literal + +Buffer=bytes|bytearray|memoryview from Cryptodome.Cipher._mode_ecb import EcbMode from Cryptodome.Cipher._mode_cbc import CbcMode @@ -12,36 +15,142 @@ from Cryptodome.Cipher._mode_gcm import GcmMode from Cryptodome.Cipher._mode_siv import SivMode from Cryptodome.Cipher._mode_ocb import OcbMode -AESMode = int +MODE_ECB: Literal[1] +MODE_CBC: Literal[2] +MODE_CFB: Literal[3] +MODE_OFB: Literal[5] +MODE_CTR: Literal[6] +MODE_OPENPGP: Literal[7] +MODE_CCM: Literal[8] +MODE_EAX: Literal[9] +MODE_SIV: Literal[10] +MODE_GCM: Literal[11] +MODE_OCB: Literal[12] -MODE_ECB: AESMode -MODE_CBC: AESMode -MODE_CFB: AESMode -MODE_OFB: AESMode -MODE_CTR: AESMode -MODE_OPENPGP: AESMode -MODE_CCM: AESMode -MODE_EAX: AESMode -MODE_GCM: AESMode -MODE_SIV: AESMode -MODE_OCB: AESMode +# MODE_ECB +@overload +def new(key: Buffer, + mode: Literal[1], + use_aesni : bool = ...) -> \ + EcbMode: ... -Buffer = Union[bytes, bytearray, memoryview] +# MODE_CBC +@overload +def new(key: Buffer, + mode: Literal[2], + iv : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + CbcMode: ... +@overload def new(key: Buffer, - mode: AESMode, - iv : Buffer = ..., - IV : Buffer = ..., - nonce : Buffer = ..., + mode: Literal[2], + IV : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + CbcMode: ... + +# MODE_CFB +@overload +def new(key: Buffer, + mode: Literal[3], + iv : Optional[Buffer] = ..., segment_size : int = ..., - mac_len : int = ..., - assoc_len : int = ..., + use_aesni : bool = ...) -> \ + CfbMode: ... + +@overload +def new(key: Buffer, + mode: Literal[3], + IV : Optional[Buffer] = ..., + segment_size : int = ..., + use_aesni : bool = ...) -> \ + CfbMode: ... + +# MODE_OFB +@overload +def new(key: Buffer, + mode: Literal[5], + iv : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + OfbMode: ... + +@overload +def new(key: Buffer, + mode: Literal[5], + IV : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + OfbMode: ... + +# MODE_CTR +@overload +def new(key: Buffer, + mode: Literal[6], + nonce : Optional[Buffer] = ..., initial_value : Union[int, Buffer] = ..., counter : Dict = ..., use_aesni : bool = ...) -> \ - Union[EcbMode, CbcMode, CfbMode, OfbMode, CtrMode, - OpenPgpMode, CcmMode, EaxMode, GcmMode, - SivMode, OcbMode]: ... + CtrMode: ... + +# MODE_OPENPGP +@overload +def new(key: Buffer, + mode: Literal[7], + iv : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + OpenPgpMode: ... + +@overload +def new(key: Buffer, + mode: Literal[7], + IV : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + OpenPgpMode: ... + +# MODE_CCM +@overload +def new(key: Buffer, + mode: Literal[8], + nonce : Optional[Buffer] = ..., + mac_len : int = ..., + assoc_len : int = ..., + use_aesni : bool = ...) -> \ + CcmMode: ... + +# MODE_EAX +@overload +def new(key: Buffer, + mode: Literal[9], + nonce : Optional[Buffer] = ..., + mac_len : int = ..., + use_aesni : bool = ...) -> \ + EaxMode: ... + +# MODE_GCM +@overload +def new(key: Buffer, + mode: Literal[10], + nonce : Optional[Buffer] = ..., + use_aesni : bool = ...) -> \ + SivMode: ... + +# MODE_SIV +@overload +def new(key: Buffer, + mode: Literal[11], + nonce : Optional[Buffer] = ..., + mac_len : int = ..., + use_aesni : bool = ...) -> \ + GcmMode: ... + +# MODE_OCB +@overload +def new(key: Buffer, + mode: Literal[12], + nonce : Optional[Buffer] = ..., + mac_len : int = ..., + use_aesni : bool = ...) -> \ + OcbMode: ... + block_size: int key_size: Tuple[int, int, int] diff --git a/frozen_deps/Cryptodome/Cipher/ARC2.pyi b/frozen_deps/Cryptodome/Cipher/ARC2.pyi index 9659c68..a122a52 100644 --- a/frozen_deps/Cryptodome/Cipher/ARC2.pyi +++ b/frozen_deps/Cryptodome/Cipher/ARC2.pyi @@ -1,4 +1,6 @@ -from typing import Union, Dict, Iterable +from typing import Union, Dict, Iterable, Optional + +Buffer = bytes|bytearray|memoryview from Cryptodome.Cipher._mode_ecb import EcbMode from Cryptodome.Cipher._mode_cbc import CbcMode @@ -18,13 +20,11 @@ MODE_CTR: ARC2Mode MODE_OPENPGP: ARC2Mode MODE_EAX: ARC2Mode -Buffer = Union[bytes, bytearray, memoryview] - def new(key: Buffer, mode: ARC2Mode, - iv : Buffer = ..., - IV : Buffer = ..., - nonce : Buffer = ..., + iv : Optional[Buffer] = ..., + IV : Optional[Buffer] = ..., + nonce : Optional[Buffer] = ..., segment_size : int = ..., mac_len : int = ..., initial_value : Union[int, Buffer] = ..., diff --git a/frozen_deps/Cryptodome/Cipher/ARC4.py b/frozen_deps/Cryptodome/Cipher/ARC4.py index e640e77..543a323 100644 --- a/frozen_deps/Cryptodome/Cipher/ARC4.py +++ b/frozen_deps/Cryptodome/Cipher/ARC4.py @@ -20,8 +20,6 @@ # SOFTWARE. # =================================================================== -from Cryptodome.Util.py3compat import b - from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer, create_string_buffer, get_raw_buffer, SmartPointer, c_size_t, c_uint8_ptr) @@ -113,7 +111,7 @@ def new(key, *args, **kwargs): :param key: The secret key to use in the symmetric cipher. - Its length must be in the range ``[5..256]``. + Its length must be in the range ``[1..256]``. The recommended length is 16 bytes. :type key: bytes, bytearray, memoryview @@ -131,7 +129,8 @@ def new(key, *args, **kwargs): """ return ARC4Cipher(key, *args, **kwargs) + # Size of a data block (in bytes) block_size = 1 # Size of a key (in bytes) -key_size = range(5, 256+1) +key_size = range(1, 256+1) diff --git a/frozen_deps/Cryptodome/Cipher/ARC4.pyi b/frozen_deps/Cryptodome/Cipher/ARC4.pyi index 2e75d6f..b081585 100644 --- a/frozen_deps/Cryptodome/Cipher/ARC4.pyi +++ b/frozen_deps/Cryptodome/Cipher/ARC4.pyi @@ -1,6 +1,6 @@ from typing import Any, Union, Iterable -Buffer = Union[bytes, bytearray, memoryview] +Buffer = bytes|bytearray|memoryview class ARC4Cipher: block_size: int diff --git a/frozen_deps/Cryptodome/Cipher/Blowfish.pyi b/frozen_deps/Cryptodome/Cipher/Blowfish.pyi index a669240..b8b21c6 100644 --- a/frozen_deps/Cryptodome/Cipher/Blowfish.pyi +++ b/frozen_deps/Cryptodome/Cipher/Blowfish.pyi @@ -1,4 +1,6 @@ -from typing import Union, Dict, Iterable +from typing import Union, Dict, Iterable, Optional + +Buffer = bytes|bytearray|memoryview from Cryptodome.Cipher._mode_ecb import EcbMode from Cryptodome.Cipher._mode_cbc import CbcMode @@ -18,13 +20,11 @@ MODE_CTR: BlowfishMode MODE_OPENPGP: BlowfishMode MODE_EAX: BlowfishMode -Buffer = Union[bytes, bytearray, memoryview] - def new(key: Buffer, mode: BlowfishMode, - iv : Buffer = ..., - IV : Buffer = ..., - nonce : Buffer = ..., + iv : Optional[Buffer] = ..., + IV : Optional[Buffer] = ..., + nonce : Optional[Buffer] = ..., segment_size : int = ..., mac_len : int = ..., initial_value : Union[int, Buffer] = ..., diff --git a/frozen_deps/Cryptodome/Cipher/CAST.pyi b/frozen_deps/Cryptodome/Cipher/CAST.pyi index 6b411cf..be01f09 100644 --- a/frozen_deps/Cryptodome/Cipher/CAST.pyi +++ b/frozen_deps/Cryptodome/Cipher/CAST.pyi @@ -1,4 +1,6 @@ -from typing import Union, Dict, Iterable +from typing import Union, Dict, Iterable, Optional + +Buffer = bytes|bytearray|memoryview from Cryptodome.Cipher._mode_ecb import EcbMode from Cryptodome.Cipher._mode_cbc import CbcMode @@ -18,13 +20,11 @@ MODE_CTR: CASTMode MODE_OPENPGP: CASTMode MODE_EAX: CASTMode -Buffer = Union[bytes, bytearray, memoryview] - def new(key: Buffer, mode: CASTMode, - iv : Buffer = ..., - IV : Buffer = ..., - nonce : Buffer = ..., + iv : Optional[Buffer] = ..., + IV : Optional[Buffer] = ..., + nonce : Optional[Buffer] = ..., segment_size : int = ..., mac_len : int = ..., initial_value : Union[int, Buffer] = ..., diff --git a/frozen_deps/Cryptodome/Cipher/ChaCha20.py b/frozen_deps/Cryptodome/Cipher/ChaCha20.py index b4f8b5f..648d692 100644 --- a/frozen_deps/Cryptodome/Cipher/ChaCha20.py +++ b/frozen_deps/Cryptodome/Cipher/ChaCha20.py @@ -106,7 +106,7 @@ class ChaCha20Cipher(object): self._name = "ChaCha20" nonce = self.nonce - self._next = ( self.encrypt, self.decrypt ) + self._next = ("encrypt", "decrypt") self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init( @@ -134,9 +134,9 @@ class ChaCha20Cipher(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("Cipher object can only be used for decryption") - self._next = ( self.encrypt, ) + self._next = ("encrypt",) return self._encrypt(plaintext, output) def _encrypt(self, plaintext, output): @@ -180,9 +180,9 @@ class ChaCha20Cipher(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("Cipher object can only be used for encryption") - self._next = ( self.decrypt, ) + self._next = ("decrypt",) try: return self._encrypt(ciphertext, output) diff --git a/frozen_deps/Cryptodome/Cipher/ChaCha20.pyi b/frozen_deps/Cryptodome/Cipher/ChaCha20.pyi index 3d00a1d..f5001cd 100644 --- a/frozen_deps/Cryptodome/Cipher/ChaCha20.pyi +++ b/frozen_deps/Cryptodome/Cipher/ChaCha20.pyi @@ -1,6 +1,6 @@ -from typing import Union, overload +from typing import Union, overload, Optional -Buffer = Union[bytes, bytearray, memoryview] +Buffer = bytes|bytearray|memoryview def _HChaCha20(key: Buffer, nonce: Buffer) -> bytearray: ... @@ -19,7 +19,7 @@ class ChaCha20Cipher: def decrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ... def seek(self, position: int) -> None: ... -def new(key: Buffer, nonce: Buffer = ...) -> ChaCha20Cipher: ... +def new(key: Buffer, nonce: Optional[Buffer] = ...) -> ChaCha20Cipher: ... block_size: int key_size: int diff --git a/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.py b/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.py index b6bc7a6..b2923ed 100644 --- a/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.py +++ b/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.py @@ -63,10 +63,8 @@ class ChaCha20Poly1305Cipher(object): See also `new()` at the module level.""" - self.nonce = _copy_bytes(None, None, nonce) - - self._next = (self.update, self.encrypt, self.decrypt, self.digest, - self.verify) + self._next = ("update", "encrypt", "decrypt", "digest", + "verify") self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20) @@ -94,7 +92,7 @@ class ChaCha20Poly1305Cipher(object): A piece of associated data. There are no restrictions on its size. """ - if self.update not in self._next: + if "update" not in self._next: raise TypeError("update() method cannot be called") self._len_aad += len(data) @@ -120,13 +118,13 @@ class ChaCha20Poly1305Cipher(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() method cannot be called") if self._status == _CipherStatus.PROCESSING_AUTH_DATA: self._pad_aad() - self._next = (self.encrypt, self.digest) + self._next = ("encrypt", "digest") result = self._cipher.encrypt(plaintext, output=output) self._len_ct += len(plaintext) @@ -149,13 +147,13 @@ class ChaCha20Poly1305Cipher(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() method cannot be called") if self._status == _CipherStatus.PROCESSING_AUTH_DATA: self._pad_aad() - self._next = (self.decrypt, self.verify) + self._next = ("decrypt", "verify") self._len_ct += len(ciphertext) self._authenticator.update(ciphertext) @@ -189,9 +187,9 @@ class ChaCha20Poly1305Cipher(object): :Return: the MAC tag, as 16 ``bytes``. """ - if self.digest not in self._next: + if "digest" not in self._next: raise TypeError("digest() method cannot be called") - self._next = (self.digest,) + self._next = ("digest",) return self._compute_mac() @@ -218,10 +216,10 @@ class ChaCha20Poly1305Cipher(object): or the key is incorrect. """ - if self.verify not in self._next: + if "verify" not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") - self._next = (self.verify,) + self._next = ("verify",) secret = get_random_bytes(16) @@ -316,10 +314,10 @@ def new(**kwargs): nonce = get_random_bytes(12) if len(nonce) in (8, 12): - pass + chacha20_poly1305_nonce = nonce elif len(nonce) == 24: key = _HChaCha20(key, nonce[:16]) - nonce = b'\x00\x00\x00\x00' + nonce[16:] + chacha20_poly1305_nonce = b'\x00\x00\x00\x00' + nonce[16:] else: raise ValueError("Nonce must be 8, 12 or 24 bytes long") @@ -329,7 +327,9 @@ def new(**kwargs): if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) - return ChaCha20Poly1305Cipher(key, nonce) + cipher = ChaCha20Poly1305Cipher(key, chacha20_poly1305_nonce) + cipher.nonce = _copy_bytes(None, None, nonce) + return cipher # Size of a key (in bytes) diff --git a/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.pyi b/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.pyi index ef0450f..109e805 100644 --- a/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.pyi +++ b/frozen_deps/Cryptodome/Cipher/ChaCha20_Poly1305.pyi @@ -1,6 +1,6 @@ -from typing import Union, Tuple, overload +from typing import Union, Tuple, overload, Optional -Buffer = Union[bytes, bytearray, memoryview] +Buffer = bytes|bytearray|memoryview class ChaCha20Poly1305Cipher: nonce: bytes @@ -22,7 +22,7 @@ class ChaCha20Poly1305Cipher: def encrypt_and_digest(self, plaintext: Buffer) -> Tuple[bytes, bytes]: ... def decrypt_and_verify(self, ciphertext: Buffer, received_mac_tag: Buffer) -> bytes: ... -def new(key: Buffer, nonce: Buffer = ...) -> ChaCha20Poly1305Cipher: ... +def new(key: Buffer, nonce: Optional[Buffer] = ...) -> ChaCha20Poly1305Cipher: ... block_size: int key_size: int diff --git a/frozen_deps/Cryptodome/Cipher/DES.pyi b/frozen_deps/Cryptodome/Cipher/DES.pyi index 1ba2752..25a3b23 100644 --- a/frozen_deps/Cryptodome/Cipher/DES.pyi +++ b/frozen_deps/Cryptodome/Cipher/DES.pyi @@ -1,4 +1,6 @@ -from typing import Union, Dict, Iterable +from typing import Union, Dict, Iterable, Optional + +Buffer = bytes|bytearray|memoryview from Cryptodome.Cipher._mode_ecb import EcbMode from Cryptodome.Cipher._mode_cbc import CbcMode @@ -18,13 +20,11 @@ MODE_CTR: DESMode MODE_OPENPGP: DESMode MODE_EAX: DESMode -Buffer = Union[bytes, bytearray, memoryview] - def new(key: Buffer, mode: DESMode, - iv : Buffer = ..., - IV : Buffer = ..., - nonce : Buffer = ..., + iv : Optional[Buffer] = ..., + IV : Optional[Buffer] = ..., + nonce : Optional[Buffer] = ..., segment_size : int = ..., mac_len : int = ..., initial_value : Union[int, Buffer] = ..., diff --git a/frozen_deps/Cryptodome/Cipher/DES3.pyi b/frozen_deps/Cryptodome/Cipher/DES3.pyi index c1a524f..2c150f8 100644 --- a/frozen_deps/Cryptodome/Cipher/DES3.pyi +++ b/frozen_deps/Cryptodome/Cipher/DES3.pyi @@ -1,4 +1,6 @@ -from typing import Union, Dict, Tuple +from typing import Union, Dict, Tuple, Optional + +Buffer = bytes|bytearray|memoryview from Cryptodome.Cipher._mode_ecb import EcbMode from Cryptodome.Cipher._mode_cbc import CbcMode @@ -20,13 +22,11 @@ MODE_CTR: DES3Mode MODE_OPENPGP: DES3Mode MODE_EAX: DES3Mode -Buffer = Union[bytes, bytearray, memoryview] - def new(key: Buffer, mode: DES3Mode, - iv : Buffer = ..., - IV : Buffer = ..., - nonce : Buffer = ..., + iv : Optional[Buffer] = ..., + IV : Optional[Buffer] = ..., + nonce : Optional[Buffer] = ..., segment_size : int = ..., mac_len : int = ..., initial_value : Union[int, Buffer] = ..., diff --git a/frozen_deps/Cryptodome/Cipher/PKCS1_OAEP.py b/frozen_deps/Cryptodome/Cipher/PKCS1_OAEP.py index 7525c5d..08f9efe 100644 --- a/frozen_deps/Cryptodome/Cipher/PKCS1_OAEP.py +++ b/frozen_deps/Cryptodome/Cipher/PKCS1_OAEP.py @@ -23,11 +23,13 @@ from Cryptodome.Signature.pss import MGF1 import Cryptodome.Hash.SHA1 -from Cryptodome.Util.py3compat import bord, _copy_bytes +from Cryptodome.Util.py3compat import _copy_bytes import Cryptodome.Util.number -from Cryptodome.Util.number import ceil_div, bytes_to_long, long_to_bytes -from Cryptodome.Util.strxor import strxor +from Cryptodome.Util.number import ceil_div, bytes_to_long, long_to_bytes +from Cryptodome.Util.strxor import strxor from Cryptodome import Random +from ._pkcs1_oaep_decode import oaep_decode + class PKCS1OAEP_Cipher: """Cipher object for PKCS#1 v1.5 OAEP. @@ -68,7 +70,7 @@ class PKCS1OAEP_Cipher: if mgfunc: self._mgf = mgfunc else: - self._mgf = lambda x,y: MGF1(x,y,self._hashObj) + self._mgf = lambda x, y: MGF1(x, y, self._hashObj) self._label = _copy_bytes(None, None, label) self._randfunc = randfunc @@ -105,7 +107,7 @@ class PKCS1OAEP_Cipher: # See 7.1.1 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) - k = ceil_div(modBits, 8) # Convert from bits to bytes + k = ceil_div(modBits, 8) # Convert from bits to bytes hLen = self._hashObj.digest_size mLen = len(message) @@ -159,22 +161,18 @@ class PKCS1OAEP_Cipher: # See 7.1.2 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) - k = ceil_div(modBits,8) # Convert from bits to bytes + k = ceil_div(modBits, 8) # Convert from bits to bytes hLen = self._hashObj.digest_size # Step 1b and 1c - if len(ciphertext) != k or k<hLen+2: + if len(ciphertext) != k or k < hLen+2: raise ValueError("Ciphertext with incorrect length.") # Step 2a (O2SIP) ct_int = bytes_to_long(ciphertext) - # Step 2b (RSADP) - m_int = self._key._decrypt(ct_int) - # Complete step 2c (I2OSP) - em = long_to_bytes(m_int, k) + # Step 2b (RSADP) and step 2c (I2OSP) + em = self._key._decrypt_to_bytes(ct_int) # Step 3a lHash = self._hashObj.new(self._label).digest() - # Step 3b - y = em[0] # y must be 0, but we MUST NOT check it here in order not to # allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143) maskedSeed = em[1:hLen+1] @@ -187,22 +185,17 @@ class PKCS1OAEP_Cipher: dbMask = self._mgf(seed, k-hLen-1) # Step 3f db = strxor(maskedDB, dbMask) - # Step 3g - one_pos = hLen + db[hLen:].find(b'\x01') - lHash1 = db[:hLen] - invalid = bord(y) | int(one_pos < hLen) - hash_compare = strxor(lHash1, lHash) - for x in hash_compare: - invalid |= bord(x) - for x in db[hLen:one_pos]: - invalid |= bord(x) - if invalid != 0: + # Step 3b + 3g + res = oaep_decode(em, lHash, db) + if res <= 0: raise ValueError("Incorrect decryption.") # Step 4 - return db[one_pos + 1:] + return db[res:] + def new(key, hashAlgo=None, mgfunc=None, label=b'', randfunc=None): - """Return a cipher object :class:`PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption. + """Return a cipher object :class:`PKCS1OAEP_Cipher` + that can be used to perform PKCS#1 OAEP encryption or decryption. :param key: The key object to use to encrypt or decrypt the message. @@ -236,4 +229,3 @@ def new(key, hashAlgo=None, mgfunc=None, label=b'', randfunc=None): if randfunc is None: randfunc = Random.get_random_bytes return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label, randfunc) - diff --git a/frozen_deps/Cryptodome/Cipher/PKCS1_v1_5.py b/frozen_deps/Cryptodome/Cipher/PKCS1_v1_5.py index 17ef9eb..d7a9b79 100644 --- a/frozen_deps/Cryptodome/Cipher/PKCS1_v1_5.py +++ b/frozen_deps/Cryptodome/Cipher/PKCS1_v1_5.py @@ -25,31 +25,7 @@ __all__ = ['new', 'PKCS115_Cipher'] from Cryptodome import Random from Cryptodome.Util.number import bytes_to_long, long_to_bytes from Cryptodome.Util.py3compat import bord, is_bytes, _copy_bytes - -from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, c_size_t, - c_uint8_ptr) - - -_raw_pkcs1_decode = load_pycryptodome_raw_lib("Cryptodome.Cipher._pkcs1_decode", - """ - int pkcs1_decode(const uint8_t *em, size_t len_em, - const uint8_t *sentinel, size_t len_sentinel, - size_t expected_pt_len, - uint8_t *output); - """) - - -def _pkcs1_decode(em, sentinel, expected_pt_len, output): - if len(em) != len(output): - raise ValueError("Incorrect output length") - - ret = _raw_pkcs1_decode.pkcs1_decode(c_uint8_ptr(em), - c_size_t(len(em)), - c_uint8_ptr(sentinel), - c_size_t(len(sentinel)), - c_size_t(expected_pt_len), - c_uint8_ptr(output)) - return ret +from ._pkcs1_oaep_decode import pkcs1_decode class PKCS115_Cipher: @@ -113,7 +89,6 @@ class PKCS115_Cipher: continue ps.append(new_byte) ps = b"".join(ps) - assert(len(ps) == k - mLen - 3) # Step 2b em = b'\x00\x02' + ps + b'\x00' + _copy_bytes(None, None, message) # Step 3a (OS2IP) @@ -176,23 +151,20 @@ class PKCS115_Cipher: # Step 2a (O2SIP) ct_int = bytes_to_long(ciphertext) - # Step 2b (RSADP) - m_int = self._key._decrypt(ct_int) - - # Complete step 2c (I2OSP) - em = long_to_bytes(m_int, k) + # Step 2b (RSADP) and Step 2c (I2OSP) + em = self._key._decrypt_to_bytes(ct_int) # Step 3 (not constant time when the sentinel is not a byte string) output = bytes(bytearray(k)) if not is_bytes(sentinel) or len(sentinel) > k: - size = _pkcs1_decode(em, b'', expected_pt_len, output) + size = pkcs1_decode(em, b'', expected_pt_len, output) if size < 0: return sentinel else: return output[size:] # Step 3 (somewhat constant time) - size = _pkcs1_decode(em, sentinel, expected_pt_len, output) + size = pkcs1_decode(em, sentinel, expected_pt_len, output) return output[size:] diff --git a/frozen_deps/Cryptodome/Cipher/Salsa20.pyi b/frozen_deps/Cryptodome/Cipher/Salsa20.pyi index 9178f0d..cf8690e 100644 --- a/frozen_deps/Cryptodome/Cipher/Salsa20.pyi +++ b/frozen_deps/Cryptodome/Cipher/Salsa20.pyi @@ -1,7 +1,6 @@ -from typing import Union, Tuple, Optional, overload +from typing import Union, Tuple, Optional, overload, Optional - -Buffer = Union[bytes, bytearray, memoryview] +Buffer = bytes|bytearray|memoryview class Salsa20Cipher: nonce: bytes diff --git a/frozen_deps/Cryptodome/Cipher/_ARC4.abi3.so b/frozen_deps/Cryptodome/Cipher/_ARC4.abi3.so Binary files differindex c367472..451d359 100755 --- a/frozen_deps/Cryptodome/Cipher/_ARC4.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_ARC4.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_ARC4.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_ARC4.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 41266ee..0000000 --- a/frozen_deps/Cryptodome/Cipher/_ARC4.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_Salsa20.abi3.so b/frozen_deps/Cryptodome/Cipher/_Salsa20.abi3.so Binary files differindex 10ba4b7..a303d91 100755 --- a/frozen_deps/Cryptodome/Cipher/_Salsa20.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_Salsa20.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_Salsa20.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_Salsa20.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 83a9be7..0000000 --- a/frozen_deps/Cryptodome/Cipher/_Salsa20.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_chacha20.abi3.so b/frozen_deps/Cryptodome/Cipher/_chacha20.abi3.so Binary files differindex 316d6cb..f1f1fa1 100755 --- a/frozen_deps/Cryptodome/Cipher/_chacha20.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_chacha20.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_chacha20.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_chacha20.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 554ee0e..0000000 --- a/frozen_deps/Cryptodome/Cipher/_chacha20.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_mode_cbc.py b/frozen_deps/Cryptodome/Cipher/_mode_cbc.py index edc29ca..94d02e7 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_cbc.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_cbc.py @@ -120,7 +120,7 @@ class CbcMode(object): self.IV = self.iv """Alias for `iv`""" - self._next = [ self.encrypt, self.decrypt ] + self._next = ["encrypt", "decrypt"] def encrypt(self, plaintext, output=None): """Encrypt data with the key and the parameters set at initialization. @@ -158,18 +158,18 @@ class CbcMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") - self._next = [ self.encrypt ] - + self._next = ["encrypt"] + if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output - + if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") - + if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) @@ -221,10 +221,10 @@ class CbcMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") - self._next = [ self.decrypt ] - + self._next = ["decrypt"] + if output is None: plaintext = create_string_buffer(len(ciphertext)) else: @@ -232,7 +232,7 @@ class CbcMode(object): if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") - + if len(ciphertext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) @@ -285,7 +285,7 @@ def _create_cbc_cipher(factory, **kwargs): if len(iv) != factory.block_size: raise ValueError("Incorrect IV length (it must be %d bytes long)" % - factory.block_size) + factory.block_size) if kwargs: raise TypeError("Unknown parameters for CBC: %s" % str(kwargs)) diff --git a/frozen_deps/Cryptodome/Cipher/_mode_ccm.py b/frozen_deps/Cryptodome/Cipher/_mode_ccm.py index 0e1c2f6..ec2e4f4 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_ccm.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_ccm.py @@ -155,8 +155,8 @@ class CcmMode(object): self._t = None # Allowed transitions after initialization - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] # Cumulative lengths self._cumul_assoc_len = 0 @@ -252,12 +252,12 @@ class CcmMode(object): A piece of associated data. There are no restrictions on its size. """ - if self.update not in self._next: + if "update" not in self._next: raise TypeError("update() can only be called" " immediately after initialization") - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] self._cumul_assoc_len += len(assoc_data) if self._assoc_len is not None and \ @@ -336,10 +336,10 @@ class CcmMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") - self._next = [self.encrypt, self.digest] + self._next = ["encrypt", "digest"] # No more associated data allowed from now if self._assoc_len is None: @@ -356,7 +356,7 @@ class CcmMode(object): if self._msg_len is None: self._msg_len = len(plaintext) self._start_mac() - self._next = [self.digest] + self._next = ["digest"] self._cumul_msg_len += len(plaintext) if self._cumul_msg_len > self._msg_len: @@ -409,10 +409,10 @@ class CcmMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() can only be called" " after initialization or an update()") - self._next = [self.decrypt, self.verify] + self._next = ["decrypt", "verify"] # No more associated data allowed from now if self._assoc_len is None: @@ -429,7 +429,7 @@ class CcmMode(object): if self._msg_len is None: self._msg_len = len(ciphertext) self._start_mac() - self._next = [self.verify] + self._next = ["verify"] self._cumul_msg_len += len(ciphertext) if self._cumul_msg_len > self._msg_len: @@ -461,10 +461,10 @@ class CcmMode(object): :Return: the MAC, as a byte string. """ - if self.digest not in self._next: + if "digest" not in self._next: raise TypeError("digest() cannot be called when decrypting" " or validating a message") - self._next = [self.digest] + self._next = ["digest"] return self._digest() def _digest(self): @@ -523,10 +523,10 @@ class CcmMode(object): or the key is incorrect. """ - if self.verify not in self._next: + if "verify" not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") - self._next = [self.verify] + self._next = ["verify"] self._digest() secret = get_random_bytes(16) diff --git a/frozen_deps/Cryptodome/Cipher/_mode_cfb.py b/frozen_deps/Cryptodome/Cipher/_mode_cfb.py index b790dd4..1b1b6c3 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_cfb.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_cfb.py @@ -119,7 +119,7 @@ class CfbMode(object): self.IV = self.iv """Alias for `iv`""" - self._next = [ self.encrypt, self.decrypt ] + self._next = ["encrypt", "decrypt"] def encrypt(self, plaintext, output=None): """Encrypt data with the key and the parameters set at initialization. @@ -154,18 +154,18 @@ class CfbMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") - self._next = [ self.encrypt ] - + self._next = ["encrypt"] + if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output - + if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") - + if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) @@ -215,10 +215,10 @@ class CfbMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") - self._next = [ self.decrypt ] - + self._next = ["decrypt"] + if output is None: plaintext = create_string_buffer(len(ciphertext)) else: @@ -226,11 +226,11 @@ class CfbMode(object): if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") - + if len(ciphertext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) - + result = raw_cfb_lib.CFB_decrypt(self._state.get(), c_uint8_ptr(ciphertext), c_uint8_ptr(plaintext), diff --git a/frozen_deps/Cryptodome/Cipher/_mode_ctr.py b/frozen_deps/Cryptodome/Cipher/_mode_ctr.py index 74783ec..9ce357f 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_ctr.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_ctr.py @@ -146,7 +146,7 @@ class CtrMode(object): self.block_size = len(initial_counter_block) """The block size of the underlying cipher, in bytes.""" - self._next = [self.encrypt, self.decrypt] + self._next = ["encrypt", "decrypt"] def encrypt(self, plaintext, output=None): """Encrypt data with the key and the parameters set at initialization. @@ -181,9 +181,9 @@ class CtrMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") - self._next = [self.encrypt] + self._next = ["encrypt"] if output is None: ciphertext = create_string_buffer(len(plaintext)) @@ -245,9 +245,9 @@ class CtrMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") - self._next = [self.decrypt] + self._next = ["decrypt"] if output is None: plaintext = create_string_buffer(len(ciphertext)) diff --git a/frozen_deps/Cryptodome/Cipher/_mode_eax.py b/frozen_deps/Cryptodome/Cipher/_mode_eax.py index 8efb77a..44ef21f 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_eax.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_eax.py @@ -90,12 +90,12 @@ class EaxMode(object): self._mac_tag = None # Cache for MAC tag # Allowed transitions after initialization - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] # MAC tag length - if not (4 <= self._mac_len <= self.block_size): - raise ValueError("Parameter 'mac_len' must not be larger than %d" + if not (2 <= self._mac_len <= self.block_size): + raise ValueError("'mac_len' must be at least 2 and not larger than %d" % self.block_size) # Nonce cannot be empty and must be a byte string @@ -145,12 +145,12 @@ class EaxMode(object): A piece of associated data. There are no restrictions on its size. """ - if self.update not in self._next: + if "update" not in self._next: raise TypeError("update() can only be called" " immediately after initialization") - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] self._signer.update(assoc_data) return self @@ -188,10 +188,10 @@ class EaxMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") - self._next = [self.encrypt, self.digest] + self._next = ["encrypt", "digest"] ct = self._cipher.encrypt(plaintext, output=output) if output is None: self._omac[2].update(ct) @@ -232,10 +232,10 @@ class EaxMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() can only be called" " after initialization or an update()") - self._next = [self.decrypt, self.verify] + self._next = ["decrypt", "verify"] self._omac[2].update(ciphertext) return self._cipher.decrypt(ciphertext, output=output) @@ -250,10 +250,10 @@ class EaxMode(object): :Return: the MAC, as a byte string. """ - if self.digest not in self._next: + if "digest" not in self._next: raise TypeError("digest() cannot be called when decrypting" " or validating a message") - self._next = [self.digest] + self._next = ["digest"] if not self._mac_tag: tag = b'\x00' * self.block_size @@ -289,10 +289,10 @@ class EaxMode(object): or the key is incorrect. """ - if self.verify not in self._next: + if "verify" not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") - self._next = [self.verify] + self._next = ["verify"] if not self._mac_tag: tag = b'\x00' * self.block_size diff --git a/frozen_deps/Cryptodome/Cipher/_mode_gcm.py b/frozen_deps/Cryptodome/Cipher/_mode_gcm.py index c90061b..9914400 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_gcm.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_gcm.py @@ -186,7 +186,7 @@ class GcmMode(object): if len(nonce) == 0: raise ValueError("Nonce cannot be empty") - + if not is_buffer(nonce): raise TypeError("Nonce must be bytes, bytearray or memoryview") @@ -207,8 +207,8 @@ class GcmMode(object): raise ValueError("Parameter 'mac_len' must be in the range 4..16") # Allowed transitions after initialization - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] self._no_more_assoc_data = False @@ -229,10 +229,10 @@ class GcmMode(object): if len(self.nonce) == 12: j0 = self.nonce + b"\x00\x00\x00\x01" else: - fill = (16 - (len(nonce) % 16)) % 16 + 8 + fill = (16 - (len(self.nonce) % 16)) % 16 + 8 ghash_in = (self.nonce + b'\x00' * fill + - long_to_bytes(8 * len(nonce), 8)) + long_to_bytes(8 * len(self.nonce), 8)) j0 = _GHASH(hash_subkey, ghash_c).update(ghash_in).digest() # Step 3 - Prepare GCTR cipher for encryption/decryption @@ -282,12 +282,12 @@ class GcmMode(object): A piece of associated data. There are no restrictions on its size. """ - if self.update not in self._next: + if "update" not in self._next: raise TypeError("update() can only be called" " immediately after initialization") - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] self._update(assoc_data) self._auth_len += len(assoc_data) @@ -364,10 +364,10 @@ class GcmMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") - self._next = [self.encrypt, self.digest] + self._next = ["encrypt", "digest"] ciphertext = self._cipher.encrypt(plaintext, output=output) @@ -417,10 +417,10 @@ class GcmMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() can only be called" " after initialization or an update()") - self._next = [self.decrypt, self.verify] + self._next = ["decrypt", "verify"] if self._status == MacStatus.PROCESSING_AUTH_DATA: self._pad_cache_and_update() @@ -442,10 +442,10 @@ class GcmMode(object): :Return: the MAC, as a byte string. """ - if self.digest not in self._next: + if "digest" not in self._next: raise TypeError("digest() cannot be called when decrypting" " or validating a message") - self._next = [self.digest] + self._next = ["digest"] return self._compute_mac() @@ -492,10 +492,10 @@ class GcmMode(object): or the key is incorrect. """ - if self.verify not in self._next: + if "verify" not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") - self._next = [self.verify] + self._next = ["verify"] secret = get_random_bytes(16) diff --git a/frozen_deps/Cryptodome/Cipher/_mode_ocb.py b/frozen_deps/Cryptodome/Cipher/_mode_ocb.py index 27c2797..1295e61 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_ocb.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_ocb.py @@ -71,7 +71,7 @@ Example: import struct from binascii import unhexlify -from Cryptodome.Util.py3compat import bord, _copy_bytes +from Cryptodome.Util.py3compat import bord, _copy_bytes, bchr from Cryptodome.Util.number import long_to_bytes, bytes_to_long from Cryptodome.Util.strxor import strxor @@ -142,15 +142,22 @@ class OcbMode(object): self._cache_P = b"" # Allowed transitions after initialization - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] # Compute Offset_0 params_without_key = dict(cipher_params) key = params_without_key.pop("key") - nonce = (struct.pack('B', self._mac_len << 4 & 0xFF) + - b'\x00' * (14 - len(nonce)) + - b'\x01' + self.nonce) + + taglen_mod128 = (self._mac_len * 8) % 128 + if len(self.nonce) < 15: + nonce = bchr(taglen_mod128 << 1) +\ + b'\x00' * (14 - len(nonce)) +\ + b'\x01' +\ + self.nonce + else: + nonce = bchr((taglen_mod128 << 1) | 0x01) +\ + self.nonce bottom_bits = bord(nonce[15]) & 0x3F # 6 bits, 0..63 top_bits = bord(nonce[15]) & 0xC0 # 2 bits @@ -217,12 +224,12 @@ class OcbMode(object): A piece of associated data. """ - if self.update not in self._next: + if "update" not in self._next: raise TypeError("update() can only be called" " immediately after initialization") - self._next = [self.encrypt, self.decrypt, self.digest, - self.verify, self.update] + self._next = ["encrypt", "decrypt", "digest", + "verify", "update"] if len(self._cache_A) > 0: filler = min(16 - len(self._cache_A), len(assoc_data)) @@ -316,14 +323,14 @@ class OcbMode(object): Its length may not match the length of the *plaintext*. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") if plaintext is None: - self._next = [self.digest] + self._next = ["digest"] else: - self._next = [self.encrypt] + self._next = ["encrypt"] return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt") def decrypt(self, ciphertext=None): @@ -345,14 +352,14 @@ class OcbMode(object): Its length may not match the length of the *ciphertext*. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() can only be called after" " initialization or an update()") if ciphertext is None: - self._next = [self.verify] + self._next = ["verify"] else: - self._next = [self.decrypt] + self._next = ["decrypt"] return self._transcrypt(ciphertext, _raw_ocb_lib.OCB_decrypt, "decrypt") @@ -388,12 +395,12 @@ class OcbMode(object): :Return: the MAC, as a byte string. """ - if self.digest not in self._next: + if "digest" not in self._next: raise TypeError("digest() cannot be called now for this cipher") assert(len(self._cache_P) == 0) - self._next = [self.digest] + self._next = ["digest"] if self._mac_tag is None: self._compute_mac_tag() @@ -423,12 +430,12 @@ class OcbMode(object): or the key is incorrect. """ - if self.verify not in self._next: + if "verify" not in self._next: raise TypeError("verify() cannot be called now for this cipher") assert(len(self._cache_P) == 0) - self._next = [self.verify] + self._next = ["verify"] if self._mac_tag is None: self._compute_mac_tag() diff --git a/frozen_deps/Cryptodome/Cipher/_mode_ofb.py b/frozen_deps/Cryptodome/Cipher/_mode_ofb.py index 04aaccf..8c0ccf6 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_ofb.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_ofb.py @@ -116,7 +116,7 @@ class OfbMode(object): self.IV = self.iv """Alias for `iv`""" - self._next = [ self.encrypt, self.decrypt ] + self._next = ["encrypt", "decrypt"] def encrypt(self, plaintext, output=None): """Encrypt data with the key and the parameters set at initialization. @@ -151,18 +151,18 @@ class OfbMode(object): Otherwise, ``None``. """ - if self.encrypt not in self._next: + if "encrypt" not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") - self._next = [ self.encrypt ] - + self._next = ["encrypt"] + if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output - + if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") - + if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) @@ -212,10 +212,10 @@ class OfbMode(object): Otherwise, ``None``. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") - self._next = [ self.decrypt ] - + self._next = ["decrypt"] + if output is None: plaintext = create_string_buffer(len(ciphertext)) else: @@ -223,7 +223,7 @@ class OfbMode(object): if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") - + if len(ciphertext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) diff --git a/frozen_deps/Cryptodome/Cipher/_mode_siv.py b/frozen_deps/Cryptodome/Cipher/_mode_siv.py index d10c4dc..4a76ad6 100644 --- a/frozen_deps/Cryptodome/Cipher/_mode_siv.py +++ b/frozen_deps/Cryptodome/Cipher/_mode_siv.py @@ -123,8 +123,8 @@ class SivMode(object): factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs) # Allowed transitions after initialization - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] def _create_ctr_cipher(self, v): """Create a new CTR cipher from V in SIV mode""" @@ -164,12 +164,12 @@ class SivMode(object): The next associated data component. """ - if self.update not in self._next: + if "update" not in self._next: raise TypeError("update() can only be called" " immediately after initialization") - self._next = [self.update, self.encrypt, self.decrypt, - self.digest, self.verify] + self._next = ["update", "encrypt", "decrypt", + "digest", "verify"] return self._kdf.update(component) @@ -206,10 +206,10 @@ class SivMode(object): :Return: the MAC, as a byte string. """ - if self.digest not in self._next: + if "digest" not in self._next: raise TypeError("digest() cannot be called when decrypting" " or validating a message") - self._next = [self.digest] + self._next = ["digest"] if self._mac_tag is None: self._mac_tag = self._kdf.derive() return self._mac_tag @@ -240,10 +240,10 @@ class SivMode(object): or the key is incorrect. """ - if self.verify not in self._next: + if "verify" not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") - self._next = [self.verify] + self._next = ["verify"] if self._mac_tag is None: self._mac_tag = self._kdf.derive() @@ -290,19 +290,19 @@ class SivMode(object): The first item becomes ``None`` when the ``output`` parameter specified a location for the result. """ - - if self.encrypt not in self._next: + + if "encrypt" not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") - self._next = [ self.digest ] + self._next = ["digest"] # Compute V (MAC) if hasattr(self, 'nonce'): self._kdf.update(self.nonce) self._kdf.update(plaintext) self._mac_tag = self._kdf.derive() - + cipher = self._create_ctr_cipher(self._mac_tag) return cipher.encrypt(plaintext, output=output), self._mac_tag @@ -336,10 +336,10 @@ class SivMode(object): or the key is incorrect. """ - if self.decrypt not in self._next: + if "decrypt" not in self._next: raise TypeError("decrypt() can only be called" " after initialization or an update()") - self._next = [ self.verify ] + self._next = ["verify"] # Take the MAC and start the cipher for decryption self._cipher = self._create_ctr_cipher(mac_tag) @@ -350,7 +350,7 @@ class SivMode(object): self._kdf.update(self.nonce) self._kdf.update(plaintext if output is None else output) self.verify(mac_tag) - + return plaintext diff --git a/frozen_deps/Cryptodome/Cipher/_pkcs1_decode.abi3.so b/frozen_deps/Cryptodome/Cipher/_pkcs1_decode.abi3.so Binary files differindex cbb4a6f..71cd311 100755 --- a/frozen_deps/Cryptodome/Cipher/_pkcs1_decode.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_pkcs1_decode.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_pkcs1_oaep_decode.py b/frozen_deps/Cryptodome/Cipher/_pkcs1_oaep_decode.py new file mode 100644 index 0000000..82bdaa7 --- /dev/null +++ b/frozen_deps/Cryptodome/Cipher/_pkcs1_oaep_decode.py @@ -0,0 +1,41 @@ +from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, c_size_t, + c_uint8_ptr) + + +_raw_pkcs1_decode = load_pycryptodome_raw_lib("Cryptodome.Cipher._pkcs1_decode", + """ + int pkcs1_decode(const uint8_t *em, size_t len_em, + const uint8_t *sentinel, size_t len_sentinel, + size_t expected_pt_len, + uint8_t *output); + + int oaep_decode(const uint8_t *em, + size_t em_len, + const uint8_t *lHash, + size_t hLen, + const uint8_t *db, + size_t db_len); + """) + + +def pkcs1_decode(em, sentinel, expected_pt_len, output): + if len(em) != len(output): + raise ValueError("Incorrect output length") + + ret = _raw_pkcs1_decode.pkcs1_decode(c_uint8_ptr(em), + c_size_t(len(em)), + c_uint8_ptr(sentinel), + c_size_t(len(sentinel)), + c_size_t(expected_pt_len), + c_uint8_ptr(output)) + return ret + + +def oaep_decode(em, lHash, db): + ret = _raw_pkcs1_decode.oaep_decode(c_uint8_ptr(em), + c_size_t(len(em)), + c_uint8_ptr(lHash), + c_size_t(len(lHash)), + c_uint8_ptr(db), + c_size_t(len(db))) + return ret diff --git a/frozen_deps/Cryptodome/Cipher/_raw_aes.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_aes.abi3.so Binary files differindex 883fc94..b37dd95 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_aes.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_aes.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_aes.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_aes.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 027ed17..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_aes.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_aesni.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_aesni.abi3.so Binary files differindex 8e971c8..5f08fe7 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_aesni.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_aesni.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_aesni.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_aesni.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 1ec22d9..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_aesni.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_arc2.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_arc2.abi3.so Binary files differindex 2370b62..2287d2e 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_arc2.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_arc2.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_arc2.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_arc2.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index d439cbc..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_arc2.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_blowfish.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_blowfish.abi3.so Binary files differindex 48af6a3..ad77ccb 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_blowfish.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_blowfish.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_blowfish.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_blowfish.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 158eed5..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_blowfish.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_cast.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_cast.abi3.so Binary files differindex 7efb7e7..730e178 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_cast.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_cast.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_cast.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_cast.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index f416c8d..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_cast.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_cbc.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_cbc.abi3.so Binary files differindex 0696380..847d824 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_cbc.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_cbc.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_cbc.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_cbc.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index fd0fa43..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_cbc.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_cfb.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_cfb.abi3.so Binary files differindex 32d333a..2c9b852 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_cfb.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_cfb.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_cfb.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_cfb.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 7bb29c0..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_cfb.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ctr.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_ctr.abi3.so Binary files differindex 1810b56..761cd36 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_ctr.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_ctr.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ctr.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_ctr.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index f70ad97..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_ctr.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_des.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_des.abi3.so Binary files differindex 01a2495..7f1f824 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_des.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_des.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_des.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_des.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 622e436..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_des.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_des3.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_des3.abi3.so Binary files differindex ec932c1..b475c52 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_des3.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_des3.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_des3.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_des3.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index d1b6042..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_des3.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ecb.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_ecb.abi3.so Binary files differindex 7dc6a67..91e8126 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_ecb.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_ecb.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index be15667..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.abi3.so Binary files differindex 43734c9..c3c45d5 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index c003ada..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_eksblowfish.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ocb.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_ocb.abi3.so Binary files differindex 50e0016..9685971 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_ocb.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_ocb.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ocb.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_ocb.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index fa682a1..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_ocb.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ofb.abi3.so b/frozen_deps/Cryptodome/Cipher/_raw_ofb.abi3.so Binary files differindex e0db6db..a4a629a 100755 --- a/frozen_deps/Cryptodome/Cipher/_raw_ofb.abi3.so +++ b/frozen_deps/Cryptodome/Cipher/_raw_ofb.abi3.so diff --git a/frozen_deps/Cryptodome/Cipher/_raw_ofb.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Cipher/_raw_ofb.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 12b870c..0000000 --- a/frozen_deps/Cryptodome/Cipher/_raw_ofb.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/BLAKE2b.py b/frozen_deps/Cryptodome/Hash/BLAKE2b.py index d7e968f..85da887 100644 --- a/frozen_deps/Cryptodome/Hash/BLAKE2b.py +++ b/frozen_deps/Cryptodome/Hash/BLAKE2b.py @@ -233,13 +233,13 @@ def new(**kwargs): raise ValueError("'digest_bytes' not in range 1..64") else: if not (8 <= digest_bits <= 512) or (digest_bits % 8): - raise ValueError("'digest_bytes' not in range 8..512, " + raise ValueError("'digest_bits' not in range 8..512, " "with steps of 8") digest_bytes = digest_bits // 8 key = kwargs.pop("key", b"") if len(key) > 64: - raise ValueError("BLAKE2s key cannot exceed 64 bytes") + raise ValueError("BLAKE2b key cannot exceed 64 bytes") if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) diff --git a/frozen_deps/Cryptodome/Hash/BLAKE2s.py b/frozen_deps/Cryptodome/Hash/BLAKE2s.py index a16b515..43be5c4 100644 --- a/frozen_deps/Cryptodome/Hash/BLAKE2s.py +++ b/frozen_deps/Cryptodome/Hash/BLAKE2s.py @@ -233,7 +233,7 @@ def new(**kwargs): raise ValueError("'digest_bytes' not in range 1..32") else: if not (8 <= digest_bits <= 256) or (digest_bits % 8): - raise ValueError("'digest_bytes' not in range 8..256, " + raise ValueError("'digest_bits' not in range 8..256, " "with steps of 8") digest_bytes = digest_bits // 8 diff --git a/frozen_deps/Cryptodome/Hash/CMAC.py b/frozen_deps/Cryptodome/Hash/CMAC.py index e831700..8feb79f 100644 --- a/frozen_deps/Cryptodome/Hash/CMAC.py +++ b/frozen_deps/Cryptodome/Hash/CMAC.py @@ -242,11 +242,15 @@ class CMAC(object): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): - """Return the **printable** MAC tag of the message authenticated so far. + """Verify that a given **printable** MAC (computed by another party) + is valid. - :return: The MAC tag, computed over the data processed so far. - Hexadecimal encoded. - :rtype: string + Args: + hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string. + + Raises: + ValueError: if the MAC does not match. It means that the message + has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag))) diff --git a/frozen_deps/Cryptodome/Hash/HMAC.py b/frozen_deps/Cryptodome/Hash/HMAC.py index 165dd83..615056a 100644 --- a/frozen_deps/Cryptodome/Hash/HMAC.py +++ b/frozen_deps/Cryptodome/Hash/HMAC.py @@ -35,13 +35,28 @@ from Cryptodome.Util.py3compat import bord, tobytes from binascii import unhexlify -from Cryptodome.Hash import MD5 from Cryptodome.Hash import BLAKE2s from Cryptodome.Util.strxor import strxor from Cryptodome.Random import get_random_bytes __all__ = ['new', 'HMAC'] +_hash2hmac_oid = { + '1.3.14.3.2.26': '1.2.840.113549.2.7', # SHA-1 + '2.16.840.1.101.3.4.2.4': '1.2.840.113549.2.8', # SHA-224 + '2.16.840.1.101.3.4.2.1': '1.2.840.113549.2.9', # SHA-256 + '2.16.840.1.101.3.4.2.2': '1.2.840.113549.2.10', # SHA-384 + '2.16.840.1.101.3.4.2.3': '1.2.840.113549.2.11', # SHA-512 + '2.16.840.1.101.3.4.2.5': '1.2.840.113549.2.12', # SHA-512_224 + '2.16.840.1.101.3.4.2.6': '1.2.840.113549.2.13', # SHA-512_256 + '2.16.840.1.101.3.4.2.7': '2.16.840.1.101.3.4.2.13', # SHA-3 224 + '2.16.840.1.101.3.4.2.8': '2.16.840.1.101.3.4.2.14', # SHA-3 256 + '2.16.840.1.101.3.4.2.9': '2.16.840.1.101.3.4.2.15', # SHA-3 384 + '2.16.840.1.101.3.4.2.10': '2.16.840.1.101.3.4.2.16', # SHA-3 512 +} + +_hmac2hash_oid = {v: k for k, v in _hash2hmac_oid.items()} + class HMAC(object): """An HMAC hash object. @@ -49,11 +64,15 @@ class HMAC(object): :ivar digest_size: the size in bytes of the resulting MAC tag :vartype digest_size: integer + + :ivar oid: the ASN.1 object ID of the HMAC algorithm. + Only present if the algorithm was officially assigned one. """ def __init__(self, key, msg=b"", digestmod=None): if digestmod is None: + from Cryptodome.Hash import MD5 digestmod = MD5 if msg is None: @@ -64,6 +83,12 @@ class HMAC(object): self._digestmod = digestmod + # Hash OID --> HMAC OID + try: + self.oid = _hash2hmac_oid[digestmod.oid] + except (KeyError, AttributeError): + pass + if isinstance(key, memoryview): key = key.tobytes() diff --git a/frozen_deps/Cryptodome/Hash/KangarooTwelve.py b/frozen_deps/Cryptodome/Hash/KangarooTwelve.py index 44d935f..60ced57 100644 --- a/frozen_deps/Cryptodome/Hash/KangarooTwelve.py +++ b/frozen_deps/Cryptodome/Hash/KangarooTwelve.py @@ -28,16 +28,10 @@ # POSSIBILITY OF SUCH DAMAGE. # =================================================================== -from Cryptodome.Util._raw_api import (VoidPointer, SmartPointer, - create_string_buffer, - get_raw_buffer, c_size_t, - c_uint8_ptr, c_ubyte) - from Cryptodome.Util.number import long_to_bytes from Cryptodome.Util.py3compat import bchr -from .keccak import _raw_keccak_lib - +from . import TurboSHAKE128 def _length_encode(x): if x == 0: @@ -70,7 +64,8 @@ class K12_XOF(object): self._padding = None # Final padding is only decided in read() # Internal hash that consumes FinalNode - self._hash1 = self._create_keccak() + # The real domain separation byte will be known before squeezing + self._hash1 = TurboSHAKE128.new(domain=1) self._length1 = 0 # Internal hash that produces CV_i (reset each time) @@ -83,42 +78,6 @@ class K12_XOF(object): if data: self.update(data) - def _create_keccak(self): - state = VoidPointer() - result = _raw_keccak_lib.keccak_init(state.address_of(), - c_size_t(32), # 32 bytes of capacity (256 bits) - c_ubyte(12)) # Reduced number of rounds - if result: - raise ValueError("Error %d while instantiating KangarooTwelve" - % result) - return SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) - - def _update(self, data, hash_obj): - result = _raw_keccak_lib.keccak_absorb(hash_obj.get(), - c_uint8_ptr(data), - c_size_t(len(data))) - if result: - raise ValueError("Error %d while updating KangarooTwelve state" - % result) - - def _squeeze(self, hash_obj, length, padding): - bfr = create_string_buffer(length) - result = _raw_keccak_lib.keccak_squeeze(hash_obj.get(), - bfr, - c_size_t(length), - c_ubyte(padding)) - if result: - raise ValueError("Error %d while extracting from KangarooTwelve" - % result) - - return get_raw_buffer(bfr) - - def _reset(self, hash_obj): - result = _raw_keccak_lib.keccak_reset(hash_obj.get()) - if result: - raise ValueError("Error %d while resetting KangarooTwelve state" - % result) - def update(self, data): """Hash the next piece of data. @@ -127,7 +86,7 @@ class K12_XOF(object): Args: data (byte string/byte array/memoryview): The next chunk of the - message to hash. + message to hash. """ if self._state == SQUEEZING: @@ -138,7 +97,7 @@ class K12_XOF(object): if next_length + len(self._custom) <= 8192: self._length1 = next_length - self._update(data, self._hash1) + self._hash1.update(data) return self # Switch to tree hashing @@ -148,7 +107,7 @@ class K12_XOF(object): data_mem = memoryview(data) assert(self._length1 < 8192) dtc = min(len(data), 8192 - self._length1) - self._update(data_mem[:dtc], self._hash1) + self._hash1.update(data_mem[:dtc]) self._length1 += dtc if self._length1 < 8192: @@ -158,10 +117,10 @@ class K12_XOF(object): assert(self._length1 == 8192) divider = b'\x03' + b'\x00' * 7 - self._update(divider, self._hash1) + self._hash1.update(divider) self._length1 += 8 - self._hash2 = self._create_keccak() + self._hash2 = TurboSHAKE128.new(domain=0x0B) self._length2 = 0 self._ctr = 1 @@ -178,15 +137,15 @@ class K12_XOF(object): while index < len_data: new_index = min(index + 8192 - self._length2, len_data) - self._update(data_mem[index:new_index], self._hash2) + self._hash2.update(data_mem[index:new_index]) self._length2 += new_index - index index = new_index if self._length2 == 8192: - cv_i = self._squeeze(self._hash2, 32, 0x0B) - self._update(cv_i, self._hash1) + cv_i = self._hash2.read(32) + self._hash1.update(cv_i) self._length1 += 32 - self._reset(self._hash2) + self._hash2._reset() self._length2 = 0 self._ctr += 1 @@ -210,7 +169,7 @@ class K12_XOF(object): custom_was_consumed = False if self._state == SHORT_MSG: - self._update(self._custom, self._hash1) + self._hash1.update(self._custom) self._padding = 0x07 self._state = SQUEEZING @@ -225,20 +184,21 @@ class K12_XOF(object): # Is there still some leftover data in hash2? if self._length2 > 0: - cv_i = self._squeeze(self._hash2, 32, 0x0B) - self._update(cv_i, self._hash1) + cv_i = self._hash2.read(32) + self._hash1.update(cv_i) self._length1 += 32 - self._reset(self._hash2) + self._hash2._reset() self._length2 = 0 self._ctr += 1 trailer = _length_encode(self._ctr - 1) + b'\xFF\xFF' - self._update(trailer, self._hash1) + self._hash1.update(trailer) self._padding = 0x06 self._state = SQUEEZING - return self._squeeze(self._hash1, length, self._padding) + self._hash1._domain = self._padding + return self._hash1.read(length) def new(self, data=None, custom=b''): return type(self)(data, custom) diff --git a/frozen_deps/Cryptodome/Hash/TupleHash128.py b/frozen_deps/Cryptodome/Hash/TupleHash128.py index 5c910e4..49aeccc 100644 --- a/frozen_deps/Cryptodome/Hash/TupleHash128.py +++ b/frozen_deps/Cryptodome/Hash/TupleHash128.py @@ -47,20 +47,21 @@ class TupleHash(object): self._cshake = cshake._new(b'', custom, b'TupleHash') self._digest = None - def update(self, data): - """Authenticate the next byte string in the tuple. + def update(self, *data): + """Authenticate the next tuple of byte strings. + TupleHash guarantees the logical separation between each byte string. Args: - data (bytes/bytearray/memoryview): The next byte string. + data (bytes/bytearray/memoryview): One or more items to hash. """ if self._digest is not None: raise TypeError("You cannot call 'update' after 'digest' or 'hexdigest'") - if not is_bytes(data): - raise TypeError("You can only call 'update' on bytes") - - self._cshake.update(_encode_str(tobytes(data))) + for item in data: + if not is_bytes(item): + raise TypeError("You can only call 'update' on bytes" ) + self._cshake.update(_encode_str(item)) return self @@ -132,7 +133,4 @@ def new(**kwargs): custom = kwargs.pop("custom", b'') - if kwargs: - raise TypeError("Unknown parameters: " + str(kwargs)) - return TupleHash(custom, cSHAKE128, digest_bytes) diff --git a/frozen_deps/Cryptodome/Hash/TupleHash128.pyi b/frozen_deps/Cryptodome/Hash/TupleHash128.pyi index 3b1e81e..2e0ea83 100644 --- a/frozen_deps/Cryptodome/Hash/TupleHash128.pyi +++ b/frozen_deps/Cryptodome/Hash/TupleHash128.pyi @@ -1,4 +1,4 @@ -from typing import Any, Union +from typing import Any, Union, List, Tuple from types import ModuleType Buffer = Union[bytes, bytearray, memoryview] @@ -9,7 +9,7 @@ class TupleHash(object): custom: bytes, cshake: ModuleType, digest_size: int) -> None: ... - def update(self, data: Buffer) -> TupleHash: ... + def update(self, *data: Buffer) -> TupleHash: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... def new(self, diff --git a/frozen_deps/Cryptodome/Hash/TupleHash256.py b/frozen_deps/Cryptodome/Hash/TupleHash256.py index 9b4fba0..40a824a 100644 --- a/frozen_deps/Cryptodome/Hash/TupleHash256.py +++ b/frozen_deps/Cryptodome/Hash/TupleHash256.py @@ -67,7 +67,4 @@ def new(**kwargs): custom = kwargs.pop("custom", b'') - if kwargs: - raise TypeError("Unknown parameters: " + str(kwargs)) - return TupleHash(custom, cSHAKE256, digest_bytes) diff --git a/frozen_deps/Cryptodome/Hash/TurboSHAKE128.py b/frozen_deps/Cryptodome/Hash/TurboSHAKE128.py new file mode 100644 index 0000000..92ac59e --- /dev/null +++ b/frozen_deps/Cryptodome/Hash/TurboSHAKE128.py @@ -0,0 +1,112 @@ +from Cryptodome.Util._raw_api import (VoidPointer, SmartPointer, + create_string_buffer, + get_raw_buffer, c_size_t, + c_uint8_ptr, c_ubyte) + +from Cryptodome.Util.number import long_to_bytes +from Cryptodome.Util.py3compat import bchr + +from .keccak import _raw_keccak_lib + + +class TurboSHAKE(object): + """A TurboSHAKE hash object. + Do not instantiate directly. + Use the :func:`new` function. + """ + + def __init__(self, capacity, domain_separation, data): + + state = VoidPointer() + result = _raw_keccak_lib.keccak_init(state.address_of(), + c_size_t(capacity), + c_ubyte(12)) # Reduced number of rounds + if result: + raise ValueError("Error %d while instantiating TurboSHAKE" + % result) + self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) + + self._is_squeezing = False + self._capacity = capacity + self._domain = domain_separation + + if data: + self.update(data) + + + def update(self, data): + """Continue hashing of a message by consuming the next chunk of data. + + Args: + data (byte string/byte array/memoryview): The next chunk of the message being hashed. + """ + + if self._is_squeezing: + raise TypeError("You cannot call 'update' after the first 'read'") + + result = _raw_keccak_lib.keccak_absorb(self._state.get(), + c_uint8_ptr(data), + c_size_t(len(data))) + if result: + raise ValueError("Error %d while updating TurboSHAKE state" + % result) + return self + + def read(self, length): + """ + Compute the next piece of XOF output. + + .. note:: + You cannot use :meth:`update` anymore after the first call to + :meth:`read`. + + Args: + length (integer): the amount of bytes this method must return + + :return: the next piece of XOF output (of the given length) + :rtype: byte string + """ + + self._is_squeezing = True + bfr = create_string_buffer(length) + result = _raw_keccak_lib.keccak_squeeze(self._state.get(), + bfr, + c_size_t(length), + c_ubyte(self._domain)) + if result: + raise ValueError("Error %d while extracting from TurboSHAKE" + % result) + + return get_raw_buffer(bfr) + + def new(self, data=None): + return type(self)(self._capacity, self._domain, data) + + def _reset(self): + result = _raw_keccak_lib.keccak_reset(self._state.get()) + if result: + raise ValueError("Error %d while resetting TurboSHAKE state" + % result) + self._is_squeezing = False + + +def new(**kwargs): + """Create a new TurboSHAKE128 object. + + Args: + domain (integer): + Optional - A domain separation byte, between 0x01 and 0x7F. + The default value is 0x1F. + data (bytes/bytearray/memoryview): + Optional - The very first chunk of the message to hash. + It is equivalent to an early call to :meth:`update`. + + :Return: A :class:`TurboSHAKE` object + """ + + domain_separation = kwargs.get('domain', 0x1F) + if not (0x01 <= domain_separation <= 0x7F): + raise ValueError("Incorrect domain separation value (%d)" % + domain_separation) + data = kwargs.get('data') + return TurboSHAKE(32, domain_separation, data=data) diff --git a/frozen_deps/Cryptodome/Hash/TurboSHAKE128.pyi b/frozen_deps/Cryptodome/Hash/TurboSHAKE128.pyi new file mode 100644 index 0000000..d74c9c0 --- /dev/null +++ b/frozen_deps/Cryptodome/Hash/TurboSHAKE128.pyi @@ -0,0 +1,17 @@ +from typing import Union, Optional +from typing_extensions import TypedDict, Unpack, NotRequired + +Buffer = Union[bytes, bytearray, memoryview] + +class TurboSHAKE(object): + + def __init__(self, capacity: int, domain_separation: int, data: Union[Buffer, None]) -> None: ... + def update(self, data: Buffer) -> TurboSHAKE : ... + def read(self, length: int) -> bytes: ... + def new(self, data: Optional[Buffer]=None) -> TurboSHAKE: ... + +class Args(TypedDict): + domain: NotRequired[int] + data: NotRequired[Buffer] + +def new(**kwargs: Unpack[Args]) -> TurboSHAKE: ... diff --git a/frozen_deps/Cryptodome/Hash/TurboSHAKE256.py b/frozen_deps/Cryptodome/Hash/TurboSHAKE256.py new file mode 100644 index 0000000..ce27a48 --- /dev/null +++ b/frozen_deps/Cryptodome/Hash/TurboSHAKE256.py @@ -0,0 +1,22 @@ +from .TurboSHAKE128 import TurboSHAKE + +def new(**kwargs): + """Create a new TurboSHAKE256 object. + + Args: + domain (integer): + Optional - A domain separation byte, between 0x01 and 0x7F. + The default value is 0x1F. + data (bytes/bytearray/memoryview): + Optional - The very first chunk of the message to hash. + It is equivalent to an early call to :meth:`update`. + + :Return: A :class:`TurboSHAKE` object + """ + + domain_separation = kwargs.get('domain', 0x1F) + if not (0x01 <= domain_separation <= 0x7F): + raise ValueError("Incorrect domain separation value (%d)" % + domain_separation) + data = kwargs.get('data') + return TurboSHAKE(64, domain_separation, data=data) diff --git a/frozen_deps/Cryptodome/Hash/TurboSHAKE256.pyi b/frozen_deps/Cryptodome/Hash/TurboSHAKE256.pyi new file mode 100644 index 0000000..561e946 --- /dev/null +++ b/frozen_deps/Cryptodome/Hash/TurboSHAKE256.pyi @@ -0,0 +1,12 @@ +from typing import Union +from typing_extensions import TypedDict, Unpack, NotRequired + +from .TurboSHAKE128 import TurboSHAKE + +Buffer = Union[bytes, bytearray, memoryview] + +class Args(TypedDict): + domain: NotRequired[int] + data: NotRequired[Buffer] + +def new(**kwargs: Unpack[Args]) -> TurboSHAKE: ... diff --git a/frozen_deps/Cryptodome/Hash/_BLAKE2b.abi3.so b/frozen_deps/Cryptodome/Hash/_BLAKE2b.abi3.so Binary files differindex dfdf331..40cf664 100755 --- a/frozen_deps/Cryptodome/Hash/_BLAKE2b.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_BLAKE2b.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_BLAKE2b.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_BLAKE2b.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 7338d66..0000000 --- a/frozen_deps/Cryptodome/Hash/_BLAKE2b.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_BLAKE2s.abi3.so b/frozen_deps/Cryptodome/Hash/_BLAKE2s.abi3.so Binary files differindex 26e69e8..04a1ace 100755 --- a/frozen_deps/Cryptodome/Hash/_BLAKE2s.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_BLAKE2s.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_BLAKE2s.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_BLAKE2s.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index db4ebde..0000000 --- a/frozen_deps/Cryptodome/Hash/_BLAKE2s.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_MD2.abi3.so b/frozen_deps/Cryptodome/Hash/_MD2.abi3.so Binary files differindex 576ba1e..1573ca3 100755 --- a/frozen_deps/Cryptodome/Hash/_MD2.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_MD2.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_MD2.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_MD2.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index e56703c..0000000 --- a/frozen_deps/Cryptodome/Hash/_MD2.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_MD4.abi3.so b/frozen_deps/Cryptodome/Hash/_MD4.abi3.so Binary files differindex 0afc5ca..8f41e31 100755 --- a/frozen_deps/Cryptodome/Hash/_MD4.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_MD4.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_MD4.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_MD4.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index fbf60b8..0000000 --- a/frozen_deps/Cryptodome/Hash/_MD4.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_MD5.abi3.so b/frozen_deps/Cryptodome/Hash/_MD5.abi3.so Binary files differindex 38caf8d..b22cf36 100755 --- a/frozen_deps/Cryptodome/Hash/_MD5.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_MD5.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_MD5.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_MD5.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index dbe7d60..0000000 --- a/frozen_deps/Cryptodome/Hash/_MD5.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_RIPEMD160.abi3.so b/frozen_deps/Cryptodome/Hash/_RIPEMD160.abi3.so Binary files differindex 2c02e71..78faa00 100755 --- a/frozen_deps/Cryptodome/Hash/_RIPEMD160.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_RIPEMD160.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_RIPEMD160.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_RIPEMD160.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 6d3560a..0000000 --- a/frozen_deps/Cryptodome/Hash/_RIPEMD160.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_SHA1.abi3.so b/frozen_deps/Cryptodome/Hash/_SHA1.abi3.so Binary files differindex 2d86b06..acd08ad 100755 --- a/frozen_deps/Cryptodome/Hash/_SHA1.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_SHA1.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_SHA1.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_SHA1.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 49b0829..0000000 --- a/frozen_deps/Cryptodome/Hash/_SHA1.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_SHA224.abi3.so b/frozen_deps/Cryptodome/Hash/_SHA224.abi3.so Binary files differindex c462c9b..9cf3ef6 100755 --- a/frozen_deps/Cryptodome/Hash/_SHA224.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_SHA224.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_SHA224.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_SHA224.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index ebaa441..0000000 --- a/frozen_deps/Cryptodome/Hash/_SHA224.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_SHA256.abi3.so b/frozen_deps/Cryptodome/Hash/_SHA256.abi3.so Binary files differindex c51c162..6dffb17 100755 --- a/frozen_deps/Cryptodome/Hash/_SHA256.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_SHA256.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_SHA256.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_SHA256.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index af2b809..0000000 --- a/frozen_deps/Cryptodome/Hash/_SHA256.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_SHA384.abi3.so b/frozen_deps/Cryptodome/Hash/_SHA384.abi3.so Binary files differindex 4a4237e..7c72fd0 100755 --- a/frozen_deps/Cryptodome/Hash/_SHA384.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_SHA384.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_SHA384.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_SHA384.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index ae78f57..0000000 --- a/frozen_deps/Cryptodome/Hash/_SHA384.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_SHA512.abi3.so b/frozen_deps/Cryptodome/Hash/_SHA512.abi3.so Binary files differindex ff9a01f..058653c 100755 --- a/frozen_deps/Cryptodome/Hash/_SHA512.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_SHA512.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_SHA512.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_SHA512.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 4565097..0000000 --- a/frozen_deps/Cryptodome/Hash/_SHA512.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/__init__.py b/frozen_deps/Cryptodome/Hash/__init__.py index 4bda084..80446e4 100644 --- a/frozen_deps/Cryptodome/Hash/__init__.py +++ b/frozen_deps/Cryptodome/Hash/__init__.py @@ -19,6 +19,51 @@ # =================================================================== __all__ = ['HMAC', 'MD2', 'MD4', 'MD5', 'RIPEMD160', 'SHA1', - 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'CMAC', 'Poly1305', + 'SHA224', 'SHA256', 'SHA384', 'SHA512', + 'SHA3_224', 'SHA3_256', 'SHA3_384', 'SHA3_512', + 'CMAC', 'Poly1305', 'cSHAKE128', 'cSHAKE256', 'KMAC128', 'KMAC256', - 'TupleHash128', 'TupleHash256', 'KangarooTwelve'] + 'TupleHash128', 'TupleHash256', 'KangarooTwelve', + 'TurboSHAKE128', 'TurboSHAKE256'] + +def new(name): + """Return a new hash instance, based on its name or + on its ASN.1 Object ID""" + + name = name.upper() + if name in ("1.3.14.3.2.26", "SHA1", "SHA-1"): + from . import SHA1 + return SHA1.new() + if name in ("2.16.840.1.101.3.4.2.4", "SHA224", "SHA-224"): + from . import SHA224 + return SHA224.new() + if name in ("2.16.840.1.101.3.4.2.1", "SHA256", "SHA-256"): + from . import SHA256 + return SHA256.new() + if name in ("2.16.840.1.101.3.4.2.2", "SHA384", "SHA-384"): + from . import SHA384 + return SHA384.new() + if name in ("2.16.840.1.101.3.4.2.3", "SHA512", "SHA-512"): + from . import SHA512 + return SHA512.new() + if name in ("2.16.840.1.101.3.4.2.5", "SHA512-224", "SHA-512-224"): + from . import SHA512 + return SHA512.new(truncate='224') + if name in ("2.16.840.1.101.3.4.2.6", "SHA512-256", "SHA-512-256"): + from . import SHA512 + return SHA512.new(truncate='256') + if name in ("2.16.840.1.101.3.4.2.7", "SHA3-224", "SHA-3-224"): + from . import SHA3_224 + return SHA3_224.new() + if name in ("2.16.840.1.101.3.4.2.8", "SHA3-256", "SHA-3-256"): + from . import SHA3_256 + return SHA3_256.new() + if name in ("2.16.840.1.101.3.4.2.9", "SHA3-384", "SHA-3-384"): + from . import SHA3_384 + return SHA3_384.new() + if name in ("2.16.840.1.101.3.4.2.10", "SHA3-512", "SHA-3-512"): + from . import SHA3_512 + return SHA3_512.new() + else: + raise ValueError("Unknown hash %s" % str(name)) + diff --git a/frozen_deps/Cryptodome/Hash/__init__.pyi b/frozen_deps/Cryptodome/Hash/__init__.pyi index e69de29..b072157 100644 --- a/frozen_deps/Cryptodome/Hash/__init__.pyi +++ b/frozen_deps/Cryptodome/Hash/__init__.pyi @@ -0,0 +1,57 @@ +from typing import overload +from typing_extensions import Literal + +from Cryptodome.Hash.SHA1 import SHA1Hash +from Cryptodome.Hash.SHA224 import SHA224Hash +from Cryptodome.Hash.SHA256 import SHA256Hash +from Cryptodome.Hash.SHA384 import SHA384Hash +from Cryptodome.Hash.SHA512 import SHA512Hash +from Cryptodome.Hash.SHA3_224 import SHA3_224_Hash +from Cryptodome.Hash.SHA3_256 import SHA3_256_Hash +from Cryptodome.Hash.SHA3_384 import SHA3_384_Hash +from Cryptodome.Hash.SHA3_512 import SHA3_512_Hash + +@overload +def new(name: Literal["1.3.14.3.2.26"]) -> SHA1Hash: ... +@overload +def new(name: Literal["SHA1"]) -> SHA1Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.4"]) -> SHA224Hash: ... +@overload +def new(name: Literal["SHA224"]) -> SHA224Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.1"]) -> SHA256Hash: ... +@overload +def new(name: Literal["SHA256"]) -> SHA256Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.2"]) -> SHA384Hash: ... +@overload +def new(name: Literal["SHA384"]) -> SHA384Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.3"]) -> SHA512Hash: ... +@overload +def new(name: Literal["SHA512"]) -> SHA512Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.5"]) -> SHA512Hash: ... +@overload +def new(name: Literal["SHA512-224"]) -> SHA512Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.6"]) -> SHA512Hash: ... +@overload +def new(name: Literal["SHA512-256"]) -> SHA512Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.7"]) -> SHA3_224_Hash: ... +@overload +def new(name: Literal["SHA3-224"]) -> SHA3_224_Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.8"]) -> SHA3_256_Hash: ... +@overload +def new(name: Literal["SHA3-256"]) -> SHA3_256_Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.9"]) -> SHA3_384_Hash: ... +@overload +def new(name: Literal["SHA3-384"]) -> SHA3_384_Hash: ... +@overload +def new(name: Literal["2.16.840.1.101.3.4.2.10"]) -> SHA3_512_Hash: ... +@overload +def new(name: Literal["SHA3-512"]) -> SHA3_512_Hash: ... diff --git a/frozen_deps/Cryptodome/Hash/_ghash_clmul.abi3.so b/frozen_deps/Cryptodome/Hash/_ghash_clmul.abi3.so Binary files differindex 248bdb7..d13832c 100755 --- a/frozen_deps/Cryptodome/Hash/_ghash_clmul.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_ghash_clmul.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_ghash_clmul.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_ghash_clmul.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 74005c5..0000000 --- a/frozen_deps/Cryptodome/Hash/_ghash_clmul.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_ghash_portable.abi3.so b/frozen_deps/Cryptodome/Hash/_ghash_portable.abi3.so Binary files differindex 292f45d..555c6fc 100755 --- a/frozen_deps/Cryptodome/Hash/_ghash_portable.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_ghash_portable.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_ghash_portable.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_ghash_portable.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index dbed009..0000000 --- a/frozen_deps/Cryptodome/Hash/_ghash_portable.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_keccak.abi3.so b/frozen_deps/Cryptodome/Hash/_keccak.abi3.so Binary files differindex b251995..4e494b0 100755 --- a/frozen_deps/Cryptodome/Hash/_keccak.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_keccak.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_keccak.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_keccak.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index f4e20c7..0000000 --- a/frozen_deps/Cryptodome/Hash/_keccak.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/_poly1305.abi3.so b/frozen_deps/Cryptodome/Hash/_poly1305.abi3.so Binary files differindex e8da59e..901b8c2 100755 --- a/frozen_deps/Cryptodome/Hash/_poly1305.abi3.so +++ b/frozen_deps/Cryptodome/Hash/_poly1305.abi3.so diff --git a/frozen_deps/Cryptodome/Hash/_poly1305.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Hash/_poly1305.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 99ca9c3..0000000 --- a/frozen_deps/Cryptodome/Hash/_poly1305.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Hash/cSHAKE128.py b/frozen_deps/Cryptodome/Hash/cSHAKE128.py index 7c2f30a..064b3d6 100644 --- a/frozen_deps/Cryptodome/Hash/cSHAKE128.py +++ b/frozen_deps/Cryptodome/Hash/cSHAKE128.py @@ -28,7 +28,7 @@ # POSSIBILITY OF SUCH DAMAGE. # =================================================================== -from Cryptodome.Util.py3compat import bchr +from Cryptodome.Util.py3compat import bchr, concat_buffers from Cryptodome.Util._raw_api import (VoidPointer, SmartPointer, create_string_buffer, @@ -69,13 +69,13 @@ def _encode_str(x): if bitlen >= (1 << 2040): raise ValueError("String too large to encode in cSHAKE") - return _left_encode(bitlen) + x + return concat_buffers(_left_encode(bitlen), x) def _bytepad(x, length): """Zero pad byte string as defined in NIST SP 800-185""" - to_pad = _left_encode(length) + x + to_pad = concat_buffers(_left_encode(length), x) # Note: this implementation works with byte aligned strings, # hence no additional bit padding is needed at this point. diff --git a/frozen_deps/Cryptodome/IO/PKCS8.py b/frozen_deps/Cryptodome/IO/PKCS8.py index d02aed9..3041545 100644 --- a/frozen_deps/Cryptodome/IO/PKCS8.py +++ b/frozen_deps/Cryptodome/IO/PKCS8.py @@ -53,44 +53,29 @@ def wrap(private_key, key_oid, passphrase=None, protection=None, Args: - private_key (byte string): + private_key (bytes): The private key encoded in binary form. The actual encoding is algorithm specific. In most cases, it is DER. key_oid (string): The object identifier (OID) of the private key to wrap. - It is a dotted string, like ``1.2.840.113549.1.1.1`` (for RSA keys). + It is a dotted string, like ``'1.2.840.113549.1.1.1'`` (for RSA keys) + or ``'1.2.840.10045.2.1'`` (for ECC keys). - passphrase (bytes string or string): + Keyword Args: + + passphrase (bytes or string): The secret passphrase from which the wrapping key is derived. Set it only if encryption is required. protection (string): The identifier of the algorithm to use for securely wrapping the key. - The default value is ``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``. + Refer to :ref:`the encryption parameters<enc_params>` . + The default value is ``'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'``. prot_params (dictionary): - Parameters for the protection algorithm. - - +------------------+-----------------------------------------------+ - | Key | Description | - +==================+===============================================+ - | iteration_count | The KDF algorithm is repeated several times to| - | | slow down brute force attacks on passwords | - | | (called *N* or CPU/memory cost in scrypt). | - | | The default value for PBKDF2 is 1000. | - | | The default value for scrypt is 16384. | - +------------------+-----------------------------------------------+ - | salt_size | Salt is used to thwart dictionary and rainbow | - | | attacks on passwords. The default value is 8 | - | | bytes. | - +------------------+-----------------------------------------------+ - | block_size | *(scrypt only)* Memory-cost (r). The default | - | | value is 8. | - +------------------+-----------------------------------------------+ - | parallelization | *(scrypt only)* CPU-cost (p). The default | - | | value is 1. | - +------------------+-----------------------------------------------+ + Parameters for the key derivation function (KDF). + Refer to :ref:`the encryption parameters<enc_params>` . key_params (DER object or None): The ``parameters`` field to use in the ``AlgorithmIdentifier`` @@ -103,8 +88,8 @@ def wrap(private_key, key_oid, passphrase=None, protection=None, If not specified, a new RNG will be instantiated from :mod:`Cryptodome.Random`. - Return: - The PKCS#8-wrapped private key (possibly encrypted), as a byte string. + Returns: + bytes: The PKCS#8-wrapped private key (possibly encrypted). """ # @@ -145,8 +130,10 @@ def unwrap(p8_private_key, passphrase=None): """Unwrap a private key from a PKCS#8 blob (clear or encrypted). Args: - p8_private_key (byte string): - The private key wrapped into a PKCS#8 blob, DER encoded. + p8_private_key (bytes): + The private key wrapped into a PKCS#8 container, DER encoded. + + Keyword Args: passphrase (byte string or string): The passphrase to use to decrypt the blob (if it is encrypted). @@ -154,8 +141,8 @@ def unwrap(p8_private_key, passphrase=None): A tuple containing #. the algorithm identifier of the wrapped key (OID, dotted string) - #. the private key (byte string, DER encoded) - #. the associated parameters (byte string, DER encoded) or ``None`` + #. the private key (bytes, DER encoded) + #. the associated parameters (bytes, DER encoded) or ``None`` Raises: ValueError : if decoding fails diff --git a/frozen_deps/Cryptodome/IO/PKCS8.pyi b/frozen_deps/Cryptodome/IO/PKCS8.pyi index be716af..c8d0c10 100644 --- a/frozen_deps/Cryptodome/IO/PKCS8.pyi +++ b/frozen_deps/Cryptodome/IO/PKCS8.pyi @@ -1,14 +1,17 @@ -from typing import Dict, Tuple, Optional, Union, Callable +from typing import Tuple, Optional, Union, Callable +from typing_extensions import NotRequired from Cryptodome.Util.asn1 import DerObject +from Cryptodome.IO._PBES import ProtParams + def wrap(private_key: bytes, key_oid: str, - passphrase: Union[bytes, str] = ..., - protection: str = ..., - prot_params: Dict = ..., - key_params: Optional[DerObject] = ..., - randfunc: Optional[Callable[[int],str]] = ...) -> bytes: ... + passphrase: Union[bytes, str] = ..., + protection: str = ..., + prot_params: Optional[ProtParams] = ..., + key_params: Optional[DerObject] = ..., + randfunc: Optional[Callable[[int], str]] = ...) -> bytes: ... def unwrap(p8_private_key: bytes, passphrase: Optional[Union[bytes, str]] = ...) -> Tuple[str, bytes, Optional[bytes]]: ... diff --git a/frozen_deps/Cryptodome/IO/_PBES.py b/frozen_deps/Cryptodome/IO/_PBES.py index 9ee5385..75d8cde 100644 --- a/frozen_deps/Cryptodome/IO/_PBES.py +++ b/frozen_deps/Cryptodome/IO/_PBES.py @@ -31,15 +31,17 @@ # POSSIBILITY OF SUCH DAMAGE. # =================================================================== +import re + +from Cryptodome import Hash from Cryptodome import Random from Cryptodome.Util.asn1 import ( DerSequence, DerOctetString, DerObjectId, DerInteger, ) +from Cryptodome.Cipher import AES from Cryptodome.Util.Padding import pad, unpad -from Cryptodome.Hash import MD5, SHA1, SHA224, SHA256, SHA384, SHA512 -from Cryptodome.Cipher import DES, ARC2, DES3, AES from Cryptodome.Protocol.KDF import PBKDF1, PBKDF2, scrypt _OID_PBE_WITH_MD5_AND_DES_CBC = "1.2.840.113549.1.5.3" @@ -53,16 +55,14 @@ _OID_PBKDF2 = "1.2.840.113549.1.5.12" _OID_SCRYPT = "1.3.6.1.4.1.11591.4.11" _OID_HMAC_SHA1 = "1.2.840.113549.2.7" -_OID_HMAC_SHA224 = "1.2.840.113549.2.8" -_OID_HMAC_SHA256 = "1.2.840.113549.2.9" -_OID_HMAC_SHA384 = "1.2.840.113549.2.10" -_OID_HMAC_SHA512 = "1.2.840.113549.2.11" _OID_DES_EDE3_CBC = "1.2.840.113549.3.7" _OID_AES128_CBC = "2.16.840.1.101.3.4.1.2" _OID_AES192_CBC = "2.16.840.1.101.3.4.1.22" _OID_AES256_CBC = "2.16.840.1.101.3.4.1.42" - +_OID_AES128_GCM = "2.16.840.1.101.3.4.1.6" +_OID_AES192_GCM = "2.16.840.1.101.3.4.1.26" +_OID_AES256_GCM = "2.16.840.1.101.3.4.1.46" class PbesError(ValueError): pass @@ -103,6 +103,16 @@ class PbesError(ValueError): # prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 # } # +# PBKDF2-PRFs ALGORITHM-IDENTIFIER ::= { +# {NULL IDENTIFIED BY id-hmacWithSHA1}, +# {NULL IDENTIFIED BY id-hmacWithSHA224}, +# {NULL IDENTIFIED BY id-hmacWithSHA256}, +# {NULL IDENTIFIED BY id-hmacWithSHA384}, +# {NULL IDENTIFIED BY id-hmacWithSHA512}, +# {NULL IDENTIFIED BY id-hmacWithSHA512-224}, +# {NULL IDENTIFIED BY id-hmacWithSHA512-256}, +# ... +# } # scrypt-params ::= SEQUENCE { # salt OCTET STRING, # costParameter INTEGER (1..MAX), @@ -111,6 +121,7 @@ class PbesError(ValueError): # keyLength INTEGER (1..MAX) OPTIONAL # } + class PBES1(object): """Deprecated encryption scheme with password-based key derivation (originally defined in PKCS#5 v1.5, but still present in `v2.0`__). @@ -141,21 +152,29 @@ class PBES1(object): cipher_params = {} if pbe_oid == _OID_PBE_WITH_MD5_AND_DES_CBC: # PBE_MD5_DES_CBC + from Cryptodome.Hash import MD5 + from Cryptodome.Cipher import DES hashmod = MD5 - ciphermod = DES + module = DES elif pbe_oid == _OID_PBE_WITH_MD5_AND_RC2_CBC: # PBE_MD5_RC2_CBC + from Cryptodome.Hash import MD5 + from Cryptodome.Cipher import ARC2 hashmod = MD5 - ciphermod = ARC2 + module = ARC2 cipher_params['effective_keylen'] = 64 elif pbe_oid == _OID_PBE_WITH_SHA1_AND_DES_CBC: # PBE_SHA1_DES_CBC + from Cryptodome.Hash import SHA1 + from Cryptodome.Cipher import DES hashmod = SHA1 - ciphermod = DES + module = DES elif pbe_oid == _OID_PBE_WITH_SHA1_AND_RC2_CBC: # PBE_SHA1_RC2_CBC + from Cryptodome.Hash import SHA1 + from Cryptodome.Cipher import ARC2 hashmod = SHA1 - ciphermod = ARC2 + module = ARC2 cipher_params['effective_keylen'] = 64 else: raise PbesError("Unknown OID for PBES1") @@ -167,7 +186,7 @@ class PBES1(object): key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod) key, iv = key_iv[:8], key_iv[8:] - cipher = ciphermod.new(key, ciphermod.MODE_CBC, iv, **cipher_params) + cipher = module.new(key, module.MODE_CBC, iv, **cipher_params) pt = cipher.decrypt(encrypted_data) return unpad(pt, cipher.block_size) @@ -231,49 +250,103 @@ class PBES2(object): if randfunc is None: randfunc = Random.new().read - if protection == 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC': + pattern = re.compile(r'^(PBKDF2WithHMAC-([0-9A-Z-]+)|scrypt)And([0-9A-Z-]+)$') + res = pattern.match(protection) + if res is None: + raise ValueError("Unknown protection %s" % protection) + + if protection.startswith("PBKDF"): + pbkdf = "pbkdf2" + pbkdf2_hmac_algo = res.group(2) + enc_algo = res.group(3) + else: + pbkdf = "scrypt" + enc_algo = res.group(3) + + aead = False + if enc_algo == 'DES-EDE3-CBC': + from Cryptodome.Cipher import DES3 key_size = 24 module = DES3 cipher_mode = DES3.MODE_CBC enc_oid = _OID_DES_EDE3_CBC - elif protection in ('PBKDF2WithHMAC-SHA1AndAES128-CBC', - 'scryptAndAES128-CBC'): + enc_param = {'iv': randfunc(8)} + elif enc_algo == 'AES128-CBC': key_size = 16 module = AES cipher_mode = AES.MODE_CBC enc_oid = _OID_AES128_CBC - elif protection in ('PBKDF2WithHMAC-SHA1AndAES192-CBC', - 'scryptAndAES192-CBC'): + enc_param = {'iv': randfunc(16)} + elif enc_algo == 'AES192-CBC': key_size = 24 module = AES cipher_mode = AES.MODE_CBC enc_oid = _OID_AES192_CBC - elif protection in ('PBKDF2WithHMAC-SHA1AndAES256-CBC', - 'scryptAndAES256-CBC'): + enc_param = {'iv': randfunc(16)} + elif enc_algo == 'AES256-CBC': key_size = 32 module = AES cipher_mode = AES.MODE_CBC enc_oid = _OID_AES256_CBC + enc_param = {'iv': randfunc(16)} + elif enc_algo == 'AES128-GCM': + key_size = 16 + module = AES + cipher_mode = AES.MODE_GCM + enc_oid = _OID_AES128_GCM + enc_param = {'nonce': randfunc(12)} + aead = True + elif enc_algo == 'AES192-GCM': + key_size = 24 + module = AES + cipher_mode = AES.MODE_GCM + enc_oid = _OID_AES192_GCM + enc_param = {'nonce': randfunc(12)} + aead = True + elif enc_algo == 'AES256-GCM': + key_size = 32 + module = AES + cipher_mode = AES.MODE_GCM + enc_oid = _OID_AES256_GCM + enc_param = {'nonce': randfunc(12)} + aead = True else: - raise ValueError("Unknown PBES2 mode") + raise ValueError("Unknown encryption mode '%s'" % enc_algo) - # Get random data - iv = randfunc(module.block_size) + iv_nonce = list(enc_param.values())[0] salt = randfunc(prot_params.get("salt_size", 8)) # Derive key from password - if protection.startswith('PBKDF2'): + if pbkdf == 'pbkdf2': + count = prot_params.get("iteration_count", 1000) - key = PBKDF2(passphrase, salt, key_size, count) + digestmod = Hash.new(pbkdf2_hmac_algo) + + key = PBKDF2(passphrase, + salt, + key_size, + count, + hmac_hash_module=digestmod) + + pbkdf2_params = DerSequence([ + DerOctetString(salt), + DerInteger(count) + ]) + + if pbkdf2_hmac_algo != 'SHA1': + try: + hmac_oid = Hash.HMAC.new(b'', digestmod=digestmod).oid + except KeyError: + raise ValueError("No OID for HMAC hash algorithm") + pbkdf2_params.append(DerSequence([DerObjectId(hmac_oid)])) + kdf_info = DerSequence([ DerObjectId(_OID_PBKDF2), # PBKDF2 - DerSequence([ - DerOctetString(salt), - DerInteger(count) - ]) + pbkdf2_params ]) - else: - # It must be scrypt + + elif pbkdf == 'scrypt': + count = prot_params.get("iteration_count", 16384) scrypt_r = prot_params.get('block_size', 8) scrypt_p = prot_params.get('parallelization', 1) @@ -289,12 +362,19 @@ class PBES2(object): ]) ]) + else: + raise ValueError("Unknown KDF " + res.group(1)) + # Create cipher and use it - cipher = module.new(key, cipher_mode, iv) - encrypted_data = cipher.encrypt(pad(data, cipher.block_size)) + cipher = module.new(key, cipher_mode, **enc_param) + if aead: + ct, tag = cipher.encrypt_and_digest(data) + encrypted_data = ct + tag + else: + encrypted_data = cipher.encrypt(pad(data, cipher.block_size)) enc_info = DerSequence([ DerObjectId(enc_oid), - DerOctetString(iv) + DerOctetString(iv_nonce) ]) # Result @@ -336,7 +416,7 @@ class PBES2(object): pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2) - ### Key Derivation Function selection + # Key Derivation Function selection kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2) kdf_oid = DerObjectId().decode(kdf_info[0]).value @@ -354,14 +434,16 @@ class PBES2(object): if left > 0: try: + # Check if it's an INTEGER kdf_key_length = pbkdf2_params[idx] - 0 left -= 1 idx += 1 except TypeError: + # keyLength is not present pass # Default is HMAC-SHA1 - pbkdf2_prf_oid = "1.2.840.113549.2.7" + pbkdf2_prf_oid = _OID_HMAC_SHA1 if left > 0: pbkdf2_prf_algo_id = DerSequence().decode(pbkdf2_params[idx]) pbkdf2_prf_oid = DerObjectId().decode(pbkdf2_prf_algo_id[0]).value @@ -379,57 +461,86 @@ class PBES2(object): else: raise PbesError("Unsupported PBES2 KDF") - ### Cipher selection + # Cipher selection enc_info = DerSequence().decode(pbes2_params[1]) enc_oid = DerObjectId().decode(enc_info[0]).value + aead = False if enc_oid == _OID_DES_EDE3_CBC: # DES_EDE3_CBC - ciphermod = DES3 + from Cryptodome.Cipher import DES3 + module = DES3 + cipher_mode = DES3.MODE_CBC key_size = 24 + cipher_param = 'iv' elif enc_oid == _OID_AES128_CBC: - # AES128_CBC - ciphermod = AES + module = AES + cipher_mode = AES.MODE_CBC key_size = 16 + cipher_param = 'iv' elif enc_oid == _OID_AES192_CBC: - # AES192_CBC - ciphermod = AES + module = AES + cipher_mode = AES.MODE_CBC key_size = 24 + cipher_param = 'iv' elif enc_oid == _OID_AES256_CBC: - # AES256_CBC - ciphermod = AES + module = AES + cipher_mode = AES.MODE_CBC + key_size = 32 + cipher_param = 'iv' + elif enc_oid == _OID_AES128_GCM: + module = AES + cipher_mode = AES.MODE_GCM + key_size = 16 + cipher_param = 'nonce' + aead = True + elif enc_oid == _OID_AES192_GCM: + module = AES + cipher_mode = AES.MODE_GCM + key_size = 24 + cipher_param = 'nonce' + aead = True + elif enc_oid == _OID_AES256_GCM: + module = AES + cipher_mode = AES.MODE_GCM key_size = 32 + cipher_param = 'nonce' + aead = True else: - raise PbesError("Unsupported PBES2 cipher") + raise PbesError("Unsupported PBES2 cipher " + enc_algo) if kdf_key_length and kdf_key_length != key_size: raise PbesError("Mismatch between PBES2 KDF parameters" " and selected cipher") - IV = DerOctetString().decode(enc_info[1]).payload + iv_nonce = DerOctetString().decode(enc_info[1]).payload # Create cipher if kdf_oid == _OID_PBKDF2: - if pbkdf2_prf_oid == _OID_HMAC_SHA1: - hmac_hash_module = SHA1 - elif pbkdf2_prf_oid == _OID_HMAC_SHA224: - hmac_hash_module = SHA224 - elif pbkdf2_prf_oid == _OID_HMAC_SHA256: - hmac_hash_module = SHA256 - elif pbkdf2_prf_oid == _OID_HMAC_SHA384: - hmac_hash_module = SHA384 - elif pbkdf2_prf_oid == _OID_HMAC_SHA512: - hmac_hash_module = SHA512 - else: + + try: + hmac_hash_module_oid = Hash.HMAC._hmac2hash_oid[pbkdf2_prf_oid] + except KeyError: raise PbesError("Unsupported HMAC %s" % pbkdf2_prf_oid) + hmac_hash_module = Hash.new(hmac_hash_module_oid) key = PBKDF2(passphrase, salt, key_size, iteration_count, hmac_hash_module=hmac_hash_module) else: key = scrypt(passphrase, salt, key_size, iteration_count, scrypt_r, scrypt_p) - cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV) + cipher = module.new(key, cipher_mode, **{cipher_param:iv_nonce}) # Decrypt data - pt = cipher.decrypt(encrypted_data) - return unpad(pt, cipher.block_size) + if len(encrypted_data) < cipher.block_size: + raise ValueError("Too little data to decrypt") + + if aead: + tag_len = cipher.block_size + pt = cipher.decrypt_and_verify(encrypted_data[:-tag_len], + encrypted_data[-tag_len:]) + else: + pt_padded = cipher.decrypt(encrypted_data) + pt = unpad(pt_padded, cipher.block_size) + + return pt diff --git a/frozen_deps/Cryptodome/IO/_PBES.pyi b/frozen_deps/Cryptodome/IO/_PBES.pyi index a8a34ce..0673364 100644 --- a/frozen_deps/Cryptodome/IO/_PBES.pyi +++ b/frozen_deps/Cryptodome/IO/_PBES.pyi @@ -1,4 +1,5 @@ -from typing import Dict, Optional, Callable +from typing import Optional, Callable, TypedDict +from typing_extensions import NotRequired class PbesError(ValueError): ... @@ -7,13 +8,19 @@ class PBES1(object): @staticmethod def decrypt(data: bytes, passphrase: bytes) -> bytes: ... +class ProtParams(TypedDict): + iteration_count: NotRequired[int] + salt_size: NotRequired[int] + block_size: NotRequired[int] + parallelization: NotRequired[int] + class PBES2(object): @staticmethod def encrypt(data: bytes, passphrase: bytes, - protection: str, - prot_params: Optional[Dict] = ..., - randfunc: Optional[Callable[[int],bytes]] = ...) -> bytes: ... + protection: str, + prot_params: Optional[ProtParams] = ..., + randfunc: Optional[Callable[[int],bytes]] = ...) -> bytes: ... @staticmethod def decrypt(data:bytes, passphrase: bytes) -> bytes: ... diff --git a/frozen_deps/Cryptodome/Math/Numbers.pyi b/frozen_deps/Cryptodome/Math/Numbers.pyi index 2285a3b..b0206ca 100644 --- a/frozen_deps/Cryptodome/Math/Numbers.pyi +++ b/frozen_deps/Cryptodome/Math/Numbers.pyi @@ -1,4 +1,2 @@ -from Cryptodome.Math._IntegerBase import IntegerBase - -class Integer(IntegerBase): - pass +from Cryptodome.Math._IntegerBase import IntegerBase as Integer +__all__ = ['Integer'] diff --git a/frozen_deps/Cryptodome/Math/_IntegerBase.py b/frozen_deps/Cryptodome/Math/_IntegerBase.py index 7d78c4b..03dd591 100644 --- a/frozen_deps/Cryptodome/Math/_IntegerBase.py +++ b/frozen_deps/Cryptodome/Math/_IntegerBase.py @@ -390,3 +390,23 @@ class IntegerBase(ABC): ) return norm_candidate + min_inclusive + @staticmethod + @abc.abstractmethod + def _mult_modulo_bytes(term1, term2, modulus): + """Multiply two integers, take the modulo, and encode as big endian. + This specialized method is used for RSA decryption. + + Args: + term1 : integer + The first term of the multiplication, non-negative. + term2 : integer + The second term of the multiplication, non-negative. + modulus: integer + The modulus, a positive odd number. + :Returns: + A byte string, with the result of the modular multiplication + encoded in big endian mode. + It is as long as the modulus would be, with zero padding + on the left if needed. + """ + pass diff --git a/frozen_deps/Cryptodome/Math/_IntegerBase.pyi b/frozen_deps/Cryptodome/Math/_IntegerBase.pyi index 362c512..ea23532 100644 --- a/frozen_deps/Cryptodome/Math/_IntegerBase.pyi +++ b/frozen_deps/Cryptodome/Math/_IntegerBase.pyi @@ -4,6 +4,8 @@ RandFunc = Callable[[int],int] class IntegerBase: + def __init__(self, value: Union[IntegerBase, int]): ... + def __int__(self) -> int: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... @@ -58,4 +60,8 @@ class IntegerBase: def random(cls, **kwargs: Union[int,RandFunc]) -> IntegerBase : ... @classmethod def random_range(cls, **kwargs: Union[int,RandFunc]) -> IntegerBase : ... + @staticmethod + def _mult_modulo_bytes(term1: Union[IntegerBase, int], + term2: Union[IntegerBase, int], + modulus: Union[IntegerBase, int]) -> bytes: ... diff --git a/frozen_deps/Cryptodome/Math/_IntegerCustom.py b/frozen_deps/Cryptodome/Math/_IntegerCustom.py index 0e23152..20eadca 100644 --- a/frozen_deps/Cryptodome/Math/_IntegerCustom.py +++ b/frozen_deps/Cryptodome/Math/_IntegerCustom.py @@ -41,12 +41,18 @@ from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, from Cryptodome.Random.random import getrandbits c_defs = """ -int monty_pow(const uint8_t *base, - const uint8_t *exp, - const uint8_t *modulus, - uint8_t *out, - size_t len, - uint64_t seed); +int monty_pow(uint8_t *out, + const uint8_t *base, + const uint8_t *exp, + const uint8_t *modulus, + size_t len, + uint64_t seed); + +int monty_multiply(uint8_t *out, + const uint8_t *term1, + const uint8_t *term2, + const uint8_t *modulus, + size_t len); """ @@ -116,3 +122,41 @@ class IntegerCustom(IntegerNative): result = bytes_to_long(get_raw_buffer(out)) self._value = result return self + + @staticmethod + def _mult_modulo_bytes(term1, term2, modulus): + + # With modular reduction + mod_value = int(modulus) + if mod_value < 0: + raise ValueError("Modulus must be positive") + if mod_value == 0: + raise ZeroDivisionError("Modulus cannot be zero") + + # C extension only works with odd moduli + if (mod_value & 1) == 0: + raise ValueError("Odd modulus is required") + + # C extension only works with non-negative terms smaller than modulus + if term1 >= mod_value or term1 < 0: + term1 %= mod_value + if term2 >= mod_value or term2 < 0: + term2 %= mod_value + + modulus_b = long_to_bytes(mod_value) + numbers_len = len(modulus_b) + term1_b = long_to_bytes(term1, numbers_len) + term2_b = long_to_bytes(term2, numbers_len) + out = create_string_buffer(numbers_len) + + error = _raw_montgomery.monty_multiply( + out, + term1_b, + term2_b, + modulus_b, + c_size_t(numbers_len) + ) + if error: + raise ValueError("monty_multiply failed with error: %d" % error) + + return get_raw_buffer(out) diff --git a/frozen_deps/Cryptodome/Math/_IntegerGMP.py b/frozen_deps/Cryptodome/Math/_IntegerGMP.py index 3ab7c59..f58f044 100644 --- a/frozen_deps/Cryptodome/Math/_IntegerGMP.py +++ b/frozen_deps/Cryptodome/Math/_IntegerGMP.py @@ -749,6 +749,26 @@ class IntegerGMP(IntegerBase): raise ValueError("n must be positive odd for the Jacobi symbol") return _gmp.mpz_jacobi(a._mpz_p, n._mpz_p) + @staticmethod + def _mult_modulo_bytes(term1, term2, modulus): + if not isinstance(term1, IntegerGMP): + term1 = IntegerGMP(term1) + if not isinstance(term2, IntegerGMP): + term2 = IntegerGMP(term2) + if not isinstance(modulus, IntegerGMP): + modulus = IntegerGMP(modulus) + + if modulus < 0: + raise ValueError("Modulus must be positive") + if modulus == 0: + raise ZeroDivisionError("Modulus cannot be zero") + if (modulus & 1) == 0: + raise ValueError("Odd modulus is required") + + numbers_len = len(modulus.to_bytes()) + result = ((term1 * term2) % modulus).to_bytes(numbers_len) + return result + # Clean-up def __del__(self): diff --git a/frozen_deps/Cryptodome/Math/_IntegerNative.py b/frozen_deps/Cryptodome/Math/_IntegerNative.py index 9b857ea..5f768e2 100644 --- a/frozen_deps/Cryptodome/Math/_IntegerNative.py +++ b/frozen_deps/Cryptodome/Math/_IntegerNative.py @@ -30,7 +30,7 @@ from ._IntegerBase import IntegerBase -from Cryptodome.Util.number import long_to_bytes, bytes_to_long +from Cryptodome.Util.number import long_to_bytes, bytes_to_long, inverse, GCD class IntegerNative(IntegerBase): @@ -280,13 +280,7 @@ class IntegerNative(IntegerBase): if self._value == 0: return 1 - bit_size = 0 - tmp = self._value - while tmp: - tmp >>= 1 - bit_size += 1 - - return bit_size + return self._value.bit_length() def size_in_bytes(self): return (self.size_in_bits() - 1) // 8 + 1 @@ -318,22 +312,7 @@ class IntegerNative(IntegerBase): self._value = int(source) def inplace_inverse(self, modulus): - modulus = int(modulus) - if modulus == 0: - raise ZeroDivisionError("Modulus cannot be zero") - if modulus < 0: - raise ValueError("Modulus cannot be negative") - r_p, r_n = self._value, modulus - s_p, s_n = 1, 0 - while r_n > 0: - q = r_p // r_n - r_p, r_n = r_n, r_p - q * r_n - s_p, s_n = s_n, s_p - q * s_n - if r_p != 1: - raise ValueError("No inverse value can be computed" + str(r_p)) - while s_p < 0: - s_p += modulus - self._value = s_p + self._value = inverse(self._value, int(modulus)) return self def inverse(self, modulus): @@ -342,11 +321,7 @@ class IntegerNative(IntegerBase): return result def gcd(self, term): - r_p, r_n = abs(self._value), abs(int(term)) - while r_n > 0: - q = r_p // r_n - r_p, r_n = r_n, r_p - q * r_n - return self.__class__(r_p) + return self.__class__(GCD(abs(self._value), abs(int(term)))) def lcm(self, term): term = int(term) @@ -393,3 +368,15 @@ class IntegerNative(IntegerBase): n1 = n % a1 # Step 8 return s * IntegerNative.jacobi_symbol(n1, a1) + + @staticmethod + def _mult_modulo_bytes(term1, term2, modulus): + if modulus < 0: + raise ValueError("Modulus must be positive") + if modulus == 0: + raise ZeroDivisionError("Modulus cannot be zero") + if (modulus & 1) == 0: + raise ValueError("Odd modulus is required") + + number_len = len(long_to_bytes(modulus)) + return long_to_bytes((term1 * term2) % modulus, number_len) diff --git a/frozen_deps/Cryptodome/Math/_modexp.abi3.so b/frozen_deps/Cryptodome/Math/_modexp.abi3.so Binary files differindex 3e0e3b2..d11de72 100755 --- a/frozen_deps/Cryptodome/Math/_modexp.abi3.so +++ b/frozen_deps/Cryptodome/Math/_modexp.abi3.so diff --git a/frozen_deps/Cryptodome/Math/_modexp.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Math/_modexp.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index bb3667e..0000000 --- a/frozen_deps/Cryptodome/Math/_modexp.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Protocol/DH.py b/frozen_deps/Cryptodome/Protocol/DH.py new file mode 100644 index 0000000..bb174f0 --- /dev/null +++ b/frozen_deps/Cryptodome/Protocol/DH.py @@ -0,0 +1,101 @@ +from Cryptodome.Util.number import long_to_bytes +from Cryptodome.PublicKey.ECC import EccKey + + +def _compute_ecdh(key_priv, key_pub): + # See Section 5.7.1.2 in NIST SP 800-56Ar3 + pointP = key_pub.pointQ * key_priv.d + if pointP.is_point_at_infinity(): + raise ValueError("Invalid ECDH point") + z = long_to_bytes(pointP.x, pointP.size_in_bytes()) + return z + + +def key_agreement(**kwargs): + """Perform a Diffie-Hellman key agreement. + + Keywords: + kdf (callable): + A key derivation function that accepts ``bytes`` as input and returns + ``bytes``. + static_priv (EccKey): + The local static private key. Optional. + static_pub (EccKey): + The static public key that belongs to the peer. Optional. + eph_priv (EccKey): + The local ephemeral private key, generated for this session. Optional. + eph_pub (EccKey): + The ephemeral public key, received from the peer for this session. Optional. + + At least two keys must be passed, of which one is a private key and one + a public key. + + Returns (bytes): + The derived secret key material. + """ + + static_priv = kwargs.get('static_priv', None) + static_pub = kwargs.get('static_pub', None) + eph_priv = kwargs.get('eph_priv', None) + eph_pub = kwargs.get('eph_pub', None) + kdf = kwargs.get('kdf', None) + + if kdf is None: + raise ValueError("'kdf' is mandatory") + + count_priv = 0 + count_pub = 0 + curve = None + + def check_curve(curve, key, name, private): + if not isinstance(key, EccKey): + raise TypeError("'%s' must be an ECC key" % name) + if private and not key.has_private(): + raise TypeError("'%s' must be a private ECC key" % name) + if curve is None: + curve = key.curve + elif curve != key.curve: + raise TypeError("'%s' is defined on an incompatible curve" % name) + return curve + + if static_priv is not None: + curve = check_curve(curve, static_priv, 'static_priv', True) + count_priv += 1 + + if static_pub is not None: + curve = check_curve(curve, static_pub, 'static_pub', False) + count_pub += 1 + + if eph_priv is not None: + curve = check_curve(curve, eph_priv, 'eph_priv', True) + count_priv += 1 + + if eph_pub is not None: + curve = check_curve(curve, eph_pub, 'eph_pub', False) + count_pub += 1 + + if (count_priv + count_pub) < 2 or count_priv == 0 or count_pub == 0: + raise ValueError("Too few keys for the ECDH key agreement") + + Zs = b'' + Ze = b'' + + if static_priv and static_pub: + # C(*, 2s) + Zs = _compute_ecdh(static_priv, static_pub) + + if eph_priv and eph_pub: + # C(2e, 0s) or C(2e, 2s) + if bool(static_priv) != bool(static_pub): + raise ValueError("DH mode C(2e, 1s) is not supported") + Ze = _compute_ecdh(eph_priv, eph_pub) + elif eph_priv and static_pub: + # C(1e, 2s) or C(1e, 1s) + Ze = _compute_ecdh(eph_priv, static_pub) + elif eph_pub and static_priv: + # C(1e, 2s) or C(1e, 1s) + Ze = _compute_ecdh(static_priv, eph_pub) + + Z = Ze + Zs + + return kdf(Z) diff --git a/frozen_deps/Cryptodome/Protocol/DH.pyi b/frozen_deps/Cryptodome/Protocol/DH.pyi new file mode 100644 index 0000000..b1da888 --- /dev/null +++ b/frozen_deps/Cryptodome/Protocol/DH.pyi @@ -0,0 +1,15 @@ +from typing import TypedDict, Callable, TypeVar, Generic +from typing_extensions import Unpack, NotRequired + +from Cryptodome.PublicKey.ECC import EccKey + +T = TypeVar('T') + +class RequestParams(TypedDict, Generic[T]): + kdf: Callable[[bytes|bytearray|memoryview], T] + static_priv: NotRequired[EccKey] + static_pub: NotRequired[EccKey] + eph_priv: NotRequired[EccKey] + eph_pub: NotRequired[EccKey] + +def key_agreement(**kwargs: Unpack[RequestParams[T]]) -> T: ... diff --git a/frozen_deps/Cryptodome/Protocol/KDF.py b/frozen_deps/Cryptodome/Protocol/KDF.py index 4baa276..b6d747e 100644 --- a/frozen_deps/Cryptodome/Protocol/KDF.py +++ b/frozen_deps/Cryptodome/Protocol/KDF.py @@ -27,7 +27,7 @@ import struct from functools import reduce from Cryptodome.Util.py3compat import (tobytes, bord, _copy_bytes, iter_range, - tostr, bchr, bstr) + tostr, bchr, bstr) from Cryptodome.Hash import SHA1, SHA256, HMAC, CMAC, BLAKE2s from Cryptodome.Util.strxor import strxor @@ -103,10 +103,16 @@ def PBKDF2(password, salt, dkLen=16, count=1000, prf=None, hmac_hash_module=None Args: password (string or byte string): The secret password to generate the key from. + + Strings will be encoded as ISO 8859-1 (also known as Latin-1), + which does not allow any characters with codepoints > 255. salt (string or byte string): A (byte) string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. It is recommended to use at least 16 bytes. + + Strings will be encoded as ISO 8859-1 (also known as Latin-1), + which does not allow any characters with codepoints > 255. dkLen (integer): The cumulative length of the keys to produce. @@ -201,10 +207,10 @@ class _S2V(object): self._key = _copy_bytes(None, None, key) self._ciphermod = ciphermod self._last_string = self._cache = b'\x00' * ciphermod.block_size - + # Max number of update() call we can process self._n_updates = ciphermod.block_size * 8 - 1 - + if cipher_params is None: self._cipher_params = {} else: @@ -281,13 +287,13 @@ def HKDF(master, key_len, salt, hashmod, num_keys=1, context=None): The unguessable value used by the KDF to generate the other keys. It must be a high-entropy secret, though not necessarily uniform. It must not be a password. + key_len (integer): + The length in bytes of every derived key. salt (byte string): A non-secret, reusable value that strengthens the randomness extraction step. Ideally, it is as long as the digest size of the chosen hash. If empty, a string of zeroes in used. - key_len (integer): - The length in bytes of every derived key. hashmod (module): A cryptographic hash algorithm from :mod:`Cryptodome.Hash`. :mod:`Cryptodome.Hash.SHA512` is a good choice. @@ -346,7 +352,7 @@ def scrypt(password, salt, key_len, N, r, p, num_keys=1): but it should be randomly chosen for each derivation. It is recommended to be at least 16 bytes long. key_len (integer): - The length in bytes of every derived key. + The length in bytes of each derived key. N (integer): CPU/Memory cost parameter. It must be a power of 2 and less than :math:`2^{32}`. @@ -572,3 +578,65 @@ def bcrypt_check(password, bcrypt_hash): mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash2).digest() if mac1 != mac2: raise ValueError("Incorrect bcrypt hash") + + +def SP800_108_Counter(master, key_len, prf, num_keys=None, label=b'', context=b''): + """Derive one or more keys from a master secret using + a pseudorandom function in Counter Mode, as specified in + `NIST SP 800-108r1 <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-108r1.pdf>`_. + + Args: + master (byte string): + The secret value used by the KDF to derive the other keys. + It must not be a password. + The length on the secret must be consistent with the input expected by + the :data:`prf` function. + key_len (integer): + The length in bytes of each derived key. + prf (function): + A pseudorandom function that takes two byte strings as parameters: + the secret and an input. It returns another byte string. + num_keys (integer): + The number of keys to derive. Every key is :data:`key_len` bytes long. + By default, only 1 key is derived. + label (byte string): + Optional description of the purpose of the derived keys. + It must not contain zero bytes. + context (byte string): + Optional information pertaining to + the protocol that uses the keys, such as the identity of the + participants, nonces, session IDs, etc. + It must not contain zero bytes. + + Return: + - a byte string (if ``num_keys`` is not specified), or + - a tuple of byte strings (if ``num_key`` is specified). + """ + + if num_keys is None: + num_keys = 1 + + if label.find(b'\x00') != -1: + raise ValueError("Null byte found in label") + + if context.find(b'\x00') != -1: + raise ValueError("Null byte found in context") + + key_len_enc = long_to_bytes(key_len * num_keys * 8, 4) + output_len = key_len * num_keys + + i = 1 + dk = b"" + while len(dk) < output_len: + info = long_to_bytes(i, 4) + label + b'\x00' + context + key_len_enc + dk += prf(master, info) + i += 1 + if i > 0xFFFFFFFF: + raise ValueError("Overflow in SP800 108 counter") + + if num_keys == 1: + return dk[:key_len] + else: + kol = [dk[idx:idx + key_len] + for idx in iter_range(0, output_len, key_len)] + return kol diff --git a/frozen_deps/Cryptodome/Protocol/KDF.pyi b/frozen_deps/Cryptodome/Protocol/KDF.pyi index fb004bf..745f019 100644 --- a/frozen_deps/Cryptodome/Protocol/KDF.pyi +++ b/frozen_deps/Cryptodome/Protocol/KDF.pyi @@ -1,7 +1,11 @@ from types import ModuleType -from typing import Optional, Callable, Tuple, Union, Dict, Any +from typing import Optional, Callable, Tuple, Union, Dict, Any, overload +from typing_extensions import Literal + +Buffer=bytes|bytearray|memoryview RNG = Callable[[int], bytes] +PRF = Callable[[bytes, bytes], bytes] def PBKDF1(password: str, salt: bytes, dkLen: int, count: Optional[int]=1000, hashAlgo: Optional[ModuleType]=None) -> bytes: ... def PBKDF2(password: str, salt: bytes, dkLen: Optional[int]=16, count: Optional[int]=1000, prf: Optional[RNG]=None, hmac_hash_module: Optional[ModuleType]=None) -> bytes: ... @@ -22,3 +26,17 @@ def _bcrypt_decode(data: bytes) -> bytes: ... def _bcrypt_hash(password:bytes , cost: int, salt: bytes, constant:bytes, invert:bool) -> bytes: ... def bcrypt(password: Union[bytes, str], cost: int, salt: Optional[bytes]=None) -> bytes: ... def bcrypt_check(password: Union[bytes, str], bcrypt_hash: Union[bytes, bytearray, str]) -> None: ... + +@overload +def SP800_108_Counter(master: Buffer, + key_len: int, + prf: PRF, + num_keys: Literal[None] = None, + label: Buffer = b'', context: Buffer = b'') -> bytes: ... + +@overload +def SP800_108_Counter(master: Buffer, + key_len: int, + prf: PRF, + num_keys: int, + label: Buffer = b'', context: Buffer = b'') -> Tuple[bytes]: ... diff --git a/frozen_deps/Cryptodome/Protocol/__init__.py b/frozen_deps/Cryptodome/Protocol/__init__.py index efdf034..76e22bf 100644 --- a/frozen_deps/Cryptodome/Protocol/__init__.py +++ b/frozen_deps/Cryptodome/Protocol/__init__.py @@ -28,4 +28,4 @@ # POSSIBILITY OF SUCH DAMAGE. # =================================================================== -__all__ = ['KDF', 'SecretSharing'] +__all__ = ['KDF', 'SecretSharing', 'DH'] diff --git a/frozen_deps/Cryptodome/Protocol/_scrypt.abi3.so b/frozen_deps/Cryptodome/Protocol/_scrypt.abi3.so Binary files differindex 6ba8f35..baf83a8 100755 --- a/frozen_deps/Cryptodome/Protocol/_scrypt.abi3.so +++ b/frozen_deps/Cryptodome/Protocol/_scrypt.abi3.so diff --git a/frozen_deps/Cryptodome/Protocol/_scrypt.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Protocol/_scrypt.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index c979025..0000000 --- a/frozen_deps/Cryptodome/Protocol/_scrypt.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/PublicKey/ECC.py b/frozen_deps/Cryptodome/PublicKey/ECC.py index 84a4e07..4546742 100644 --- a/frozen_deps/Cryptodome/PublicKey/ECC.py +++ b/frozen_deps/Cryptodome/PublicKey/ECC.py @@ -101,7 +101,7 @@ int ed25519_neg(Point *p); int ed25519_get_xy(uint8_t *xb, uint8_t *yb, size_t modsize, Point *p); int ed25519_double(Point *p); int ed25519_add(Point *P1, const Point *P2); -int ed25519_scalar(Point *P, uint8_t *scalar, size_t scalar_len, uint64_t seed); +int ed25519_scalar(Point *P, const uint8_t *scalar, size_t scalar_len, uint64_t seed); """) _ed448_lib = load_pycryptodome_raw_lib("Cryptodome.PublicKey._ed448", """ @@ -534,6 +534,9 @@ class EccPoint(object): return self def __eq__(self, point): + if not isinstance(point, EccPoint): + return False + cmp_func = lib_func(self, "cmp") return 0 == cmp_func(self._point.get(), point._point.get()) @@ -753,7 +756,7 @@ class EccKey(object): if curve_name not in _curves: raise ValueError("Unsupported curve (%s)" % curve_name) self._curve = _curves[curve_name] - self.curve = curve_name + self.curve = self._curve.desc count = int(self._d is not None) + int(self._seed is not None) @@ -801,6 +804,9 @@ class EccKey(object): return self._curve.desc in ("Ed25519", "Ed448") def __eq__(self, other): + if not isinstance(other, EccKey): + return False + if other.has_private() != self.has_private(): return False @@ -809,7 +815,7 @@ class EccKey(object): def __repr__(self): if self.has_private(): if self._is_eddsa(): - extra = ", seed=%s" % self._seed.hex() + extra = ", seed=%s" % tostr(binascii.hexlify(self._seed)) else: extra = ", d=%d" % int(self._d) else: @@ -957,7 +963,7 @@ class EccKey(object): from Cryptodome.IO import PKCS8 if kwargs.get('passphrase', None) is not None and 'protection' not in kwargs: - raise ValueError("At least the 'protection' parameter should be present") + raise ValueError("At least the 'protection' parameter must be present") if self._is_eddsa(): oid = self._curve.oid @@ -1035,7 +1041,7 @@ class EccKey(object): Args: format (string): - The format to use for encoding the key: + The output format: - ``'DER'``. The key will be encoded in ASN.1 DER format (binary). For a public key, the ASN.1 ``subjectPublicKeyInfo`` structure @@ -1056,20 +1062,25 @@ class EccKey(object): * For NIST P-curves: equivalent to ``'SEC1'``. * For EdDSA curves: ``bytes`` in the format defined in `RFC8032`_. - passphrase (byte string or string): - The passphrase to use for protecting the private key. + passphrase (bytes or string): + (*Private keys only*) The passphrase to protect the + private key. use_pkcs8 (boolean): - Only relevant for private keys. - + (*Private keys only*) If ``True`` (default and recommended), the `PKCS#8`_ representation will be used. It must be ``True`` for EdDSA curves. + If ``False`` and a passphrase is present, the obsolete PEM + encryption will be used. + protection (string): When a private key is exported with password-protection and PKCS#8 (both ``DER`` and ``PEM`` formats), this parameter MUST be - present and be a valid algorithm supported by :mod:`Cryptodome.IO.PKCS8`. - It is recommended to use ``PBKDF2WithHMAC-SHA1AndAES128-CBC``. + present, + For all possible protection schemes, + refer to :ref:`the encryption parameters of PKCS#8<enc_params>`. + It is recommended to use ``'PBKDF2WithHMAC-SHA5126AndAES128-CBC'``. compress (boolean): If ``True``, the method returns a more compact representation @@ -1080,6 +1091,16 @@ class EccKey(object): This parameter is ignored for EdDSA curves, as compression is mandatory. + prot_params (dict): + When a private key is exported with password-protection + and PKCS#8 (both ``DER`` and ``PEM`` formats), this dictionary + contains the parameters to use to derive the encryption key + from the passphrase. + For all possible values, + refer to :ref:`the encryption parameters of PKCS#8<enc_params>`. + The recommendation is to use ``{'iteration_count':21000}`` for PBKDF2, + and ``{'iteration_count':131072}`` for scrypt. + .. warning:: If you don't provide a passphrase, the private key will be exported in the clear! @@ -1115,8 +1136,11 @@ class EccKey(object): raise ValueError("Empty passphrase") use_pkcs8 = args.pop("use_pkcs8", True) - if not use_pkcs8 and self._is_eddsa(): - raise ValueError("'pkcs8' must be True for EdDSA curves") + if not use_pkcs8: + if self._is_eddsa(): + raise ValueError("'pkcs8' must be True for EdDSA curves") + if 'protection' in args: + raise ValueError("'protection' is only supported for PKCS#8") if ext_format == "PEM": if use_pkcs8: @@ -1390,8 +1414,8 @@ def _import_rfc5915_der(encoded, passphrase, curve_oid=None): d = Integer.from_bytes(scalar_bytes) # Decode public key (if any) - if len(private_key) == 4: - public_key_enc = DerBitString(explicit=1).decode(private_key[3]).value + if len(private_key) > 2: + public_key_enc = DerBitString(explicit=1).decode(private_key[-1]).value public_key = _import_public_der(public_key_enc, curve_oid=curve_oid) point_x = public_key.pointQ.x point_y = public_key.pointQ.y @@ -1766,7 +1790,7 @@ def import_key(encoded, passphrase=None, curve_name=None): return _import_der(encoded, passphrase) # SEC1 - if len(encoded) > 0 and bord(encoded[0]) in b'\x02\x03\x04': + if len(encoded) > 0 and bord(encoded[0]) in (0x02, 0x03, 0x04): if curve_name is None: raise ValueError("No curve name was provided") return _import_public_der(encoded, curve_name=curve_name) diff --git a/frozen_deps/Cryptodome/PublicKey/ECC.pyi b/frozen_deps/Cryptodome/PublicKey/ECC.pyi index b0bfbec..e3c4ed5 100644 --- a/frozen_deps/Cryptodome/PublicKey/ECC.pyi +++ b/frozen_deps/Cryptodome/PublicKey/ECC.pyi @@ -1,12 +1,24 @@ -from typing import Union, Callable, Optional, NamedTuple, List, Tuple, Dict, NamedTuple, Any +from __future__ import annotations + +from typing import Union, Callable, Optional, Tuple, Dict, NamedTuple, Any, overload, Literal +from typing_extensions import TypedDict, Unpack, NotRequired from Cryptodome.Math.Numbers import Integer +from Cryptodome.IO._PBES import ProtParams RNG = Callable[[int], bytes] -class UnsupportedEccFeature(ValueError): ... + +class UnsupportedEccFeature(ValueError): + ... + + class EccPoint(object): - def __init__(self, x: Union[int, Integer], y: Union[int, Integer], curve: Optional[str] = ...) -> None: ... + def __init__(self, + x: Union[int, Integer], + y: Union[int, Integer], + curve: Optional[str] = ...) -> None: ... + def set(self, point: EccPoint) -> EccPoint: ... def __eq__(self, point: object) -> bool: ... def __neg__(self) -> EccPoint: ... @@ -27,6 +39,15 @@ class EccPoint(object): def __imul__(self, scalar: int) -> EccPoint: ... def __mul__(self, scalar: int) -> EccPoint: ... + +class ExportParams(TypedDict): + passphrase: NotRequired[Union[bytes, str]] + use_pkcs8: NotRequired[bool] + protection: NotRequired[str] + compress: NotRequired[bool] + prot_params: NotRequired[ProtParams] + + class EccKey(object): curve: str def __init__(self, *, curve: str = ..., d: int = ..., point: EccPoint = ...) -> None: ... @@ -38,7 +59,18 @@ class EccKey(object): @property def pointQ(self) -> EccPoint: ... def public_key(self) -> EccKey: ... - def export_key(self, **kwargs: Union[str, bytes, bool]) -> Union[str,bytes]: ... + + @overload + def export_key(self, + *, + format: Literal['PEM', 'OpenSSH'], + **kwargs: Unpack[ExportParams]) -> str: ... + + @overload + def export_key(self, + *, + format: Literal['DER', 'SEC1', 'raw'], + **kwargs: Unpack[ExportParams]) -> bytes: ... _Curve = NamedTuple("_Curve", [('p', Integer), @@ -54,13 +86,17 @@ _Curve = NamedTuple("_Curve", [('p', Integer), ('openssh', Union[str, None]), ]) -_curves : Dict[str, _Curve] +_curves: Dict[str, _Curve] def generate(**kwargs: Union[str, RNG]) -> EccKey: ... def construct(**kwargs: Union[str, int]) -> EccKey: ... + + def import_key(encoded: Union[bytes, str], - passphrase: Optional[str]=None, - curve_name:Optional[str]=None) -> EccKey: ... + passphrase: Optional[str] = None, + curve_name: Optional[str] = None) -> EccKey: ... + + def _import_ed25519_public_key(encoded: bytes) -> EccKey: ... def _import_ed448_public_key(encoded: bytes) -> EccKey: ... diff --git a/frozen_deps/Cryptodome/PublicKey/RSA.py b/frozen_deps/Cryptodome/PublicKey/RSA.py index bafe036..9a27c36 100644 --- a/frozen_deps/Cryptodome/PublicKey/RSA.py +++ b/frozen_deps/Cryptodome/PublicKey/RSA.py @@ -38,6 +38,7 @@ import struct from Cryptodome import Random from Cryptodome.Util.py3compat import tobytes, bord, tostr from Cryptodome.Util.asn1 import DerSequence, DerNull +from Cryptodome.Util.number import bytes_to_long from Cryptodome.Math.Numbers import Integer from Cryptodome.Math.Primality import (test_probable_prime, @@ -49,7 +50,7 @@ from Cryptodome.PublicKey import (_expand_subject_public_key_info, class RsaKey(object): - r"""Class defining an actual RSA key. + r"""Class defining an RSA key, private or public. Do not instantiate directly. Use :func:`generate`, :func:`construct` or :func:`import_key` instead. @@ -68,10 +69,14 @@ class RsaKey(object): :ivar q: Second factor of the RSA modulus :vartype q: integer - :ivar u: Chinese remainder component (:math:`p^{-1} \text{mod } q`) - :vartype u: integer + :ivar invp: Chinese remainder component (:math:`p^{-1} \text{mod } q`) + :vartype invp: integer + + :ivar invq: Chinese remainder component (:math:`q^{-1} \text{mod } p`) + :vartype invq: integer - :undocumented: exportKey, publickey + :ivar u: Same as ``invp`` + :vartype u: integer """ def __init__(self, **kwargs): @@ -103,6 +108,7 @@ class RsaKey(object): if input_set == private_set: self._dp = self._d % (self._p - 1) # = (e⁻¹) mod (p-1) self._dq = self._d % (self._q - 1) # = (e⁻¹) mod (q-1) + self._invq = None # will be computed on demand @property def n(self): @@ -131,6 +137,30 @@ class RsaKey(object): return int(self._q) @property + def dp(self): + if not self.has_private(): + raise AttributeError("No CRT component 'dp' available for public keys") + return int(self._dp) + + @property + def dq(self): + if not self.has_private(): + raise AttributeError("No CRT component 'dq' available for public keys") + return int(self._dq) + + @property + def invq(self): + if not self.has_private(): + raise AttributeError("No CRT component 'invq' available for public keys") + if self._invq is None: + self._invq = self._q.inverse(self._p) + return int(self._invq) + + @property + def invp(self): + return self.u + + @property def u(self): if not self.has_private(): raise AttributeError("No CRT component 'u' available for public keys") @@ -149,7 +179,7 @@ class RsaKey(object): raise ValueError("Plaintext too large") return int(pow(Integer(plaintext), self._e, self._n)) - def _decrypt(self, ciphertext): + def _decrypt_to_bytes(self, ciphertext): if not 0 <= ciphertext < self._n: raise ValueError("Ciphertext too large") if not self.has_private(): @@ -167,12 +197,18 @@ class RsaKey(object): h = ((m2 - m1) * self._u) % self._q mp = h * self._p + m1 # Step 4: Compute m = m' * (r**(-1)) mod n - result = (r.inverse(self._n) * mp) % self._n - # Verify no faults occurred - if ciphertext != pow(result, self._e, self._n): - raise ValueError("Fault detected in RSA decryption") + # then encode into a big endian byte string + result = Integer._mult_modulo_bytes( + r.inverse(self._n), + mp, + self._n) return result + def _decrypt(self, ciphertext): + """Legacy private method""" + + return bytes_to_long(self._decrypt_to_bytes(ciphertext)) + def has_private(self): """Whether this is an RSA private key""" @@ -225,67 +261,76 @@ class RsaKey(object): return "%s RSA key at 0x%X" % (key_type, id(self)) def export_key(self, format='PEM', passphrase=None, pkcs=1, - protection=None, randfunc=None): + protection=None, randfunc=None, prot_params=None): """Export this RSA key. - Args: + Keyword Args: format (string): - The format to use for wrapping the key: + The desired output format: - - *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_. - - *'DER'*. Binary encoding. - - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. + - ``'PEM'``. (default) Text output, according to `RFC1421`_/`RFC1423`_. + - ``'DER'``. Binary output. + - ``'OpenSSH'``. Text output, according to the OpenSSH specification. Only suitable for public keys (not private keys). - passphrase (string): - (*For private keys only*) The pass phrase used for protecting the output. + Note that PEM contains a DER structure. + + passphrase (bytes or string): + (*Private keys only*) The passphrase to protect the + private key. pkcs (integer): - (*For private keys only*) The ASN.1 structure to use for - serializing the key. Note that even in case of PEM - encoding, there is an inner ASN.1 DER structure. + (*Private keys only*) The standard to use for + serializing the key: PKCS#1 or PKCS#8. - With ``pkcs=1`` (*default*), the private key is encoded in a - simple `PKCS#1`_ structure (``RSAPrivateKey``). + With ``pkcs=1`` (*default*), the private key is encoded with a + simple `PKCS#1`_ structure (``RSAPrivateKey``). The key cannot be + securely encrypted. - With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure - (``PrivateKeyInfo``). + With ``pkcs=8``, the private key is encoded with a `PKCS#8`_ structure + (``PrivateKeyInfo``). PKCS#8 offers the best ways to securely + encrypt the key. .. note:: This parameter is ignored for a public key. - For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo`` - structure is always used. + For DER and PEM, the output is always an + ASN.1 DER ``SubjectPublicKeyInfo`` structure. protection (string): (*For private keys only*) - The encryption scheme to use for protecting the private key. + The encryption scheme to use for protecting the private key + using the passphrase. - If ``None`` (default), the behavior depends on :attr:`format`: + You can only specify a value if ``pkcs=8``. + For all possible protection schemes, + refer to :ref:`the encryption parameters of PKCS#8<enc_params>`. + The recommended value is + ``'PBKDF2WithHMAC-SHA512AndAES256-CBC'``. - - For *'DER'*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC* - scheme is used. The following operations are performed: + If ``None`` (default), the behavior depends on :attr:`format`: - 1. A 16 byte Triple DES key is derived from the passphrase - using :func:`Cryptodome.Protocol.KDF.PBKDF2` with 8 bytes salt, - and 1 000 iterations of :mod:`Cryptodome.Hash.HMAC`. - 2. The private key is encrypted using CBC. - 3. The encrypted key is encoded according to PKCS#8. + - if ``format='PEM'``, the obsolete PEM encryption scheme is used. + It is based on MD5 for key derivation, and 3DES for encryption. - - For *'PEM'*, the obsolete PEM encryption scheme is used. - It is based on MD5 for key derivation, and Triple DES for encryption. + - if ``format='DER'``, the ``'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'`` + scheme is used. - Specifying a value for :attr:`protection` is only meaningful for PKCS#8 - (that is, ``pkcs=8``) and only if a pass phrase is present too. + prot_params (dict): + (*For private keys only*) - The supported schemes for PKCS#8 are listed in the - :mod:`Cryptodome.IO.PKCS8` module (see :attr:`wrap_algo` parameter). + The parameters to use to derive the encryption key + from the passphrase. ``'protection'`` must be also specified. + For all possible values, + refer to :ref:`the encryption parameters of PKCS#8<enc_params>`. + The recommendation is to use ``{'iteration_count':21000}`` for PBKDF2, + and ``{'iteration_count':131072}`` for scrypt. randfunc (callable): A function that provides random bytes. Only used for PEM encoding. The default is :func:`Cryptodome.Random.get_random_bytes`. Returns: - byte string: the encoded key + bytes: the encoded key Raises: ValueError:when the format is unknown or when you try to encrypt a private @@ -344,9 +389,12 @@ class RsaKey(object): else: key_type = 'ENCRYPTED PRIVATE KEY' if not protection: + if prot_params: + raise ValueError("'protection' parameter must be set") protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC' binary_key = PKCS8.wrap(binary_key, oid, passphrase, protection, + prot_params=prot_params, key_params=DerNull()) passphrase = None else: @@ -368,29 +416,41 @@ class RsaKey(object): raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format) # Backward compatibility - exportKey = export_key - publickey = public_key + def exportKey(self, *args, **kwargs): + """:meta private:""" + return self.export_key(*args, **kwargs) + + def publickey(self): + """:meta private:""" + return self.public_key() # Methods defined in PyCryptodome that we don't support anymore def sign(self, M, K): + """:meta private:""" raise NotImplementedError("Use module Cryptodome.Signature.pkcs1_15 instead") def verify(self, M, signature): + """:meta private:""" raise NotImplementedError("Use module Cryptodome.Signature.pkcs1_15 instead") def encrypt(self, plaintext, K): + """:meta private:""" raise NotImplementedError("Use module Cryptodome.Cipher.PKCS1_OAEP instead") def decrypt(self, ciphertext): + """:meta private:""" raise NotImplementedError("Use module Cryptodome.Cipher.PKCS1_OAEP instead") def blind(self, M, B): + """:meta private:""" raise NotImplementedError def unblind(self, M, B): + """:meta private:""" raise NotImplementedError def size(self): + """:meta private:""" raise NotImplementedError @@ -408,6 +468,7 @@ def generate(bits, randfunc=None, e=65537): Key length, or size (in bits) of the RSA modulus. It must be at least 1024, but **2048 is recommended.** The FIPS standard only defines 1024, 2048 and 3072. + Keyword Args: randfunc (callable): Function that returns random bytes. The default is :func:`Cryptodome.Random.get_random_bytes`. @@ -505,6 +566,7 @@ def construct(rsa_components, consistency_check=True): 5. Second factor of *n* (*q*). Optional. 6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional. + Keyword Args: consistency_check (boolean): If ``True``, the library will verify that the provided components fulfil the main RSA properties. diff --git a/frozen_deps/Cryptodome/PublicKey/RSA.pyi b/frozen_deps/Cryptodome/PublicKey/RSA.pyi index d436acf..85f6c4a 100644 --- a/frozen_deps/Cryptodome/PublicKey/RSA.pyi +++ b/frozen_deps/Cryptodome/PublicKey/RSA.pyi @@ -1,4 +1,7 @@ -from typing import Callable, Union, Tuple, Optional +from typing import Callable, Union, Tuple, Optional, overload, Literal + +from Cryptodome.Math.Numbers import Integer +from Cryptodome.IO._PBES import ProtParams __all__ = ['generate', 'construct', 'import_key', 'RsaKey', 'oid'] @@ -7,6 +10,7 @@ RNG = Callable[[int], bytes] class RsaKey(object): def __init__(self, **kwargs: int) -> None: ... + @property def n(self) -> int: ... @property @@ -19,6 +23,11 @@ class RsaKey(object): def q(self) -> int: ... @property def u(self) -> int: ... + @property + def invp(self) -> int: ... + @property + def invq(self) -> int: ... + def size_in_bits(self) -> int: ... def size_in_bytes(self) -> int: ... def has_private(self) -> bool: ... @@ -30,18 +39,36 @@ class RsaKey(object): def __getstate__(self) -> None: ... def __repr__(self) -> str: ... def __str__(self) -> str: ... - def export_key(self, format: Optional[str]="PEM", passphrase: Optional[str]=None, pkcs: Optional[int]=1, - protection: Optional[str]=None, randfunc: Optional[RNG]=None) -> bytes: ... + + @overload + def export_key(self, + format: Optional[str]="PEM", + passphrase: Optional[str]=None, + pkcs: Optional[int]=1, + protection: Optional[str]=None, + randfunc: Optional[RNG]=None + ) -> bytes: ... + @overload + def export_key(self, *, + format: Optional[str]="PEM", + passphrase: str, + pkcs: Literal[8], + protection: str, + randfunc: Optional[RNG]=None, + prot_params: ProtParams, + ) -> bytes: ... # Backward compatibility exportKey = export_key publickey = public_key +Int = Union[int, Integer] + def generate(bits: int, randfunc: Optional[RNG]=None, e: Optional[int]=65537) -> RsaKey: ... -def construct(rsa_components: Union[Tuple[int, int], # n, e - Tuple[int, int, int], # n, e, d - Tuple[int, int, int, int, int], # n, e, d, p, q - Tuple[int, int, int, int, int, int]], # n, e, d, p, q, crt_q +def construct(rsa_components: Union[Tuple[Int, Int], # n, e + Tuple[Int, Int, Int], # n, e, d + Tuple[Int, Int, Int, Int, Int], # n, e, d, p, q + Tuple[Int, Int, Int, Int, Int, Int]], # n, e, d, p, q, crt_q consistency_check: Optional[bool]=True) -> RsaKey: ... def import_key(extern_key: Union[str, bytes], passphrase: Optional[str]=None) -> RsaKey: ... diff --git a/frozen_deps/Cryptodome/PublicKey/_ec_ws.abi3.so b/frozen_deps/Cryptodome/PublicKey/_ec_ws.abi3.so Binary files differindex b6fd404..b1272d2 100755 --- a/frozen_deps/Cryptodome/PublicKey/_ec_ws.abi3.so +++ b/frozen_deps/Cryptodome/PublicKey/_ec_ws.abi3.so diff --git a/frozen_deps/Cryptodome/PublicKey/_ec_ws.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/PublicKey/_ec_ws.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 4cb470d..0000000 --- a/frozen_deps/Cryptodome/PublicKey/_ec_ws.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/PublicKey/_ed25519.abi3.so b/frozen_deps/Cryptodome/PublicKey/_ed25519.abi3.so Binary files differindex bd8bcc5..e047bcb 100755 --- a/frozen_deps/Cryptodome/PublicKey/_ed25519.abi3.so +++ b/frozen_deps/Cryptodome/PublicKey/_ed25519.abi3.so diff --git a/frozen_deps/Cryptodome/PublicKey/_ed448.abi3.so b/frozen_deps/Cryptodome/PublicKey/_ed448.abi3.so Binary files differindex ee47399..da7209a 100755 --- a/frozen_deps/Cryptodome/PublicKey/_ed448.abi3.so +++ b/frozen_deps/Cryptodome/PublicKey/_ed448.abi3.so diff --git a/frozen_deps/Cryptodome/PublicKey/_x25519.abi3.so b/frozen_deps/Cryptodome/PublicKey/_x25519.abi3.so Binary files differindex bbdc726..dbb00d5 100755 --- a/frozen_deps/Cryptodome/PublicKey/_x25519.abi3.so +++ b/frozen_deps/Cryptodome/PublicKey/_x25519.abi3.so diff --git a/frozen_deps/Cryptodome/Random/random.pyi b/frozen_deps/Cryptodome/Random/random.pyi index f873c4a..9b7cf7e 100644 --- a/frozen_deps/Cryptodome/Random/random.pyi +++ b/frozen_deps/Cryptodome/Random/random.pyi @@ -1,13 +1,15 @@ -from typing import Callable, Tuple, Union, Sequence, Any, Optional +from typing import Callable, Tuple, Union, Sequence, Any, Optional, TypeVar __all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample'] +T = TypeVar('T') + class StrongRandom(object): def __init__(self, rng: Optional[Any]=None, randfunc: Optional[Callable]=None) -> None: ... # TODO What is rng? def getrandbits(self, k: int) -> int: ... def randrange(self, start: int, stop: int = ..., step: int = ...) -> int: ... def randint(self, a: int, b: int) -> int: ... - def choice(self, seq: Sequence) -> object: ... + def choice(self, seq: Sequence[T]) -> T: ... def shuffle(self, x: Sequence) -> None: ... def sample(self, population: Sequence, k: int) -> list: ... diff --git a/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi b/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi index 7ed68e6..e7424f5 100644 --- a/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi +++ b/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi @@ -1,7 +1,28 @@ -from typing import Optional, Callable +from typing import Union, Callable, Optional +from typing_extensions import Protocol from Cryptodome.PublicKey.RSA import RsaKey -from Cryptodome.Signature.pss import PSS_SigScheme -def new(rsa_key: RsaKey, mgfunc: Optional[Callable]=None, saltLen: Optional[int]=None, randfunc: Optional[Callable]=None) -> PSS_SigScheme: ... +class Hash(Protocol): + def digest(self) -> bytes: ... + def update(self, bytes) -> None: ... + + +class HashModule(Protocol): + @staticmethod + def new(data: Optional[bytes]) -> Hash: ... + + +MaskFunction = Callable[[bytes, int, Union[Hash, HashModule]], bytes] +RndFunction = Callable[[int], bytes] + +class PSS_SigScheme: + def __init__(self, key: RsaKey, mgfunc: MaskFunction, saltLen: int, randfunc: RndFunction) -> None: ... + def can_sign(self) -> bool: ... + def sign(self, msg_hash: Hash) -> bytes: ... + def verify(self, msg_hash: Hash, signature: bytes) -> bool: ... + + + +def new(rsa_key: RsaKey, mgfunc: Optional[MaskFunction]=None, saltLen: Optional[int]=None, randfunc: Optional[RndFunction]=None) -> PSS_SigScheme: ... diff --git a/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi b/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi index 5851e5b..d02555c 100644 --- a/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi +++ b/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi @@ -1,6 +1,16 @@ +from typing import Optional +from typing_extensions import Protocol + from Cryptodome.PublicKey.RSA import RsaKey -from Cryptodome.Signature.pkcs1_15 import PKCS115_SigScheme +class Hash(Protocol): + def digest(self) -> bytes: ... + +class PKCS115_SigScheme: + def __init__(self, rsa_key: RsaKey) -> None: ... + def can_sign(self) -> bool: ... + def sign(self, msg_hash: Hash) -> bytes: ... + def verify(self, msg_hash: Hash, signature: bytes) -> bool: ... -def new(rsa_key: RsaKey) -> PKCS115_SigScheme: ...
\ No newline at end of file +def new(rsa_key: RsaKey) -> PKCS115_SigScheme: ... diff --git a/frozen_deps/Cryptodome/Signature/eddsa.py b/frozen_deps/Cryptodome/Signature/eddsa.py index e80a866..638b96b 100644 --- a/frozen_deps/Cryptodome/Signature/eddsa.py +++ b/frozen_deps/Cryptodome/Signature/eddsa.py @@ -39,8 +39,9 @@ from Cryptodome.PublicKey.ECC import (EccKey, def import_public_key(encoded): - """Import an EdDSA ECC public key, when encoded as raw ``bytes`` as described - in RFC8032. + """Create a new Ed25519 or Ed448 public key object, + starting from the key encoded as raw ``bytes``, + in the format described in RFC8032. Args: encoded (bytes): @@ -66,8 +67,9 @@ def import_public_key(encoded): def import_private_key(encoded): - """Import an EdDSA ECC private key, when encoded as raw ``bytes`` as described - in RFC8032. + """Create a new Ed25519 or Ed448 private key object, + starting from the key encoded as raw ``bytes``, + in the format described in RFC8032. Args: encoded (bytes): @@ -313,7 +315,7 @@ def new(key, mode, context=None): can perform or verify an EdDSA signature. Args: - key (:class:`Cryptodome.PublicKey.ECC` object: + key (:class:`Cryptodome.PublicKey.ECC` object): The key to use for computing the signature (*private* keys only) or for verifying one. The key must be on the curve ``Ed25519`` or ``Ed448``. diff --git a/frozen_deps/Cryptodome/Signature/eddsa.pyi b/frozen_deps/Cryptodome/Signature/eddsa.pyi index bf985c4..809a7ad 100644 --- a/frozen_deps/Cryptodome/Signature/eddsa.pyi +++ b/frozen_deps/Cryptodome/Signature/eddsa.pyi @@ -18,4 +18,4 @@ class EdDSASigScheme(object): def sign(self, msg_or_hash: Union[bytes, Hash, XOF]) -> bytes: ... def verify(self, msg_or_hash: Union[bytes, Hash, XOF], signature: bytes) -> None: ... -def new(key: EccKey, mode: bytes, context: Optional[bytes]=None) -> EdDSASigScheme: ... +def new(key: EccKey, mode: str, context: Optional[bytes]=None) -> EdDSASigScheme: ... diff --git a/frozen_deps/Cryptodome/Signature/pkcs1_15.py b/frozen_deps/Cryptodome/Signature/pkcs1_15.py index ae9257e..bdde78a 100644 --- a/frozen_deps/Cryptodome/Signature/pkcs1_15.py +++ b/frozen_deps/Cryptodome/Signature/pkcs1_15.py @@ -77,10 +77,11 @@ class PKCS115_SigScheme: em = _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k) # Step 2a (OS2IP) em_int = bytes_to_long(em) - # Step 2b (RSASP1) - m_int = self._key._decrypt(em_int) - # Step 2c (I2OSP) - signature = long_to_bytes(m_int, k) + # Step 2b (RSASP1) and Step 2c (I2OSP) + signature = self._key._decrypt_to_bytes(em_int) + # Verify no faults occurred + if em_int != pow(bytes_to_long(signature), self._key.e, self._key.n): + raise ValueError("Fault detected in RSA private key operation") return signature def verify(self, msg_hash, signature): @@ -202,7 +203,7 @@ def _EMSA_PKCS1_V1_5_ENCODE(msg_hash, emLen, with_hash_parameters=True): # We need at least 11 bytes for the remaining data: 3 fixed bytes and # at least 8 bytes of padding). if emLen<len(digestInfo)+11: - raise TypeError("Selected hash algorithm has a too long digest (%d bytes)." % len(digest)) + raise TypeError("DigestInfo is too long for this RSA key (%d bytes)." % len(digestInfo)) PS = b'\xFF' * (emLen - len(digestInfo) - 3) return b'\x00\x01' + PS + b'\x00' + digestInfo diff --git a/frozen_deps/Cryptodome/Signature/pss.py b/frozen_deps/Cryptodome/Signature/pss.py index 0b05ed2..b929e26 100644 --- a/frozen_deps/Cryptodome/Signature/pss.py +++ b/frozen_deps/Cryptodome/Signature/pss.py @@ -107,10 +107,11 @@ class PSS_SigScheme: em = _EMSA_PSS_ENCODE(msg_hash, modBits-1, self._randfunc, mgf, sLen) # Step 2a (OS2IP) em_int = bytes_to_long(em) - # Step 2b (RSASP1) - m_int = self._key._decrypt(em_int) - # Step 2c (I2OSP) - signature = long_to_bytes(m_int, k) + # Step 2b (RSASP1) and Step 2c (I2OSP) + signature = self._key._decrypt_to_bytes(em_int) + # Verify no faults occurred + if em_int != pow(bytes_to_long(signature), self._key.e, self._key.n): + raise ValueError("Fault detected in RSA private key operation") return signature def verify(self, msg_hash, signature): @@ -178,7 +179,7 @@ def MGF1(mgfSeed, maskLen, hash_gen): :return: the mask, as a *byte string* """ - + T = b"" for counter in iter_range(ceil_div(maskLen, hash_gen.digest_size)): c = long_to_bytes(counter, 4) diff --git a/frozen_deps/Cryptodome/Signature/pss.pyi b/frozen_deps/Cryptodome/Signature/pss.pyi index 9ca19ea..84a960e 100644 --- a/frozen_deps/Cryptodome/Signature/pss.pyi +++ b/frozen_deps/Cryptodome/Signature/pss.pyi @@ -18,7 +18,7 @@ MaskFunction = Callable[[bytes, int, Union[Hash, HashModule]], bytes] RndFunction = Callable[[int], bytes] class PSS_SigScheme: - def __init__(self, key: RsaKey, mgfunc: RndFunction, saltLen: int, randfunc: RndFunction) -> None: ... + def __init__(self, key: RsaKey, mgfunc: MaskFunction, saltLen: int, randfunc: RndFunction) -> None: ... def can_sign(self) -> bool: ... def sign(self, msg_hash: Hash) -> bytes: ... def verify(self, msg_hash: Hash, signature: bytes) -> None: ... diff --git a/frozen_deps/Cryptodome/Util/Counter.py b/frozen_deps/Cryptodome/Util/Counter.py index c67bc95..269b5a7 100644 --- a/frozen_deps/Cryptodome/Util/Counter.py +++ b/frozen_deps/Cryptodome/Util/Counter.py @@ -51,6 +51,8 @@ def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, all If ``False`` (default), in big endian format. allow_wraparound (boolean): This parameter is ignored. + An ``OverflowError`` exception is always raised when the counter wraps + around to zero. Returns: An object that can be passed with the :data:`counter` parameter to a CTR mode cipher. diff --git a/frozen_deps/Cryptodome/Util/_cpuid_c.abi3.so b/frozen_deps/Cryptodome/Util/_cpuid_c.abi3.so Binary files differindex 60f1e26..51e31b7 100755 --- a/frozen_deps/Cryptodome/Util/_cpuid_c.abi3.so +++ b/frozen_deps/Cryptodome/Util/_cpuid_c.abi3.so diff --git a/frozen_deps/Cryptodome/Util/_cpuid_c.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Util/_cpuid_c.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index 718bec8..0000000 --- a/frozen_deps/Cryptodome/Util/_cpuid_c.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Util/_raw_api.py b/frozen_deps/Cryptodome/Util/_raw_api.py index c2e0187..cd64ac8 100644 --- a/frozen_deps/Cryptodome/Util/_raw_api.py +++ b/frozen_deps/Cryptodome/Util/_raw_api.py @@ -76,6 +76,12 @@ try: if '__pypy__' not in sys.builtin_module_names and sys.flags.optimize == 2: raise ImportError("CFFI with optimize=2 fails due to pycparser bug.") + # cffi still uses PyUnicode_GetSize, which was removed in Python 3.12 + # thus leading to a crash on cffi.dlopen() + # See https://groups.google.com/u/1/g/python-cffi/c/oZkOIZ_zi5k + if sys.version_info >= (3, 12) and os.name == "nt": + raise ImportError("CFFI is not compatible with Python 3.12 on Windows") + from cffi import FFI ffi = FFI() diff --git a/frozen_deps/Cryptodome/Util/_strxor.abi3.so b/frozen_deps/Cryptodome/Util/_strxor.abi3.so Binary files differindex c028978..f0f3784 100755 --- a/frozen_deps/Cryptodome/Util/_strxor.abi3.so +++ b/frozen_deps/Cryptodome/Util/_strxor.abi3.so diff --git a/frozen_deps/Cryptodome/Util/_strxor.cpython-39-x86_64-linux-gnu.so b/frozen_deps/Cryptodome/Util/_strxor.cpython-39-x86_64-linux-gnu.so Binary files differdeleted file mode 100755 index dd3fb45..0000000 --- a/frozen_deps/Cryptodome/Util/_strxor.cpython-39-x86_64-linux-gnu.so +++ /dev/null diff --git a/frozen_deps/Cryptodome/Util/asn1.py b/frozen_deps/Cryptodome/Util/asn1.py index a88f087..36f2d72 100644 --- a/frozen_deps/Cryptodome/Util/asn1.py +++ b/frozen_deps/Cryptodome/Util/asn1.py @@ -22,13 +22,20 @@ import struct -from Cryptodome.Util.py3compat import byte_string, b, bchr, bord +from Cryptodome.Util.py3compat import byte_string, bchr, bord from Cryptodome.Util.number import long_to_bytes, bytes_to_long -__all__ = ['DerObject', 'DerInteger', 'DerOctetString', 'DerNull', - 'DerSequence', 'DerObjectId', 'DerBitString', 'DerSetOf'] +__all__ = ['DerObject', 'DerInteger', 'DerBoolean', 'DerOctetString', + 'DerNull', 'DerSequence', 'DerObjectId', 'DerBitString', 'DerSetOf'] +# Useful references: +# - https://luca.ntop.org/Teaching/Appunti/asn1.html +# - https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ +# - https://www.zytrax.com/tech/survival/asn1.html +# - https://www.oss.com/asn1/resources/books-whitepapers-pubs/larmouth-asn1-book.pdf +# - https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf +# - https://misc.daniel-marschall.de/asn.1/oid-converter/online.php def _is_number(x, only_non_negative=False): test = 0 @@ -46,7 +53,7 @@ class BytesIO_EOF(object): def __init__(self, initial_bytes): self._buffer = initial_bytes self._index = 0 - self._bookmark = None + self._bookmark = None def set_bookmark(self): self._bookmark = self._index @@ -82,7 +89,7 @@ class DerObject(object): """Initialize the DER object according to a specific ASN.1 type. :Parameters: - asn1Id : integer + asn1Id : integer or byte The universal DER tag number for this object (e.g. 0x10 for a SEQUENCE). If None, the tag is not known yet. @@ -92,16 +99,20 @@ class DerObject(object): the content octets). If not specified, the payload is empty. - implicit : integer - The IMPLICIT tag number to use for the encoded object. + implicit : integer or byte + The IMPLICIT tag number (< 0x1F) to use for the encoded object. It overrides the universal tag *asn1Id*. + It cannot be combined with the ``explicit`` parameter. + By default, there is no IMPLICIT tag. constructed : bool True when the ASN.1 type is *constructed*. - False when it is *primitive*. + False when it is *primitive* (default). - explicit : integer - The EXPLICIT tag number to use for the encoded object. + explicit : integer or byte + The EXPLICIT tag number (< 0x1F) to use for the encoded object. + It cannot be combined with the ``implicit`` parameter. + By default, there is no EXPLICIT tag. """ if asn1Id is None: @@ -125,23 +136,26 @@ class DerObject(object): # context-spec | 1 0 (default for IMPLICIT/EXPLICIT) # private | 1 1 # + + constructed_bit = 0x20 if constructed else 0x00 + if None not in (explicit, implicit): raise ValueError("Explicit and implicit tags are" " mutually exclusive") if implicit is not None: - self._tag_octet = 0x80 | 0x20 * constructed | self._convertTag(implicit) - return - - if explicit is not None: - self._tag_octet = 0xA0 | self._convertTag(explicit) - self._inner_tag_octet = 0x20 * constructed | asn1Id - return - - self._tag_octet = 0x20 * constructed | asn1Id + # IMPLICIT tag overrides asn1Id + self._tag_octet = 0x80 | constructed_bit | self._convertTag(implicit) + elif explicit is not None: + # 'constructed bit' is always asserted for an EXPLICIT tag + self._tag_octet = 0x80 | 0x20 | self._convertTag(explicit) + self._inner_tag_octet = constructed_bit | asn1Id + else: + # Neither IMPLICIT nor EXPLICIT + self._tag_octet = constructed_bit | asn1Id def _convertTag(self, tag): - """Check if *tag* is a real DER tag. + """Check if *tag* is a real DER tag (5 bits). Convert it from a character to number if necessary. """ if not _is_number(tag): @@ -306,7 +320,7 @@ class DerInteger(DerObject): return DerObject.encode(self) def decode(self, der_encoded, strict=False): - """Decode a complete DER INTEGER DER, and re-initializes this + """Decode a DER-encoded INTEGER, and re-initializes this object with it. Args: @@ -341,6 +355,89 @@ class DerInteger(DerObject): self.value -= bits +class DerBoolean(DerObject): + """Class to model a DER-encoded BOOLEAN. + + An example of encoding is:: + + >>> from Cryptodome.Util.asn1 import DerBoolean + >>> bool_der = DerBoolean(True) + >>> print(bool_der.encode().hex()) + + which will show ``0101ff``, the DER encoding of True. + + And for decoding:: + + >>> s = bytes.fromhex('0101ff') + >>> try: + >>> bool_der = DerBoolean() + >>> bool_der.decode(s) + >>> print(bool_der.value) + >>> except ValueError: + >>> print "Not a valid DER BOOLEAN" + + the output will be ``True``. + + :ivar value: The boolean value + :vartype value: boolean + """ + def __init__(self, value=False, implicit=None, explicit=None): + """Initialize the DER object as a BOOLEAN. + + Args: + value (boolean): + The value of the boolean. Default is False. + + implicit (integer or byte): + The IMPLICIT tag number (< 0x1F) to use for the encoded object. + It overrides the universal tag for BOOLEAN (1). + It cannot be combined with the ``explicit`` parameter. + By default, there is no IMPLICIT tag. + + explicit (integer or byte): + The EXPLICIT tag number (< 0x1F) to use for the encoded object. + It cannot be combined with the ``implicit`` parameter. + By default, there is no EXPLICIT tag. + """ + + DerObject.__init__(self, 0x01, b'', implicit, False, explicit) + self.value = value # The boolean value + + def encode(self): + """Return the DER BOOLEAN, fully encoded as a binary string.""" + + self.payload = b'\xFF' if self.value else b'\x00' + return DerObject.encode(self) + + def decode(self, der_encoded, strict=False): + """Decode a DER-encoded BOOLEAN, and re-initializes this object with it. + + Args: + der_encoded (byte string): A DER-encoded BOOLEAN. + + Raises: + ValueError: in case of parsing errors. + """ + + return DerObject.decode(self, der_encoded, strict) + + def _decodeFromStream(self, s, strict): + """Decode a DER-encoded BOOLEAN from a file.""" + + # Fill up self.payload + DerObject._decodeFromStream(self, s, strict) + + if len(self.payload) != 1: + raise ValueError("Invalid encoding for DER BOOLEAN: payload is not 1 byte") + + if bord(self.payload[0]) == 0: + self.value = False + elif bord(self.payload[0]) == 0xFF: + self.value = True + else: + raise ValueError("Invalid payload for DER BOOLEAN") + + class DerSequence(DerObject): """Class to model a DER SEQUENCE. @@ -384,7 +481,7 @@ class DerSequence(DerObject): """ - def __init__(self, startSeq=None, implicit=None): + def __init__(self, startSeq=None, implicit=None, explicit=None): """Initialize the DER object as a SEQUENCE. :Parameters: @@ -392,12 +489,19 @@ class DerSequence(DerObject): A sequence whose element are either integers or other DER objects. - implicit : integer - The IMPLICIT tag to use for the encoded object. + implicit : integer or byte + The IMPLICIT tag number (< 0x1F) to use for the encoded object. It overrides the universal tag for SEQUENCE (16). + It cannot be combined with the ``explicit`` parameter. + By default, there is no IMPLICIT tag. + + explicit : integer or byte + The EXPLICIT tag number (< 0x1F) to use for the encoded object. + It cannot be combined with the ``implicit`` parameter. + By default, there is no EXPLICIT tag. """ - DerObject.__init__(self, 0x10, b'', implicit, True) + DerObject.__init__(self, 0x10, b'', implicit, True, explicit) if startSeq is None: self._seq = [] else: @@ -434,6 +538,10 @@ class DerSequence(DerObject): self._seq.append(item) return self + def insert(self, index, item): + self._seq.insert(index, item) + return self + def hasInts(self, only_non_negative=True): """Return the number of items in this sequence that are integers. @@ -527,7 +635,6 @@ class DerSequence(DerObject): self._seq.append(p.data_since_bookmark()) else: derInt = DerInteger() - #import pdb; pdb.set_trace() data = p.data_since_bookmark() derInt.decode(data, strict=strict) self._seq.append(derInt.value) @@ -648,19 +755,25 @@ class DerObjectId(DerObject): binary string.""" comps = [int(x) for x in self.value.split(".")] + if len(comps) < 2: raise ValueError("Not a valid Object Identifier string") - self.payload = bchr(40*comps[0]+comps[1]) - for v in comps[2:]: - if v == 0: - enc = [0] - else: - enc = [] - while v: - enc.insert(0, (v & 0x7F) | 0x80) - v >>= 7 - enc[-1] &= 0x7F - self.payload += b''.join([bchr(x) for x in enc]) + if comps[0] > 2: + raise ValueError("First component must be 0, 1 or 2") + if comps[0] < 2 and comps[1] > 39: + raise ValueError("Second component must be 39 at most") + + subcomps = [40 * comps[0] + comps[1]] + comps[2:] + + encoding = [] + for v in reversed(subcomps): + encoding.append(v & 0x7F) + v >>= 7 + while v: + encoding.append((v & 0x7F) | 0x80) + v >>= 7 + + self.payload = b''.join([bchr(x) for x in reversed(encoding)]) return DerObject.encode(self) def decode(self, der_encoded, strict=False): @@ -687,15 +800,27 @@ class DerObjectId(DerObject): # Derive self.value from self.payload p = BytesIO_EOF(self.payload) - comps = [str(x) for x in divmod(p.read_byte(), 40)] + + subcomps = [] v = 0 while p.remaining_data(): c = p.read_byte() - v = v*128 + (c & 0x7F) + v = (v << 7) + (c & 0x7F) if not (c & 0x80): - comps.append(str(v)) + subcomps.append(v) v = 0 - self.value = '.'.join(comps) + + if len(subcomps) == 0: + raise ValueError("Empty payload") + + if subcomps[0] < 40: + subcomps[:1] = [0, subcomps[0]] + elif subcomps[0] < 80: + subcomps[:1] = [1, subcomps[0] - 40] + else: + subcomps[:1] = [2, subcomps[0] - 80] + + self.value = ".".join([str(x) for x in subcomps]) class DerBitString(DerObject): @@ -736,7 +861,7 @@ class DerBitString(DerObject): If not specified, the bit string is empty. implicit : integer The IMPLICIT tag to use for the encoded object. - It overrides the universal tag for OCTET STRING (3). + It overrides the universal tag for BIT STRING (3). explicit : integer The EXPLICIT tag to use for the encoded object. """ diff --git a/frozen_deps/Cryptodome/Util/asn1.pyi b/frozen_deps/Cryptodome/Util/asn1.pyi index dac023b..ee4891c 100644 --- a/frozen_deps/Cryptodome/Util/asn1.pyi +++ b/frozen_deps/Cryptodome/Util/asn1.pyi @@ -19,13 +19,19 @@ class DerObject: def __init__(self, asn1Id: Optional[int]=None, payload: Optional[bytes]=..., implicit: Optional[int]=None, constructed: Optional[bool]=False, explicit: Optional[int]=None) -> None: ... def encode(self) -> bytes: ... - def decode(self, der_encoded: bytes, strict: Optional[bool]=False) -> DerObject: ... + def decode(self, der_encoded: bytes, strict: bool=...) -> DerObject: ... class DerInteger(DerObject): value: int def __init__(self, value: Optional[int]= 0, implicit: Optional[int]=None, explicit: Optional[int]=None) -> None: ... def encode(self) -> bytes: ... - def decode(self, der_encoded: bytes, strict: Optional[bool]=False) -> DerInteger: ... + def decode(self, der_encoded: bytes, strict: bool=...) -> DerInteger: ... + +class DerBoolean(DerObject): + value: bool + def __init__(self, value: bool=..., implicit: Optional[Union[int, bytes]]=..., explicit: Optional[Union[int, bytes]]=...) -> None: ... + def encode(self) -> bytes: ... + def decode(self, der_encoded: bytes, strict: bool=...) -> DerBoolean: ... class DerSequence(DerObject): def __init__(self, startSeq: Optional[Sequence[Union[int, DerInteger, DerObject]]]=None, implicit: Optional[int]=None) -> None: ... @@ -41,7 +47,7 @@ class DerSequence(DerObject): def hasInts(self, only_non_negative: Optional[bool]=True) -> int: ... def hasOnlyInts(self, only_non_negative: Optional[bool]=True) -> bool: ... def encode(self) -> bytes: ... - def decode(self, der_encoded: bytes, strict: Optional[bool]=False, nr_elements: Optional[int]=None, only_ints_expected: Optional[bool]=False) -> DerSequence: ... + def decode(self, der_encoded: bytes, strict: bool=..., nr_elements: Optional[int]=None, only_ints_expected: Optional[bool]=False) -> DerSequence: ... class DerOctetString(DerObject): payload: bytes @@ -54,13 +60,13 @@ class DerObjectId(DerObject): value: str def __init__(self, value: Optional[str]=..., implicit: Optional[int]=None, explicit: Optional[int]=None) -> None: ... def encode(self) -> bytes: ... - def decode(self, der_encoded: bytes, strict: Optional[bool]=False) -> DerObjectId: ... + def decode(self, der_encoded: bytes, strict: bool=...) -> DerObjectId: ... class DerBitString(DerObject): value: bytes def __init__(self, value: Optional[bytes]=..., implicit: Optional[int]=None, explicit: Optional[int]=None) -> None: ... def encode(self) -> bytes: ... - def decode(self, der_encoded: bytes, strict: Optional[bool]=False) -> DerBitString: ... + def decode(self, der_encoded: bytes, strict: bool=...) -> DerBitString: ... DerSetElement = Union[bytes, int] @@ -70,5 +76,5 @@ class DerSetOf(DerObject): def __iter__(self) -> Iterable: ... def __len__(self) -> int: ... def add(self, elem: DerSetElement) -> None: ... - def decode(self, der_encoded: bytes, strict: Optional[bool]=False) -> DerObject: ... + def decode(self, der_encoded: bytes, strict: bool=...) -> DerObject: ... def encode(self) -> bytes: ... diff --git a/frozen_deps/Cryptodome/Util/number.py b/frozen_deps/Cryptodome/Util/number.py index 5af85a3..6d59fd9 100644 --- a/frozen_deps/Cryptodome/Util/number.py +++ b/frozen_deps/Cryptodome/Util/number.py @@ -51,12 +51,8 @@ def size (N): """Returns the size of the number N in bits.""" if N < 0: - raise ValueError("Size in bits only avialable for non-negative numbers") - - bits = 0 - while N >> bits: - bits += 1 - return bits + raise ValueError("Size in bits only available for non-negative numbers") + return N.bit_length() def getRandomInteger(N, randfunc=None): @@ -113,27 +109,56 @@ def getRandomNBitInteger(N, randfunc=None): assert size(value) >= N return value -def GCD(x,y): - """Greatest Common Denominator of :data:`x` and :data:`y`. - """ - x = abs(x) ; y = abs(y) - while x > 0: - x, y = y % x, x - return y +if sys.version_info[:2] >= (3, 5): + + GCD = math.gcd + +else: + + def GCD(x,y): + """Greatest Common Denominator of :data:`x` and :data:`y`. + """ + + x = abs(x) ; y = abs(y) + while x > 0: + x, y = y % x, x + return y + -def inverse(u, v): - """The inverse of :data:`u` *mod* :data:`v`.""" +if sys.version_info[:2] >= (3, 8): - u3, v3 = u, v - u1, v1 = 1, 0 - while v3 > 0: - q = u3 // v3 - u1, v1 = v1, u1 - v1*q - u3, v3 = v3, u3 - v3*q - while u1<0: - u1 = u1 + v - return u1 + def inverse(u, v): + """The inverse of :data:`u` *mod* :data:`v`.""" + + if v == 0: + raise ZeroDivisionError("Modulus cannot be zero") + if v < 0: + raise ValueError("Modulus cannot be negative") + + return pow(u, -1, v) + +else: + + def inverse(u, v): + """The inverse of :data:`u` *mod* :data:`v`.""" + + if v == 0: + raise ZeroDivisionError("Modulus cannot be zero") + if v < 0: + raise ValueError("Modulus cannot be negative") + + u3, v3 = u, v + u1, v1 = 1, 0 + while v3 > 0: + q = u3 // v3 + u1, v1 = v1, u1 - v1*q + u3, v3 = v3, u3 - v3*q + if u3 != 1: + raise ValueError("No inverse value can be computed") + while u1<0: + u1 = u1 + v + return u1 # Given a number of bits to generate and a random generation function, # find a prime number of the appropriate size. @@ -259,7 +284,7 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): # calculate range for X # lower_bound = sqrt(2) * 2^{511 + 128*x} # upper_bound = 2^{512 + 128*x} - 1 - x = (N - 512) >> 7; + x = (N - 512) >> 7 # We need to approximate the sqrt(2) in the lower_bound by an integer # expression because floating point math overflows with these numbers lower_bound = (14142135623730950489 * (2 ** (511 + 128*x))) // 10000000000000000000 @@ -366,12 +391,12 @@ def isPrime(N, false_positive_prob=1e-6, randfunc=None): return N == 2 for p in sieve_base: if N == p: - return 1 + return True if N % p == 0: - return 0 + return False rounds = int(math.ceil(-math.log(false_positive_prob)/math.log(4))) - return _rabinMillerTest(N, rounds, randfunc) + return bool(_rabinMillerTest(N, rounds, randfunc)) # Improved conversion functions contributed by Barry Warsaw, after diff --git a/frozen_deps/Cryptodome/Util/py3compat.py b/frozen_deps/Cryptodome/Util/py3compat.py index 9a982e9..3294b66 100644 --- a/frozen_deps/Cryptodome/Util/py3compat.py +++ b/frozen_deps/Cryptodome/Util/py3compat.py @@ -87,6 +87,14 @@ if sys.version_info[0] == 2: def byte_string(s): return isinstance(s, str) + # In Python 2, a memoryview does not support concatenation + def concat_buffers(a, b): + if isinstance(a, memoryview): + a = a.tobytes() + if isinstance(b, memoryview): + b = b.tobytes() + return a + b + from StringIO import StringIO BytesIO = StringIO @@ -137,6 +145,9 @@ else: def byte_string(s): return isinstance(s, bytes) + def concat_buffers(a, b): + return a + b + from io import BytesIO from io import StringIO from sys import maxsize as maxint diff --git a/frozen_deps/Cryptodome/__init__.py b/frozen_deps/Cryptodome/__init__.py index 9c2f83b..c33481e 100644 --- a/frozen_deps/Cryptodome/__init__.py +++ b/frozen_deps/Cryptodome/__init__.py @@ -1,6 +1,6 @@ __all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util', 'Signature', 'IO', 'Math'] -version_info = (3, 15, '0') +version_info = (3, 20, '0') __version__ = ".".join([str(x) for x in version_info]) |