aboutsummaryrefslogtreecommitdiff
path: root/frozen_deps/Cryptodome/Signature
diff options
context:
space:
mode:
authorDeterminant <tederminant@gmail.com>2020-11-17 20:04:09 -0500
committerDeterminant <tederminant@gmail.com>2020-11-17 20:04:09 -0500
commitc4d90bf4ea0c5b7a016028ed994de19638d3113b (patch)
tree693279a91311155f565e90ecd2d93bf701d6d4e9 /frozen_deps/Cryptodome/Signature
parent3bef51eec2299403467e621ae660cef3f9256ac8 (diff)
support saving as a keystore file
Diffstat (limited to 'frozen_deps/Cryptodome/Signature')
-rw-r--r--frozen_deps/Cryptodome/Signature/DSS.py413
-rw-r--r--frozen_deps/Cryptodome/Signature/DSS.pyi27
-rw-r--r--frozen_deps/Cryptodome/Signature/PKCS1_PSS.py55
-rw-r--r--frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi7
-rw-r--r--frozen_deps/Cryptodome/Signature/PKCS1_v1_5.py53
-rw-r--r--frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi6
-rw-r--r--frozen_deps/Cryptodome/Signature/__init__.py36
-rw-r--r--frozen_deps/Cryptodome/Signature/pkcs1_15.py222
-rw-r--r--frozen_deps/Cryptodome/Signature/pkcs1_15.pyi17
-rw-r--r--frozen_deps/Cryptodome/Signature/pss.py386
-rw-r--r--frozen_deps/Cryptodome/Signature/pss.pyi30
11 files changed, 1252 insertions, 0 deletions
diff --git a/frozen_deps/Cryptodome/Signature/DSS.py b/frozen_deps/Cryptodome/Signature/DSS.py
new file mode 100644
index 0000000..3dcbeb4
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/DSS.py
@@ -0,0 +1,413 @@
+#
+# Signature/DSS.py : DSS.py
+#
+# ===================================================================
+#
+# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# ===================================================================
+
+__all__ = ['new']
+
+
+from Cryptodome.Util.asn1 import DerSequence
+from Cryptodome.Util.number import long_to_bytes
+from Cryptodome.Math.Numbers import Integer
+
+from Cryptodome.Hash import HMAC
+from Cryptodome.PublicKey.ECC import EccKey
+
+
+class DssSigScheme(object):
+ """A (EC)DSA signature object.
+ Do not instantiate directly.
+ Use :func:`Cryptodome.Signature.DSS.new`.
+ """
+
+ def __init__(self, key, encoding, order):
+ """Create a new Digital Signature Standard (DSS) object.
+
+ Do not instantiate this object directly,
+ use `Cryptodome.Signature.DSS.new` instead.
+ """
+
+ self._key = key
+ self._encoding = encoding
+ self._order = order
+
+ self._order_bits = self._order.size_in_bits()
+ self._order_bytes = (self._order_bits - 1) // 8 + 1
+
+ def can_sign(self):
+ """Return ``True`` if this signature object can be used
+ for signing messages."""
+
+ return self._key.has_private()
+
+ def _compute_nonce(self, msg_hash):
+ raise NotImplementedError("To be provided by subclasses")
+
+ def _valid_hash(self, msg_hash):
+ raise NotImplementedError("To be provided by subclasses")
+
+ def sign(self, msg_hash):
+ """Produce the DSA/ECDSA signature of a message.
+
+ :parameter msg_hash:
+ The hash that was carried out over the message.
+ The object belongs to the :mod:`Cryptodome.Hash` package.
+
+ Under mode *'fips-186-3'*, the hash must be a FIPS
+ approved secure hash (SHA-1 or a member of the SHA-2 family),
+ of cryptographic strength appropriate for the DSA key.
+ For instance, a 3072/256 DSA key can only be used
+ in combination with SHA-512.
+ :type msg_hash: hash object
+
+ :return: The signature as a *byte string*
+ :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key
+ :raise TypeError: if the (EC)DSA key has no private half
+ """
+
+ if not self._valid_hash(msg_hash):
+ raise ValueError("Hash is not sufficiently strong")
+
+ # Generate the nonce k (critical!)
+ nonce = self._compute_nonce(msg_hash)
+
+ # Perform signature using the raw API
+ z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
+ sig_pair = self._key._sign(z, nonce)
+
+ # Encode the signature into a single byte string
+ if self._encoding == 'binary':
+ output = b"".join([long_to_bytes(x, self._order_bytes)
+ for x in sig_pair])
+ else:
+ # Dss-sig ::= SEQUENCE {
+ # r INTEGER,
+ # s INTEGER
+ # }
+ # Ecdsa-Sig-Value ::= SEQUENCE {
+ # r INTEGER,
+ # s INTEGER
+ # }
+ output = DerSequence(sig_pair).encode()
+
+ return output
+
+ def verify(self, msg_hash, signature):
+ """Check if a certain (EC)DSA signature is authentic.
+
+ :parameter msg_hash:
+ The hash that was carried out over the message.
+ This is an object belonging to the :mod:`Cryptodome.Hash` module.
+
+ Under mode *'fips-186-3'*, the hash must be a FIPS
+ approved secure hash (SHA-1 or a member of the SHA-2 family),
+ of cryptographic strength appropriate for the DSA key.
+ For instance, a 3072/256 DSA key can only be used in
+ combination with SHA-512.
+ :type msg_hash: hash object
+
+ :parameter signature:
+ The signature that needs to be validated
+ :type signature: byte string
+
+ :raise ValueError: if the signature is not authentic
+ """
+
+ if not self._valid_hash(msg_hash):
+ raise ValueError("Hash is not sufficiently strong")
+
+ if self._encoding == 'binary':
+ if len(signature) != (2 * self._order_bytes):
+ raise ValueError("The signature is not authentic (length)")
+ r_prime, s_prime = [Integer.from_bytes(x)
+ for x in (signature[:self._order_bytes],
+ signature[self._order_bytes:])]
+ else:
+ try:
+ der_seq = DerSequence().decode(signature, strict=True)
+ except (ValueError, IndexError):
+ raise ValueError("The signature is not authentic (DER)")
+ if len(der_seq) != 2 or not der_seq.hasOnlyInts():
+ raise ValueError("The signature is not authentic (DER content)")
+ r_prime, s_prime = Integer(der_seq[0]), Integer(der_seq[1])
+
+ if not (0 < r_prime < self._order) or not (0 < s_prime < self._order):
+ raise ValueError("The signature is not authentic (d)")
+
+ z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
+ result = self._key._verify(z, (r_prime, s_prime))
+ if not result:
+ raise ValueError("The signature is not authentic")
+ # Make PyCryptodome code to fail
+ return False
+
+
+class DeterministicDsaSigScheme(DssSigScheme):
+ # Also applicable to ECDSA
+
+ def __init__(self, key, encoding, order, private_key):
+ super(DeterministicDsaSigScheme, self).__init__(key, encoding, order)
+ self._private_key = private_key
+
+ def _bits2int(self, bstr):
+ """See 2.3.2 in RFC6979"""
+
+ result = Integer.from_bytes(bstr)
+ q_len = self._order.size_in_bits()
+ b_len = len(bstr) * 8
+ if b_len > q_len:
+ # Only keep leftmost q_len bits
+ result >>= (b_len - q_len)
+ return result
+
+ def _int2octets(self, int_mod_q):
+ """See 2.3.3 in RFC6979"""
+
+ assert 0 < int_mod_q < self._order
+ return long_to_bytes(int_mod_q, self._order_bytes)
+
+ def _bits2octets(self, bstr):
+ """See 2.3.4 in RFC6979"""
+
+ z1 = self._bits2int(bstr)
+ if z1 < self._order:
+ z2 = z1
+ else:
+ z2 = z1 - self._order
+ return self._int2octets(z2)
+
+ def _compute_nonce(self, mhash):
+ """Generate k in a deterministic way"""
+
+ # See section 3.2 in RFC6979.txt
+ # Step a
+ h1 = mhash.digest()
+ # Step b
+ mask_v = b'\x01' * mhash.digest_size
+ # Step c
+ nonce_k = b'\x00' * mhash.digest_size
+
+ for int_oct in (b'\x00', b'\x01'):
+ # Step d/f
+ nonce_k = HMAC.new(nonce_k,
+ mask_v + int_oct +
+ self._int2octets(self._private_key) +
+ self._bits2octets(h1), mhash).digest()
+ # Step e/g
+ mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
+
+ nonce = -1
+ while not (0 < nonce < self._order):
+ # Step h.C (second part)
+ if nonce != -1:
+ nonce_k = HMAC.new(nonce_k, mask_v + b'\x00',
+ mhash).digest()
+ mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
+
+ # Step h.A
+ mask_t = b""
+
+ # Step h.B
+ while len(mask_t) < self._order_bytes:
+ mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
+ mask_t += mask_v
+
+ # Step h.C (first part)
+ nonce = self._bits2int(mask_t)
+ return nonce
+
+ def _valid_hash(self, msg_hash):
+ return True
+
+
+class FipsDsaSigScheme(DssSigScheme):
+
+ #: List of L (bit length of p) and N (bit length of q) combinations
+ #: that are allowed by FIPS 186-3. The security level is provided in
+ #: Table 2 of FIPS 800-57 (rev3).
+ _fips_186_3_L_N = (
+ (1024, 160), # 80 bits (SHA-1 or stronger)
+ (2048, 224), # 112 bits (SHA-224 or stronger)
+ (2048, 256), # 128 bits (SHA-256 or stronger)
+ (3072, 256) # 256 bits (SHA-512)
+ )
+
+ def __init__(self, key, encoding, order, randfunc):
+ super(FipsDsaSigScheme, self).__init__(key, encoding, order)
+ self._randfunc = randfunc
+
+ L = Integer(key.p).size_in_bits()
+ if (L, self._order_bits) not in self._fips_186_3_L_N:
+ error = ("L/N (%d, %d) is not compliant to FIPS 186-3"
+ % (L, self._order_bits))
+ raise ValueError(error)
+
+ def _compute_nonce(self, msg_hash):
+ # hash is not used
+ return Integer.random_range(min_inclusive=1,
+ max_exclusive=self._order,
+ randfunc=self._randfunc)
+
+ def _valid_hash(self, msg_hash):
+ """Verify that SHA-1, SHA-2 or SHA-3 are used"""
+ return (msg_hash.oid == "1.3.14.3.2.26" or
+ msg_hash.oid.startswith("2.16.840.1.101.3.4.2."))
+
+
+class FipsEcDsaSigScheme(DssSigScheme):
+
+ def __init__(self, key, encoding, order, randfunc):
+ super(FipsEcDsaSigScheme, self).__init__(key, encoding, order)
+ self._randfunc = randfunc
+
+ def _compute_nonce(self, msg_hash):
+ return Integer.random_range(min_inclusive=1,
+ max_exclusive=self._key._curve.order,
+ randfunc=self._randfunc)
+
+ def _valid_hash(self, msg_hash):
+ """Verify that SHA-[23] (256|384|512) bits are used to
+ match the security of P-256 (128 bits), P-384 (192 bits)
+ or P-521 (256 bits)"""
+
+ modulus_bits = self._key.pointQ.size_in_bits()
+
+ sha256 = ( "2.16.840.1.101.3.4.2.1", "2.16.840.1.101.3.4.2.8" )
+ sha384 = ( "2.16.840.1.101.3.4.2.2", "2.16.840.1.101.3.4.2.9" )
+ sha512 = ( "2.16.840.1.101.3.4.2.3", "2.16.840.1.101.3.4.2.10")
+
+ if msg_hash.oid in sha256:
+ return modulus_bits <= 256
+ elif msg_hash.oid in sha384:
+ return modulus_bits <= 384
+ else:
+ return msg_hash.oid in sha512
+
+
+def new(key, mode, encoding='binary', randfunc=None):
+ """Create a signature object :class:`DSS_SigScheme` that
+ can perform (EC)DSA signature or verification.
+
+ .. note::
+ Refer to `NIST SP 800 Part 1 Rev 4`_ (or newer release) for an
+ overview of the recommended key lengths.
+
+ :parameter key:
+ The key to use for computing the signature (*private* keys only)
+ or verifying one: it must be either
+ :class:`Cryptodome.PublicKey.DSA` or :class:`Cryptodome.PublicKey.ECC`.
+
+ For DSA keys, let ``L`` and ``N`` be the bit lengths of the modulus ``p``
+ and of ``q``: the pair ``(L,N)`` must appear in the following list,
+ in compliance to section 4.2 of `FIPS 186-4`_:
+
+ - (1024, 160) *legacy only; do not create new signatures with this*
+ - (2048, 224) *deprecated; do not create new signatures with this*
+ - (2048, 256)
+ - (3072, 256)
+
+ For ECC, only keys over P-256, P384, and P-521 are accepted.
+ :type key:
+ a key object
+
+ :parameter mode:
+ The parameter can take these values:
+
+ - *'fips-186-3'*. The signature generation is randomized and carried out
+ according to `FIPS 186-3`_: the nonce ``k`` is taken from the RNG.
+ - *'deterministic-rfc6979'*. The signature generation is not
+ randomized. See RFC6979_.
+ :type mode:
+ string
+
+ :parameter encoding:
+ How the signature is encoded. This value determines the output of
+ :meth:`sign` and the input to :meth:`verify`.
+
+ The following values are accepted:
+
+ - *'binary'* (default), the signature is the raw concatenation
+ of ``r`` and ``s``. It is defined in the IEEE P.1363 standard.
+
+ For DSA, the size in bytes of the signature is ``N/4`` bytes
+ (e.g. 64 for ``N=256``).
+
+ For ECDSA, the signature is always twice the length of a point
+ coordinate (e.g. 64 bytes for P-256).
+
+ - *'der'*, the signature is a ASN.1 DER SEQUENCE
+ with two INTEGERs (``r`` and ``s``). It is defined in RFC3279_.
+ The size of the signature is variable.
+ :type encoding: string
+
+ :parameter randfunc:
+ A function that returns random *byte strings*, of a given length.
+ If omitted, the internal RNG is used.
+ Only applicable for the *'fips-186-3'* mode.
+ :type randfunc: callable
+
+ .. _FIPS 186-3: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
+ .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
+ .. _NIST SP 800 Part 1 Rev 4: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf
+ .. _RFC6979: http://tools.ietf.org/html/rfc6979
+ .. _RFC3279: https://tools.ietf.org/html/rfc3279#section-2.2.2
+ """
+
+ # The goal of the 'mode' parameter is to avoid to
+ # have the current version of the standard as default.
+ #
+ # Over time, such version will be superseded by (for instance)
+ # FIPS 186-4 and it will be odd to have -3 as default.
+
+ if encoding not in ('binary', 'der'):
+ raise ValueError("Unknown encoding '%s'" % encoding)
+
+ if isinstance(key, EccKey):
+ order = key._curve.order
+ private_key_attr = 'd'
+ else:
+ order = Integer(key.q)
+ private_key_attr = 'x'
+
+ if key.has_private():
+ private_key = getattr(key, private_key_attr)
+ else:
+ private_key = None
+
+ if mode == 'deterministic-rfc6979':
+ return DeterministicDsaSigScheme(key, encoding, order, private_key)
+ elif mode == 'fips-186-3':
+ if isinstance(key, EccKey):
+ return FipsEcDsaSigScheme(key, encoding, order, randfunc)
+ else:
+ return FipsDsaSigScheme(key, encoding, order, randfunc)
+ else:
+ raise ValueError("Unknown DSS mode '%s'" % mode)
diff --git a/frozen_deps/Cryptodome/Signature/DSS.pyi b/frozen_deps/Cryptodome/Signature/DSS.pyi
new file mode 100644
index 0000000..52ecc8f
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/DSS.pyi
@@ -0,0 +1,27 @@
+from typing import Union, Optional, Callable
+from typing_extensions import Protocol
+
+from Cryptodome.PublicKey.DSA import DsaKey
+from Cryptodome.PublicKey.ECC import EccKey
+
+class Hash(Protocol):
+ def digest(self) -> bytes: ...
+
+__all__ = ['new']
+
+class DssSigScheme:
+ def __init__(self, key: Union[DsaKey, EccKey], encoding: str, order: int) -> None: ...
+ def can_sign(self) -> bool: ...
+ def sign(self, msg_hash: Hash) -> bytes: ...
+ def verify(self, msg_hash: Hash, signature: bytes) -> bool: ...
+
+class DeterministicDsaSigScheme(DssSigScheme):
+ def __init__(self, key, encoding, order, private_key) -> None: ...
+
+class FipsDsaSigScheme(DssSigScheme):
+ def __init__(self, key: DsaKey, encoding: str, order: int, randfunc: Callable) -> None: ...
+
+class FipsEcDsaSigScheme(DssSigScheme):
+ def __init__(self, key: EccKey, encoding: str, order: int, randfunc: Callable) -> None: ...
+
+def new(key: Union[DsaKey, EccKey], mode: str, encoding: Optional[str]='binary', randfunc: Optional[Callable]=None) -> Union[DeterministicDsaSigScheme, FipsDsaSigScheme, FipsEcDsaSigScheme]: ...
diff --git a/frozen_deps/Cryptodome/Signature/PKCS1_PSS.py b/frozen_deps/Cryptodome/Signature/PKCS1_PSS.py
new file mode 100644
index 0000000..1e7e5b5
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/PKCS1_PSS.py
@@ -0,0 +1,55 @@
+# ===================================================================
+#
+# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# ===================================================================
+
+"""
+Legacy module for PKCS#1 PSS signatures.
+
+:undocumented: __package__
+"""
+
+import types
+
+from Cryptodome.Signature import pss
+
+
+def _pycrypto_verify(self, hash_object, signature):
+ try:
+ self._verify(hash_object, signature)
+ except (ValueError, TypeError):
+ return False
+ return True
+
+
+def new(rsa_key, mgfunc=None, saltLen=None, randfunc=None):
+ pkcs1 = pss.new(rsa_key, mask_func=mgfunc,
+ salt_bytes=saltLen, rand_func=randfunc)
+ pkcs1._verify = pkcs1.verify
+ pkcs1.verify = types.MethodType(_pycrypto_verify, pkcs1)
+ return pkcs1
diff --git a/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi b/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi
new file mode 100644
index 0000000..7ed68e6
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/PKCS1_PSS.pyi
@@ -0,0 +1,7 @@
+from typing import Optional, Callable
+
+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: ...
diff --git a/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.py b/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.py
new file mode 100644
index 0000000..d560663
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.py
@@ -0,0 +1,53 @@
+# ===================================================================
+#
+# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# ===================================================================
+
+"""
+Legacy module for PKCS#1 v1.5 signatures.
+
+:undocumented: __package__
+"""
+
+import types
+
+from Cryptodome.Signature import pkcs1_15
+
+def _pycrypto_verify(self, hash_object, signature):
+ try:
+ self._verify(hash_object, signature)
+ except (ValueError, TypeError):
+ return False
+ return True
+
+def new(rsa_key):
+ pkcs1 = pkcs1_15.new(rsa_key)
+ pkcs1._verify = pkcs1.verify
+ pkcs1.verify = types.MethodType(_pycrypto_verify, pkcs1)
+ return pkcs1
+
diff --git a/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi b/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi
new file mode 100644
index 0000000..5851e5b
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/PKCS1_v1_5.pyi
@@ -0,0 +1,6 @@
+from Cryptodome.PublicKey.RSA import RsaKey
+
+from Cryptodome.Signature.pkcs1_15 import PKCS115_SigScheme
+
+
+def new(rsa_key: RsaKey) -> PKCS115_SigScheme: ... \ No newline at end of file
diff --git a/frozen_deps/Cryptodome/Signature/__init__.py b/frozen_deps/Cryptodome/Signature/__init__.py
new file mode 100644
index 0000000..da028a5
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/__init__.py
@@ -0,0 +1,36 @@
+# ===================================================================
+#
+# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# ===================================================================
+
+"""Digital signature protocols
+
+A collection of standardized protocols to carry out digital signatures.
+"""
+
+__all__ = ['PKCS1_v1_5', 'PKCS1_PSS', 'DSS', 'pkcs1_15', 'pss']
diff --git a/frozen_deps/Cryptodome/Signature/pkcs1_15.py b/frozen_deps/Cryptodome/Signature/pkcs1_15.py
new file mode 100644
index 0000000..f572f85
--- /dev/null
+++ b/frozen_deps/Cryptodome/Signature/pkcs1_15.py
@@ -0,0 +1,222 @@
+# ===================================================================
+#
+# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# ===================================================================
+
+import Cryptodome.Util.number
+from Cryptodome.Util.number import ceil_div, bytes_to_long, long_to_bytes
+from Cryptodome.Util.asn1 import DerSequence, DerNull, DerOctetString, DerObjectId
+
+class PKCS115_SigScheme:
+ """A signature object for ``RSASSA-PKCS1-v1_5``.
+ Do not instantiate directly.
+ Use :func:`Cryptodome.Signature.pkcs1_15.new`.
+ """
+
+ def __init__(self, rsa_key):
+ """Initialize this PKCS#1 v1.5 signature scheme object.
+
+ :Parameters:
+ rsa_key : an RSA key object
+ Creation of signatures is only possible if this is a *private*
+ RSA key. Verification of signatures is always possible.
+ """
+ self._key = rsa_key
+
+ def can_sign(self):
+ """Return ``True`` if this object can be used to sign messages."""
+ return self._key.has_private()
+
+ def sign(self, msg_hash):
+ """Create the PKCS#1 v1.5 signature of a message.
+
+ This function is also called ``RSASSA-PKCS1-V1_5-SIGN`` and
+ it is specified in
+ `section 8.2.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#page-36>`_.
+
+ :parameter msg_hash:
+ This is an object from the :mod:`Cryptodome.Hash` package.
+ It has been used to digest the message to sign.
+ :type msg_hash: hash object
+
+ :return: the signature encoded as a *byte string*.
+ :raise ValueError: if the RSA key is not long enough for the given hash algorithm.
+ :raise TypeError: if the RSA key has no private half.
+ """
+
+ # See 8.2.1 in RFC3447
+ modBits = Cryptodome.Util.number.size(self._key.n)
+ k = ceil_div(modBits,8) # Convert from bits to bytes
+
+ # Step 1
+ 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)
+ return signature
+
+ def verify(self, msg_hash, signature):
+ """Check if the PKCS#1 v1.5 signature over a message is valid.
+
+ This function is also called ``RSASSA-PKCS1-V1_5-VERIFY`` and
+ it is specified in
+ `section 8.2.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#page-37>`_.
+
+ :parameter msg_hash:
+ The hash that was carried out over the message. This is an object
+ belonging to the :mod:`Cryptodome.Hash` module.
+ :type parameter: hash object
+
+ :parameter signature:
+ The signature that needs to be validated.
+ :type signature: byte string
+
+ :raise ValueError: if the signature is not valid.
+ """
+
+ # See 8.2.2 in RFC3447
+ modBits = Cryptodome.Util.number.size(self._key.n)
+ k = ceil_div(modBits, 8) # Convert from bits to bytes
+
+ # Step 1
+ if len(signature) != k:
+ raise ValueError("Invalid signature")
+ # Step 2a (O2SIP)
+ signature_int = bytes_to_long(signature)
+ # Step 2b (RSAVP1)
+ em_int = self._key._encrypt(signature_int)
+ # Step 2c (I2OSP)
+ em1 = long_to_bytes(em_int, k)
+ # Step 3
+ try:
+ possible_em1 = [ _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, True) ]
+ # MD2/4/5 hashes always require NULL params in AlgorithmIdentifier.
+ # For all others, it is optional.
+ try:
+ algorithm_is_md = msg_hash.oid.startswith('1.2.840.113549.2.')
+ except AttributeError:
+ algorithm_is_md = False
+ if not algorithm_is_md: # MD2/MD4/MD5
+ possible_em1.append(_EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, False))
+ except ValueError:
+ raise ValueError("Invalid signature")
+ # Step 4
+ # By comparing the full encodings (as opposed to checking each
+ # of its components one at a time) we avoid attacks to the padding
+ # scheme like Bleichenbacher's (see http://www.mail-archive.com/cryptography@metzdowd.com/msg06537).
+ #
+ if em1 not in possible_em1:
+ raise ValueError("Invalid signature")
+ pass
+
+
+def _EMSA_PKCS1_V1_5_ENCODE(msg_hash, emLen, with_hash_parameters=True):
+ """
+ Implement the ``EMSA-PKCS1-V1_5-ENCODE`` function, as defined
+ in PKCS#1 v2.1 (RFC3447, 9.2).
+
+ ``_EMSA-PKCS1-V1_5-ENCODE`` actually accepts the message ``M`` as input,
+ and hash it internally. Here, we expect that the message has already
+ been hashed instead.
+
+ :Parameters:
+ msg_hash : hash object
+ The hash object that holds the digest of the message being signed.
+ emLen : int
+ The length the final encoding must have, in bytes.
+ with_hash_parameters : bool
+ If True (default), include NULL parameters for the hash
+ algorithm in the ``digestAlgorithm`` SEQUENCE.
+
+ :attention: the early standard (RFC2313) stated that ``DigestInfo``
+ had to be BER-encoded. This means that old signatures
+ might have length tags in indefinite form, which
+ is not supported in DER. Such encoding cannot be
+ reproduced by this function.
+
+ :Return: An ``emLen`` byte long string that encodes the hash.
+ """
+
+ # First, build the ASN.1 DER object DigestInfo:
+ #
+ # DigestInfo ::= SEQUENCE {
+ # digestAlgorithm AlgorithmIdentifier,
+ # digest OCTET STRING
+ # }
+ #
+ # where digestAlgorithm identifies the hash function and shall be an
+ # algorithm ID with an OID in the set PKCS1-v1-5DigestAlgorithms.
+ #
+ # PKCS1-v1-5DigestAlgorithms ALGORITHM-IDENTIFIER ::= {
+ # { OID id-md2 PARAMETERS NULL }|
+ # { OID id-md5 PARAMETERS NULL }|
+ # { OID id-sha1 PARAMETERS NULL }|
+ # { OID id-sha256 PARAMETERS NULL }|
+ # { OID id-sha384 PARAMETERS NULL }|
+ # { OID id-sha512 PARAMETERS NULL }
+ # }
+ #
+ # Appendix B.1 also says that for SHA-1/-2 algorithms, the parameters
+ # should be omitted. They may be present, but when they are, they shall
+ # have NULL value.
+
+ digestAlgo = DerSequence([ DerObjectId(msg_hash.oid).encode() ])
+
+ if with_hash_parameters:
+ digestAlgo.append(DerNull().encode())
+
+ digest = DerOctetString(msg_hash.digest())
+ digestInfo = DerSequence([
+ digestAlgo.encode(),
+ digest.encode()
+ ]).encode()
+
+ # We