Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- wemm/lib/python3.10/site-packages/Crypto/IO/PKCS8.py +226 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/Numbers.py +47 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/Numbers.pyi +2 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/Primality.py +369 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/Primality.pyi +18 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerBase.py +412 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerBase.pyi +67 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerCustom.py +162 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerNative.py +382 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerNative.pyi +3 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/Numbers.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/Primality.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerBase.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerCustom.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerGMP.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerNative.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_AES.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_CBC.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_ChaCha20.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_DES.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_DES3.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_GCM.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/common.py +510 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/test_ChaCha20.py +529 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/test_pkcs1_15.py +283 -0
- wemm/lib/python3.10/site-packages/Crypto/SelfTest/PublicKey/test_ElGamal.py +217 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/DSS.py +403 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/DSS.pyi +27 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/DSS.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/PKCS1_v1_5.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/pkcs1_15.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/pss.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/eddsa.py +343 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/eddsa.pyi +21 -0
- wemm/lib/python3.10/site-packages/Crypto/Signature/pss.py +387 -0
- wemm/lib/python3.10/site-packages/_yaml/__init__.py +33 -0
- wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/METADATA +246 -0
- wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/RECORD +56 -0
- wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/REQUESTED +0 -0
- wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/WHEEL +4 -0
- wemm/lib/python3.10/site-packages/botocore/data/amplifybackend/2020-08-11/endpoint-rule-set-1.json.gz +3 -0
- wemm/lib/python3.10/site-packages/botocore/data/location/2020-11-19/endpoint-rule-set-1.json.gz +3 -0
- wemm/lib/python3.10/site-packages/tokenizers/__init__.py +100 -0
- wemm/lib/python3.10/site-packages/tokenizers/decoders/__init__.py +14 -0
- wemm/lib/python3.10/site-packages/tokenizers/implementations/__init__.py +6 -0
- wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/bert_wordpiece.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/sentencepiece_bpe.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/sentencepiece_unigram.cpython-310.pyc +0 -0
wemm/lib/python3.10/site-packages/Crypto/IO/PKCS8.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# PublicKey/PKCS8.py : PKCS#8 functions
|
| 3 |
+
#
|
| 4 |
+
# ===================================================================
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 7 |
+
# All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Redistribution and use in source and binary forms, with or without
|
| 10 |
+
# modification, are permitted provided that the following conditions
|
| 11 |
+
# are met:
|
| 12 |
+
#
|
| 13 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 14 |
+
# notice, this list of conditions and the following disclaimer.
|
| 15 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 16 |
+
# notice, this list of conditions and the following disclaimer in
|
| 17 |
+
# the documentation and/or other materials provided with the
|
| 18 |
+
# distribution.
|
| 19 |
+
#
|
| 20 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 21 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 22 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 23 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 24 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 25 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 26 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 27 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 28 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 29 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 30 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 31 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 32 |
+
# ===================================================================
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
from Crypto.Util.py3compat import *
|
| 36 |
+
|
| 37 |
+
from Crypto.Util.asn1 import (
|
| 38 |
+
DerNull,
|
| 39 |
+
DerSequence,
|
| 40 |
+
DerObjectId,
|
| 41 |
+
DerOctetString,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
from Crypto.IO._PBES import PBES1, PBES2, PbesError
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
__all__ = ['wrap', 'unwrap']
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def wrap(private_key, key_oid, passphrase=None, protection=None,
|
| 51 |
+
prot_params=None, key_params=DerNull(), randfunc=None):
|
| 52 |
+
"""Wrap a private key into a PKCS#8 blob (clear or encrypted).
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
|
| 56 |
+
private_key (bytes):
|
| 57 |
+
The private key encoded in binary form. The actual encoding is
|
| 58 |
+
algorithm specific. In most cases, it is DER.
|
| 59 |
+
|
| 60 |
+
key_oid (string):
|
| 61 |
+
The object identifier (OID) of the private key to wrap.
|
| 62 |
+
It is a dotted string, like ``'1.2.840.113549.1.1.1'`` (for RSA keys)
|
| 63 |
+
or ``'1.2.840.10045.2.1'`` (for ECC keys).
|
| 64 |
+
|
| 65 |
+
Keyword Args:
|
| 66 |
+
|
| 67 |
+
passphrase (bytes or string):
|
| 68 |
+
The secret passphrase from which the wrapping key is derived.
|
| 69 |
+
Set it only if encryption is required.
|
| 70 |
+
|
| 71 |
+
protection (string):
|
| 72 |
+
The identifier of the algorithm to use for securely wrapping the key.
|
| 73 |
+
Refer to :ref:`the encryption parameters<enc_params>` .
|
| 74 |
+
The default value is ``'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'``.
|
| 75 |
+
|
| 76 |
+
prot_params (dictionary):
|
| 77 |
+
Parameters for the key derivation function (KDF).
|
| 78 |
+
Refer to :ref:`the encryption parameters<enc_params>` .
|
| 79 |
+
|
| 80 |
+
key_params (DER object or None):
|
| 81 |
+
The ``parameters`` field to use in the ``AlgorithmIdentifier``
|
| 82 |
+
SEQUENCE. If ``None``, no ``parameters`` field will be added.
|
| 83 |
+
By default, the ASN.1 type ``NULL`` is used.
|
| 84 |
+
|
| 85 |
+
randfunc (callable):
|
| 86 |
+
Random number generation function; it should accept a single integer
|
| 87 |
+
N and return a string of random data, N bytes long.
|
| 88 |
+
If not specified, a new RNG will be instantiated
|
| 89 |
+
from :mod:`Crypto.Random`.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
bytes: The PKCS#8-wrapped private key (possibly encrypted).
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
#
|
| 96 |
+
# PrivateKeyInfo ::= SEQUENCE {
|
| 97 |
+
# version Version,
|
| 98 |
+
# privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
|
| 99 |
+
# privateKey PrivateKey,
|
| 100 |
+
# attributes [0] IMPLICIT Attributes OPTIONAL
|
| 101 |
+
# }
|
| 102 |
+
#
|
| 103 |
+
if key_params is None:
|
| 104 |
+
algorithm = DerSequence([DerObjectId(key_oid)])
|
| 105 |
+
else:
|
| 106 |
+
algorithm = DerSequence([DerObjectId(key_oid), key_params])
|
| 107 |
+
|
| 108 |
+
pk_info = DerSequence([
|
| 109 |
+
0,
|
| 110 |
+
algorithm,
|
| 111 |
+
DerOctetString(private_key)
|
| 112 |
+
])
|
| 113 |
+
pk_info_der = pk_info.encode()
|
| 114 |
+
|
| 115 |
+
if passphrase is None:
|
| 116 |
+
return pk_info_der
|
| 117 |
+
|
| 118 |
+
if not passphrase:
|
| 119 |
+
raise ValueError("Empty passphrase")
|
| 120 |
+
|
| 121 |
+
# Encryption with PBES2
|
| 122 |
+
passphrase = tobytes(passphrase)
|
| 123 |
+
if protection is None:
|
| 124 |
+
protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
|
| 125 |
+
return PBES2.encrypt(pk_info_der, passphrase,
|
| 126 |
+
protection, prot_params, randfunc)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def unwrap(p8_private_key, passphrase=None):
|
| 130 |
+
"""Unwrap a private key from a PKCS#8 blob (clear or encrypted).
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
p8_private_key (bytes):
|
| 134 |
+
The private key wrapped into a PKCS#8 container, DER encoded.
|
| 135 |
+
|
| 136 |
+
Keyword Args:
|
| 137 |
+
passphrase (byte string or string):
|
| 138 |
+
The passphrase to use to decrypt the blob (if it is encrypted).
|
| 139 |
+
|
| 140 |
+
Return:
|
| 141 |
+
A tuple containing
|
| 142 |
+
|
| 143 |
+
#. the algorithm identifier of the wrapped key (OID, dotted string)
|
| 144 |
+
#. the private key (bytes, DER encoded)
|
| 145 |
+
#. the associated parameters (bytes, DER encoded) or ``None``
|
| 146 |
+
|
| 147 |
+
Raises:
|
| 148 |
+
ValueError : if decoding fails
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
if passphrase is not None:
|
| 152 |
+
passphrase = tobytes(passphrase)
|
| 153 |
+
|
| 154 |
+
found = False
|
| 155 |
+
try:
|
| 156 |
+
p8_private_key = PBES1.decrypt(p8_private_key, passphrase)
|
| 157 |
+
found = True
|
| 158 |
+
except PbesError as e:
|
| 159 |
+
error_str = "PBES1[%s]" % str(e)
|
| 160 |
+
except ValueError:
|
| 161 |
+
error_str = "PBES1[Invalid]"
|
| 162 |
+
|
| 163 |
+
if not found:
|
| 164 |
+
try:
|
| 165 |
+
p8_private_key = PBES2.decrypt(p8_private_key, passphrase)
|
| 166 |
+
found = True
|
| 167 |
+
except PbesError as e:
|
| 168 |
+
error_str += ",PBES2[%s]" % str(e)
|
| 169 |
+
except ValueError:
|
| 170 |
+
error_str += ",PBES2[Invalid]"
|
| 171 |
+
|
| 172 |
+
if not found:
|
| 173 |
+
raise ValueError("Error decoding PKCS#8 (%s)" % error_str)
|
| 174 |
+
|
| 175 |
+
pk_info = DerSequence().decode(p8_private_key, nr_elements=(2, 3, 4, 5))
|
| 176 |
+
if len(pk_info) == 2 and not passphrase:
|
| 177 |
+
raise ValueError("Not a valid clear PKCS#8 structure "
|
| 178 |
+
"(maybe it is encrypted?)")
|
| 179 |
+
|
| 180 |
+
# RFC5208, PKCS#8, version is v1(0)
|
| 181 |
+
#
|
| 182 |
+
# PrivateKeyInfo ::= SEQUENCE {
|
| 183 |
+
# version Version,
|
| 184 |
+
# privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
|
| 185 |
+
# privateKey PrivateKey,
|
| 186 |
+
# attributes [0] IMPLICIT Attributes OPTIONAL
|
| 187 |
+
# }
|
| 188 |
+
#
|
| 189 |
+
# RFC5915, Asymmetric Key Package, version is v2(1)
|
| 190 |
+
#
|
| 191 |
+
# OneAsymmetricKey ::= SEQUENCE {
|
| 192 |
+
# version Version,
|
| 193 |
+
# privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
|
| 194 |
+
# privateKey PrivateKey,
|
| 195 |
+
# attributes [0] Attributes OPTIONAL,
|
| 196 |
+
# ...,
|
| 197 |
+
# [[2: publicKey [1] PublicKey OPTIONAL ]],
|
| 198 |
+
# ...
|
| 199 |
+
# }
|
| 200 |
+
|
| 201 |
+
if pk_info[0] == 0:
|
| 202 |
+
if len(pk_info) not in (3, 4):
|
| 203 |
+
raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
|
| 204 |
+
elif pk_info[0] == 1:
|
| 205 |
+
if len(pk_info) not in (3, 4, 5):
|
| 206 |
+
raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
|
| 207 |
+
else:
|
| 208 |
+
raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
|
| 209 |
+
|
| 210 |
+
algo = DerSequence().decode(pk_info[1], nr_elements=(1, 2))
|
| 211 |
+
algo_oid = DerObjectId().decode(algo[0]).value
|
| 212 |
+
if len(algo) == 1:
|
| 213 |
+
algo_params = None
|
| 214 |
+
else:
|
| 215 |
+
try:
|
| 216 |
+
DerNull().decode(algo[1])
|
| 217 |
+
algo_params = None
|
| 218 |
+
except:
|
| 219 |
+
algo_params = algo[1]
|
| 220 |
+
|
| 221 |
+
# PrivateKey ::= OCTET STRING
|
| 222 |
+
private_key = DerOctetString().decode(pk_info[2]).payload
|
| 223 |
+
|
| 224 |
+
# We ignore attributes and (for v2 only) publickey
|
| 225 |
+
|
| 226 |
+
return (algo_oid, private_key, algo_params)
|
wemm/lib/python3.10/site-packages/Crypto/Math/Numbers.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
__all__ = ["Integer"]
|
| 32 |
+
|
| 33 |
+
import os
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
if os.getenv("PYCRYPTODOME_DISABLE_GMP"):
|
| 37 |
+
raise ImportError()
|
| 38 |
+
|
| 39 |
+
from Crypto.Math._IntegerGMP import IntegerGMP as Integer
|
| 40 |
+
from Crypto.Math._IntegerGMP import implementation as _implementation
|
| 41 |
+
except (ImportError, OSError, AttributeError):
|
| 42 |
+
try:
|
| 43 |
+
from Crypto.Math._IntegerCustom import IntegerCustom as Integer
|
| 44 |
+
from Crypto.Math._IntegerCustom import implementation as _implementation
|
| 45 |
+
except (ImportError, OSError):
|
| 46 |
+
from Crypto.Math._IntegerNative import IntegerNative as Integer
|
| 47 |
+
_implementation = {}
|
wemm/lib/python3.10/site-packages/Crypto/Math/Numbers.pyi
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from Crypto.Math._IntegerBase import IntegerBase as Integer
|
| 2 |
+
__all__ = ['Integer']
|
wemm/lib/python3.10/site-packages/Crypto/Math/Primality.py
ADDED
|
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
"""Functions to create and test prime numbers.
|
| 32 |
+
|
| 33 |
+
:undocumented: __package__
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from Crypto import Random
|
| 37 |
+
from Crypto.Math.Numbers import Integer
|
| 38 |
+
|
| 39 |
+
from Crypto.Util.py3compat import iter_range
|
| 40 |
+
|
| 41 |
+
COMPOSITE = 0
|
| 42 |
+
PROBABLY_PRIME = 1
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def miller_rabin_test(candidate, iterations, randfunc=None):
|
| 46 |
+
"""Perform a Miller-Rabin primality test on an integer.
|
| 47 |
+
|
| 48 |
+
The test is specified in Section C.3.1 of `FIPS PUB 186-4`__.
|
| 49 |
+
|
| 50 |
+
:Parameters:
|
| 51 |
+
candidate : integer
|
| 52 |
+
The number to test for primality.
|
| 53 |
+
iterations : integer
|
| 54 |
+
The maximum number of iterations to perform before
|
| 55 |
+
declaring a candidate a probable prime.
|
| 56 |
+
randfunc : callable
|
| 57 |
+
An RNG function where bases are taken from.
|
| 58 |
+
|
| 59 |
+
:Returns:
|
| 60 |
+
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
|
| 61 |
+
|
| 62 |
+
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
if not isinstance(candidate, Integer):
|
| 66 |
+
candidate = Integer(candidate)
|
| 67 |
+
|
| 68 |
+
if candidate in (1, 2, 3, 5):
|
| 69 |
+
return PROBABLY_PRIME
|
| 70 |
+
|
| 71 |
+
if candidate.is_even():
|
| 72 |
+
return COMPOSITE
|
| 73 |
+
|
| 74 |
+
one = Integer(1)
|
| 75 |
+
minus_one = Integer(candidate - 1)
|
| 76 |
+
|
| 77 |
+
if randfunc is None:
|
| 78 |
+
randfunc = Random.new().read
|
| 79 |
+
|
| 80 |
+
# Step 1 and 2
|
| 81 |
+
m = Integer(minus_one)
|
| 82 |
+
a = 0
|
| 83 |
+
while m.is_even():
|
| 84 |
+
m >>= 1
|
| 85 |
+
a += 1
|
| 86 |
+
|
| 87 |
+
# Skip step 3
|
| 88 |
+
|
| 89 |
+
# Step 4
|
| 90 |
+
for i in iter_range(iterations):
|
| 91 |
+
|
| 92 |
+
# Step 4.1-2
|
| 93 |
+
base = 1
|
| 94 |
+
while base in (one, minus_one):
|
| 95 |
+
base = Integer.random_range(min_inclusive=2,
|
| 96 |
+
max_inclusive=candidate - 2,
|
| 97 |
+
randfunc=randfunc)
|
| 98 |
+
assert(2 <= base <= candidate - 2)
|
| 99 |
+
|
| 100 |
+
# Step 4.3-4.4
|
| 101 |
+
z = pow(base, m, candidate)
|
| 102 |
+
if z in (one, minus_one):
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
# Step 4.5
|
| 106 |
+
for j in iter_range(1, a):
|
| 107 |
+
z = pow(z, 2, candidate)
|
| 108 |
+
if z == minus_one:
|
| 109 |
+
break
|
| 110 |
+
if z == one:
|
| 111 |
+
return COMPOSITE
|
| 112 |
+
else:
|
| 113 |
+
return COMPOSITE
|
| 114 |
+
|
| 115 |
+
# Step 5
|
| 116 |
+
return PROBABLY_PRIME
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def lucas_test(candidate):
|
| 120 |
+
"""Perform a Lucas primality test on an integer.
|
| 121 |
+
|
| 122 |
+
The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.
|
| 123 |
+
|
| 124 |
+
:Parameters:
|
| 125 |
+
candidate : integer
|
| 126 |
+
The number to test for primality.
|
| 127 |
+
|
| 128 |
+
:Returns:
|
| 129 |
+
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
|
| 130 |
+
|
| 131 |
+
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
if not isinstance(candidate, Integer):
|
| 135 |
+
candidate = Integer(candidate)
|
| 136 |
+
|
| 137 |
+
# Step 1
|
| 138 |
+
if candidate in (1, 2, 3, 5):
|
| 139 |
+
return PROBABLY_PRIME
|
| 140 |
+
if candidate.is_even() or candidate.is_perfect_square():
|
| 141 |
+
return COMPOSITE
|
| 142 |
+
|
| 143 |
+
# Step 2
|
| 144 |
+
def alternate():
|
| 145 |
+
value = 5
|
| 146 |
+
while True:
|
| 147 |
+
yield value
|
| 148 |
+
if value > 0:
|
| 149 |
+
value += 2
|
| 150 |
+
else:
|
| 151 |
+
value -= 2
|
| 152 |
+
value = -value
|
| 153 |
+
|
| 154 |
+
for D in alternate():
|
| 155 |
+
if candidate in (D, -D):
|
| 156 |
+
continue
|
| 157 |
+
js = Integer.jacobi_symbol(D, candidate)
|
| 158 |
+
if js == 0:
|
| 159 |
+
return COMPOSITE
|
| 160 |
+
if js == -1:
|
| 161 |
+
break
|
| 162 |
+
# Found D. P=1 and Q=(1-D)/4 (note that Q is guaranteed to be an integer)
|
| 163 |
+
|
| 164 |
+
# Step 3
|
| 165 |
+
# This is \delta(n) = n - jacobi(D/n)
|
| 166 |
+
K = candidate + 1
|
| 167 |
+
# Step 4
|
| 168 |
+
r = K.size_in_bits() - 1
|
| 169 |
+
# Step 5
|
| 170 |
+
# U_1=1 and V_1=P
|
| 171 |
+
U_i = Integer(1)
|
| 172 |
+
V_i = Integer(1)
|
| 173 |
+
U_temp = Integer(0)
|
| 174 |
+
V_temp = Integer(0)
|
| 175 |
+
# Step 6
|
| 176 |
+
for i in iter_range(r - 1, -1, -1):
|
| 177 |
+
# Square
|
| 178 |
+
# U_temp = U_i * V_i % candidate
|
| 179 |
+
U_temp.set(U_i)
|
| 180 |
+
U_temp *= V_i
|
| 181 |
+
U_temp %= candidate
|
| 182 |
+
# V_temp = (((V_i ** 2 + (U_i ** 2 * D)) * K) >> 1) % candidate
|
| 183 |
+
V_temp.set(U_i)
|
| 184 |
+
V_temp *= U_i
|
| 185 |
+
V_temp *= D
|
| 186 |
+
V_temp.multiply_accumulate(V_i, V_i)
|
| 187 |
+
if V_temp.is_odd():
|
| 188 |
+
V_temp += candidate
|
| 189 |
+
V_temp >>= 1
|
| 190 |
+
V_temp %= candidate
|
| 191 |
+
# Multiply
|
| 192 |
+
if K.get_bit(i):
|
| 193 |
+
# U_i = (((U_temp + V_temp) * K) >> 1) % candidate
|
| 194 |
+
U_i.set(U_temp)
|
| 195 |
+
U_i += V_temp
|
| 196 |
+
if U_i.is_odd():
|
| 197 |
+
U_i += candidate
|
| 198 |
+
U_i >>= 1
|
| 199 |
+
U_i %= candidate
|
| 200 |
+
# V_i = (((V_temp + U_temp * D) * K) >> 1) % candidate
|
| 201 |
+
V_i.set(V_temp)
|
| 202 |
+
V_i.multiply_accumulate(U_temp, D)
|
| 203 |
+
if V_i.is_odd():
|
| 204 |
+
V_i += candidate
|
| 205 |
+
V_i >>= 1
|
| 206 |
+
V_i %= candidate
|
| 207 |
+
else:
|
| 208 |
+
U_i.set(U_temp)
|
| 209 |
+
V_i.set(V_temp)
|
| 210 |
+
# Step 7
|
| 211 |
+
if U_i == 0:
|
| 212 |
+
return PROBABLY_PRIME
|
| 213 |
+
return COMPOSITE
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
from Crypto.Util.number import sieve_base as _sieve_base_large
|
| 217 |
+
## The optimal number of small primes to use for the sieve
|
| 218 |
+
## is probably dependent on the platform and the candidate size
|
| 219 |
+
_sieve_base = set(_sieve_base_large[:100])
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def test_probable_prime(candidate, randfunc=None):
|
| 223 |
+
"""Test if a number is prime.
|
| 224 |
+
|
| 225 |
+
A number is qualified as prime if it passes a certain
|
| 226 |
+
number of Miller-Rabin tests (dependent on the size
|
| 227 |
+
of the number, but such that probability of a false
|
| 228 |
+
positive is less than 10^-30) and a single Lucas test.
|
| 229 |
+
|
| 230 |
+
For instance, a 1024-bit candidate will need to pass
|
| 231 |
+
4 Miller-Rabin tests.
|
| 232 |
+
|
| 233 |
+
:Parameters:
|
| 234 |
+
candidate : integer
|
| 235 |
+
The number to test for primality.
|
| 236 |
+
randfunc : callable
|
| 237 |
+
The routine to draw random bytes from to select Miller-Rabin bases.
|
| 238 |
+
:Returns:
|
| 239 |
+
``PROBABLE_PRIME`` if the number if prime with very high probability.
|
| 240 |
+
``COMPOSITE`` if the number is a composite.
|
| 241 |
+
For efficiency reasons, ``COMPOSITE`` is also returned for small primes.
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
if randfunc is None:
|
| 245 |
+
randfunc = Random.new().read
|
| 246 |
+
|
| 247 |
+
if not isinstance(candidate, Integer):
|
| 248 |
+
candidate = Integer(candidate)
|
| 249 |
+
|
| 250 |
+
# First, check trial division by the smallest primes
|
| 251 |
+
if int(candidate) in _sieve_base:
|
| 252 |
+
return PROBABLY_PRIME
|
| 253 |
+
try:
|
| 254 |
+
map(candidate.fail_if_divisible_by, _sieve_base)
|
| 255 |
+
except ValueError:
|
| 256 |
+
return COMPOSITE
|
| 257 |
+
|
| 258 |
+
# These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30,
|
| 259 |
+
# with p(k, t) being the probability that a randomly chosen k-bit number
|
| 260 |
+
# is composite but still survives t MR iterations.
|
| 261 |
+
mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10),
|
| 262 |
+
(620, 7), (740, 6), (890, 5), (1200, 4),
|
| 263 |
+
(1700, 3), (3700, 2))
|
| 264 |
+
|
| 265 |
+
bit_size = candidate.size_in_bits()
|
| 266 |
+
try:
|
| 267 |
+
mr_iterations = list(filter(lambda x: bit_size < x[0],
|
| 268 |
+
mr_ranges))[0][1]
|
| 269 |
+
except IndexError:
|
| 270 |
+
mr_iterations = 1
|
| 271 |
+
|
| 272 |
+
if miller_rabin_test(candidate, mr_iterations,
|
| 273 |
+
randfunc=randfunc) == COMPOSITE:
|
| 274 |
+
return COMPOSITE
|
| 275 |
+
if lucas_test(candidate) == COMPOSITE:
|
| 276 |
+
return COMPOSITE
|
| 277 |
+
return PROBABLY_PRIME
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def generate_probable_prime(**kwargs):
|
| 281 |
+
"""Generate a random probable prime.
|
| 282 |
+
|
| 283 |
+
The prime will not have any specific properties
|
| 284 |
+
(e.g. it will not be a *strong* prime).
|
| 285 |
+
|
| 286 |
+
Random numbers are evaluated for primality until one
|
| 287 |
+
passes all tests, consisting of a certain number of
|
| 288 |
+
Miller-Rabin tests with random bases followed by
|
| 289 |
+
a single Lucas test.
|
| 290 |
+
|
| 291 |
+
The number of Miller-Rabin iterations is chosen such that
|
| 292 |
+
the probability that the output number is a non-prime is
|
| 293 |
+
less than 1E-30 (roughly 2^{-100}).
|
| 294 |
+
|
| 295 |
+
This approach is compliant to `FIPS PUB 186-4`__.
|
| 296 |
+
|
| 297 |
+
:Keywords:
|
| 298 |
+
exact_bits : integer
|
| 299 |
+
The desired size in bits of the probable prime.
|
| 300 |
+
It must be at least 160.
|
| 301 |
+
randfunc : callable
|
| 302 |
+
An RNG function where candidate primes are taken from.
|
| 303 |
+
prime_filter : callable
|
| 304 |
+
A function that takes an Integer as parameter and returns
|
| 305 |
+
True if the number can be passed to further primality tests,
|
| 306 |
+
False if it should be immediately discarded.
|
| 307 |
+
|
| 308 |
+
:Return:
|
| 309 |
+
A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1).
|
| 310 |
+
|
| 311 |
+
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
exact_bits = kwargs.pop("exact_bits", None)
|
| 315 |
+
randfunc = kwargs.pop("randfunc", None)
|
| 316 |
+
prime_filter = kwargs.pop("prime_filter", lambda x: True)
|
| 317 |
+
if kwargs:
|
| 318 |
+
raise ValueError("Unknown parameters: " + kwargs.keys())
|
| 319 |
+
|
| 320 |
+
if exact_bits is None:
|
| 321 |
+
raise ValueError("Missing exact_bits parameter")
|
| 322 |
+
if exact_bits < 160:
|
| 323 |
+
raise ValueError("Prime number is not big enough.")
|
| 324 |
+
|
| 325 |
+
if randfunc is None:
|
| 326 |
+
randfunc = Random.new().read
|
| 327 |
+
|
| 328 |
+
result = COMPOSITE
|
| 329 |
+
while result == COMPOSITE:
|
| 330 |
+
candidate = Integer.random(exact_bits=exact_bits,
|
| 331 |
+
randfunc=randfunc) | 1
|
| 332 |
+
if not prime_filter(candidate):
|
| 333 |
+
continue
|
| 334 |
+
result = test_probable_prime(candidate, randfunc)
|
| 335 |
+
return candidate
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def generate_probable_safe_prime(**kwargs):
|
| 339 |
+
"""Generate a random, probable safe prime.
|
| 340 |
+
|
| 341 |
+
Note this operation is much slower than generating a simple prime.
|
| 342 |
+
|
| 343 |
+
:Keywords:
|
| 344 |
+
exact_bits : integer
|
| 345 |
+
The desired size in bits of the probable safe prime.
|
| 346 |
+
randfunc : callable
|
| 347 |
+
An RNG function where candidate primes are taken from.
|
| 348 |
+
|
| 349 |
+
:Return:
|
| 350 |
+
A probable safe prime in the range
|
| 351 |
+
2^exact_bits > p > 2^(exact_bits-1).
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
exact_bits = kwargs.pop("exact_bits", None)
|
| 355 |
+
randfunc = kwargs.pop("randfunc", None)
|
| 356 |
+
if kwargs:
|
| 357 |
+
raise ValueError("Unknown parameters: " + kwargs.keys())
|
| 358 |
+
|
| 359 |
+
if randfunc is None:
|
| 360 |
+
randfunc = Random.new().read
|
| 361 |
+
|
| 362 |
+
result = COMPOSITE
|
| 363 |
+
while result == COMPOSITE:
|
| 364 |
+
q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc)
|
| 365 |
+
candidate = q * 2 + 1
|
| 366 |
+
if candidate.size_in_bits() != exact_bits:
|
| 367 |
+
continue
|
| 368 |
+
result = test_probable_prime(candidate, randfunc=randfunc)
|
| 369 |
+
return candidate
|
wemm/lib/python3.10/site-packages/Crypto/Math/Primality.pyi
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional, Union, Set
|
| 2 |
+
|
| 3 |
+
PrimeResult = int
|
| 4 |
+
|
| 5 |
+
COMPOSITE: PrimeResult
|
| 6 |
+
PROBABLY_PRIME: PrimeResult
|
| 7 |
+
|
| 8 |
+
def miller_rabin_test(candidate: int, iterations: int, randfunc: Optional[Callable[[int],bytes]]=None) -> PrimeResult: ...
|
| 9 |
+
def lucas_test(candidate: int) -> PrimeResult: ...
|
| 10 |
+
_sieve_base: Set[int]
|
| 11 |
+
def test_probable_prime(candidate: int, randfunc: Optional[Callable[[int],bytes]]=None) -> PrimeResult: ...
|
| 12 |
+
def generate_probable_prime(*,
|
| 13 |
+
exact_bits: int = ...,
|
| 14 |
+
randfunc: Callable[[int],bytes] = ...,
|
| 15 |
+
prime_filter: Callable[[int],bool] = ...) -> int: ...
|
| 16 |
+
def generate_probable_safe_prime(*,
|
| 17 |
+
exact_bits: int = ...,
|
| 18 |
+
randfunc: Callable[[int],bytes] = ...) -> int: ...
|
wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerBase.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2018, Helder Eijs <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
import abc
|
| 32 |
+
|
| 33 |
+
from Crypto.Util.py3compat import iter_range, bord, bchr, ABC
|
| 34 |
+
|
| 35 |
+
from Crypto import Random
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class IntegerBase(ABC):
|
| 39 |
+
|
| 40 |
+
# Conversions
|
| 41 |
+
@abc.abstractmethod
|
| 42 |
+
def __int__(self):
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
@abc.abstractmethod
|
| 46 |
+
def __str__(self):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
@abc.abstractmethod
|
| 50 |
+
def __repr__(self):
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
@abc.abstractmethod
|
| 54 |
+
def to_bytes(self, block_size=0, byteorder='big'):
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
@staticmethod
|
| 58 |
+
@abc.abstractmethod
|
| 59 |
+
def from_bytes(byte_string, byteorder='big'):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
# Relations
|
| 63 |
+
@abc.abstractmethod
|
| 64 |
+
def __eq__(self, term):
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
@abc.abstractmethod
|
| 68 |
+
def __ne__(self, term):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
@abc.abstractmethod
|
| 72 |
+
def __lt__(self, term):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
@abc.abstractmethod
|
| 76 |
+
def __le__(self, term):
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
@abc.abstractmethod
|
| 80 |
+
def __gt__(self, term):
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
@abc.abstractmethod
|
| 84 |
+
def __ge__(self, term):
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
@abc.abstractmethod
|
| 88 |
+
def __nonzero__(self):
|
| 89 |
+
pass
|
| 90 |
+
__bool__ = __nonzero__
|
| 91 |
+
|
| 92 |
+
@abc.abstractmethod
|
| 93 |
+
def is_negative(self):
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
# Arithmetic operations
|
| 97 |
+
@abc.abstractmethod
|
| 98 |
+
def __add__(self, term):
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
@abc.abstractmethod
|
| 102 |
+
def __sub__(self, term):
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
@abc.abstractmethod
|
| 106 |
+
def __mul__(self, factor):
|
| 107 |
+
pass
|
| 108 |
+
|
| 109 |
+
@abc.abstractmethod
|
| 110 |
+
def __floordiv__(self, divisor):
|
| 111 |
+
pass
|
| 112 |
+
|
| 113 |
+
@abc.abstractmethod
|
| 114 |
+
def __mod__(self, divisor):
|
| 115 |
+
pass
|
| 116 |
+
|
| 117 |
+
@abc.abstractmethod
|
| 118 |
+
def inplace_pow(self, exponent, modulus=None):
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
@abc.abstractmethod
|
| 122 |
+
def __pow__(self, exponent, modulus=None):
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
@abc.abstractmethod
|
| 126 |
+
def __abs__(self):
|
| 127 |
+
pass
|
| 128 |
+
|
| 129 |
+
@abc.abstractmethod
|
| 130 |
+
def sqrt(self, modulus=None):
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
@abc.abstractmethod
|
| 134 |
+
def __iadd__(self, term):
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
@abc.abstractmethod
|
| 138 |
+
def __isub__(self, term):
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
@abc.abstractmethod
|
| 142 |
+
def __imul__(self, term):
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
@abc.abstractmethod
|
| 146 |
+
def __imod__(self, term):
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
# Boolean/bit operations
|
| 150 |
+
@abc.abstractmethod
|
| 151 |
+
def __and__(self, term):
|
| 152 |
+
pass
|
| 153 |
+
|
| 154 |
+
@abc.abstractmethod
|
| 155 |
+
def __or__(self, term):
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
@abc.abstractmethod
|
| 159 |
+
def __rshift__(self, pos):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
@abc.abstractmethod
|
| 163 |
+
def __irshift__(self, pos):
|
| 164 |
+
pass
|
| 165 |
+
|
| 166 |
+
@abc.abstractmethod
|
| 167 |
+
def __lshift__(self, pos):
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
@abc.abstractmethod
|
| 171 |
+
def __ilshift__(self, pos):
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
@abc.abstractmethod
|
| 175 |
+
def get_bit(self, n):
|
| 176 |
+
pass
|
| 177 |
+
|
| 178 |
+
# Extra
|
| 179 |
+
@abc.abstractmethod
|
| 180 |
+
def is_odd(self):
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
@abc.abstractmethod
|
| 184 |
+
def is_even(self):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
@abc.abstractmethod
|
| 188 |
+
def size_in_bits(self):
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
@abc.abstractmethod
|
| 192 |
+
def size_in_bytes(self):
|
| 193 |
+
pass
|
| 194 |
+
|
| 195 |
+
@abc.abstractmethod
|
| 196 |
+
def is_perfect_square(self):
|
| 197 |
+
pass
|
| 198 |
+
|
| 199 |
+
@abc.abstractmethod
|
| 200 |
+
def fail_if_divisible_by(self, small_prime):
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
@abc.abstractmethod
|
| 204 |
+
def multiply_accumulate(self, a, b):
|
| 205 |
+
pass
|
| 206 |
+
|
| 207 |
+
@abc.abstractmethod
|
| 208 |
+
def set(self, source):
|
| 209 |
+
pass
|
| 210 |
+
|
| 211 |
+
@abc.abstractmethod
|
| 212 |
+
def inplace_inverse(self, modulus):
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
@abc.abstractmethod
|
| 216 |
+
def inverse(self, modulus):
|
| 217 |
+
pass
|
| 218 |
+
|
| 219 |
+
@abc.abstractmethod
|
| 220 |
+
def gcd(self, term):
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
@abc.abstractmethod
|
| 224 |
+
def lcm(self, term):
|
| 225 |
+
pass
|
| 226 |
+
|
| 227 |
+
@staticmethod
|
| 228 |
+
@abc.abstractmethod
|
| 229 |
+
def jacobi_symbol(a, n):
|
| 230 |
+
pass
|
| 231 |
+
|
| 232 |
+
@staticmethod
|
| 233 |
+
def _tonelli_shanks(n, p):
|
| 234 |
+
"""Tonelli-shanks algorithm for computing the square root
|
| 235 |
+
of n modulo a prime p.
|
| 236 |
+
|
| 237 |
+
n must be in the range [0..p-1].
|
| 238 |
+
p must be at least even.
|
| 239 |
+
|
| 240 |
+
The return value r is the square root of modulo p. If non-zero,
|
| 241 |
+
another solution will also exist (p-r).
|
| 242 |
+
|
| 243 |
+
Note we cannot assume that p is really a prime: if it's not,
|
| 244 |
+
we can either raise an exception or return the correct value.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
# See https://rosettacode.org/wiki/Tonelli-Shanks_algorithm
|
| 248 |
+
|
| 249 |
+
if n in (0, 1):
|
| 250 |
+
return n
|
| 251 |
+
|
| 252 |
+
if p % 4 == 3:
|
| 253 |
+
root = pow(n, (p + 1) // 4, p)
|
| 254 |
+
if pow(root, 2, p) != n:
|
| 255 |
+
raise ValueError("Cannot compute square root")
|
| 256 |
+
return root
|
| 257 |
+
|
| 258 |
+
s = 1
|
| 259 |
+
q = (p - 1) // 2
|
| 260 |
+
while not (q & 1):
|
| 261 |
+
s += 1
|
| 262 |
+
q >>= 1
|
| 263 |
+
|
| 264 |
+
z = n.__class__(2)
|
| 265 |
+
while True:
|
| 266 |
+
euler = pow(z, (p - 1) // 2, p)
|
| 267 |
+
if euler == 1:
|
| 268 |
+
z += 1
|
| 269 |
+
continue
|
| 270 |
+
if euler == p - 1:
|
| 271 |
+
break
|
| 272 |
+
# Most probably p is not a prime
|
| 273 |
+
raise ValueError("Cannot compute square root")
|
| 274 |
+
|
| 275 |
+
m = s
|
| 276 |
+
c = pow(z, q, p)
|
| 277 |
+
t = pow(n, q, p)
|
| 278 |
+
r = pow(n, (q + 1) // 2, p)
|
| 279 |
+
|
| 280 |
+
while t != 1:
|
| 281 |
+
for i in iter_range(0, m):
|
| 282 |
+
if pow(t, 2**i, p) == 1:
|
| 283 |
+
break
|
| 284 |
+
if i == m:
|
| 285 |
+
raise ValueError("Cannot compute square root of %d mod %d" % (n, p))
|
| 286 |
+
b = pow(c, 2**(m - i - 1), p)
|
| 287 |
+
m = i
|
| 288 |
+
c = b**2 % p
|
| 289 |
+
t = (t * b**2) % p
|
| 290 |
+
r = (r * b) % p
|
| 291 |
+
|
| 292 |
+
if pow(r, 2, p) != n:
|
| 293 |
+
raise ValueError("Cannot compute square root")
|
| 294 |
+
|
| 295 |
+
return r
|
| 296 |
+
|
| 297 |
+
@classmethod
|
| 298 |
+
def random(cls, **kwargs):
|
| 299 |
+
"""Generate a random natural integer of a certain size.
|
| 300 |
+
|
| 301 |
+
:Keywords:
|
| 302 |
+
exact_bits : positive integer
|
| 303 |
+
The length in bits of the resulting random Integer number.
|
| 304 |
+
The number is guaranteed to fulfil the relation:
|
| 305 |
+
|
| 306 |
+
2^bits > result >= 2^(bits - 1)
|
| 307 |
+
|
| 308 |
+
max_bits : positive integer
|
| 309 |
+
The maximum length in bits of the resulting random Integer number.
|
| 310 |
+
The number is guaranteed to fulfil the relation:
|
| 311 |
+
|
| 312 |
+
2^bits > result >=0
|
| 313 |
+
|
| 314 |
+
randfunc : callable
|
| 315 |
+
A function that returns a random byte string. The length of the
|
| 316 |
+
byte string is passed as parameter. Optional.
|
| 317 |
+
If not provided (or ``None``), randomness is read from the system RNG.
|
| 318 |
+
|
| 319 |
+
:Return: a Integer object
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
exact_bits = kwargs.pop("exact_bits", None)
|
| 323 |
+
max_bits = kwargs.pop("max_bits", None)
|
| 324 |
+
randfunc = kwargs.pop("randfunc", None)
|
| 325 |
+
|
| 326 |
+
if randfunc is None:
|
| 327 |
+
randfunc = Random.new().read
|
| 328 |
+
|
| 329 |
+
if exact_bits is None and max_bits is None:
|
| 330 |
+
raise ValueError("Either 'exact_bits' or 'max_bits' must be specified")
|
| 331 |
+
|
| 332 |
+
if exact_bits is not None and max_bits is not None:
|
| 333 |
+
raise ValueError("'exact_bits' and 'max_bits' are mutually exclusive")
|
| 334 |
+
|
| 335 |
+
bits = exact_bits or max_bits
|
| 336 |
+
bytes_needed = ((bits - 1) // 8) + 1
|
| 337 |
+
significant_bits_msb = 8 - (bytes_needed * 8 - bits)
|
| 338 |
+
msb = bord(randfunc(1)[0])
|
| 339 |
+
if exact_bits is not None:
|
| 340 |
+
msb |= 1 << (significant_bits_msb - 1)
|
| 341 |
+
msb &= (1 << significant_bits_msb) - 1
|
| 342 |
+
|
| 343 |
+
return cls.from_bytes(bchr(msb) + randfunc(bytes_needed - 1))
|
| 344 |
+
|
| 345 |
+
@classmethod
|
| 346 |
+
def random_range(cls, **kwargs):
|
| 347 |
+
"""Generate a random integer within a given internal.
|
| 348 |
+
|
| 349 |
+
:Keywords:
|
| 350 |
+
min_inclusive : integer
|
| 351 |
+
The lower end of the interval (inclusive).
|
| 352 |
+
max_inclusive : integer
|
| 353 |
+
The higher end of the interval (inclusive).
|
| 354 |
+
max_exclusive : integer
|
| 355 |
+
The higher end of the interval (exclusive).
|
| 356 |
+
randfunc : callable
|
| 357 |
+
A function that returns a random byte string. The length of the
|
| 358 |
+
byte string is passed as parameter. Optional.
|
| 359 |
+
If not provided (or ``None``), randomness is read from the system RNG.
|
| 360 |
+
:Returns:
|
| 361 |
+
An Integer randomly taken in the given interval.
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
min_inclusive = kwargs.pop("min_inclusive", None)
|
| 365 |
+
max_inclusive = kwargs.pop("max_inclusive", None)
|
| 366 |
+
max_exclusive = kwargs.pop("max_exclusive", None)
|
| 367 |
+
randfunc = kwargs.pop("randfunc", None)
|
| 368 |
+
|
| 369 |
+
if kwargs:
|
| 370 |
+
raise ValueError("Unknown keywords: " + str(kwargs.keys))
|
| 371 |
+
if None not in (max_inclusive, max_exclusive):
|
| 372 |
+
raise ValueError("max_inclusive and max_exclusive cannot be both"
|
| 373 |
+
" specified")
|
| 374 |
+
if max_exclusive is not None:
|
| 375 |
+
max_inclusive = max_exclusive - 1
|
| 376 |
+
if None in (min_inclusive, max_inclusive):
|
| 377 |
+
raise ValueError("Missing keyword to identify the interval")
|
| 378 |
+
|
| 379 |
+
if randfunc is None:
|
| 380 |
+
randfunc = Random.new().read
|
| 381 |
+
|
| 382 |
+
norm_maximum = max_inclusive - min_inclusive
|
| 383 |
+
bits_needed = cls(norm_maximum).size_in_bits()
|
| 384 |
+
|
| 385 |
+
norm_candidate = -1
|
| 386 |
+
while not 0 <= norm_candidate <= norm_maximum:
|
| 387 |
+
norm_candidate = cls.random(
|
| 388 |
+
max_bits=bits_needed,
|
| 389 |
+
randfunc=randfunc
|
| 390 |
+
)
|
| 391 |
+
return norm_candidate + min_inclusive
|
| 392 |
+
|
| 393 |
+
@staticmethod
|
| 394 |
+
@abc.abstractmethod
|
| 395 |
+
def _mult_modulo_bytes(term1, term2, modulus):
|
| 396 |
+
"""Multiply two integers, take the modulo, and encode as big endian.
|
| 397 |
+
This specialized method is used for RSA decryption.
|
| 398 |
+
|
| 399 |
+
Args:
|
| 400 |
+
term1 : integer
|
| 401 |
+
The first term of the multiplication, non-negative.
|
| 402 |
+
term2 : integer
|
| 403 |
+
The second term of the multiplication, non-negative.
|
| 404 |
+
modulus: integer
|
| 405 |
+
The modulus, a positive odd number.
|
| 406 |
+
:Returns:
|
| 407 |
+
A byte string, with the result of the modular multiplication
|
| 408 |
+
encoded in big endian mode.
|
| 409 |
+
It is as long as the modulus would be, with zero padding
|
| 410 |
+
on the left if needed.
|
| 411 |
+
"""
|
| 412 |
+
pass
|
wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerBase.pyi
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Union, Callable
|
| 2 |
+
|
| 3 |
+
RandFunc = Callable[[int],int]
|
| 4 |
+
|
| 5 |
+
class IntegerBase:
|
| 6 |
+
|
| 7 |
+
def __init__(self, value: Union[IntegerBase, int]): ...
|
| 8 |
+
|
| 9 |
+
def __int__(self) -> int: ...
|
| 10 |
+
def __str__(self) -> str: ...
|
| 11 |
+
def __repr__(self) -> str: ...
|
| 12 |
+
def to_bytes(self, block_size: Optional[int]=0, byteorder: str= ...) -> bytes: ...
|
| 13 |
+
@staticmethod
|
| 14 |
+
def from_bytes(byte_string: bytes, byteorder: Optional[str] = ...) -> IntegerBase: ...
|
| 15 |
+
def __eq__(self, term: object) -> bool: ...
|
| 16 |
+
def __ne__(self, term: object) -> bool: ...
|
| 17 |
+
def __lt__(self, term: Union[IntegerBase, int]) -> bool: ...
|
| 18 |
+
def __le__(self, term: Union[IntegerBase, int]) -> bool: ...
|
| 19 |
+
def __gt__(self, term: Union[IntegerBase, int]) -> bool: ...
|
| 20 |
+
def __ge__(self, term: Union[IntegerBase, int]) -> bool: ...
|
| 21 |
+
def __nonzero__(self) -> bool: ...
|
| 22 |
+
def is_negative(self) -> bool: ...
|
| 23 |
+
def __add__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 24 |
+
def __sub__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 25 |
+
def __mul__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 26 |
+
def __floordiv__(self, divisor: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 27 |
+
def __mod__(self, divisor: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 28 |
+
def inplace_pow(self, exponent: int, modulus: Optional[Union[IntegerBase, int]]=None) -> IntegerBase: ...
|
| 29 |
+
def __pow__(self, exponent: int, modulus: Optional[int]) -> IntegerBase: ...
|
| 30 |
+
def __abs__(self) -> IntegerBase: ...
|
| 31 |
+
def sqrt(self, modulus: Optional[int]) -> IntegerBase: ...
|
| 32 |
+
def __iadd__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 33 |
+
def __isub__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 34 |
+
def __imul__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 35 |
+
def __imod__(self, divisor: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 36 |
+
def __and__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 37 |
+
def __or__(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 38 |
+
def __rshift__(self, pos: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 39 |
+
def __irshift__(self, pos: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 40 |
+
def __lshift__(self, pos: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 41 |
+
def __ilshift__(self, pos: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 42 |
+
def get_bit(self, n: int) -> bool: ...
|
| 43 |
+
def is_odd(self) -> bool: ...
|
| 44 |
+
def is_even(self) -> bool: ...
|
| 45 |
+
def size_in_bits(self) -> int: ...
|
| 46 |
+
def size_in_bytes(self) -> int: ...
|
| 47 |
+
def is_perfect_square(self) -> bool: ...
|
| 48 |
+
def fail_if_divisible_by(self, small_prime: Union[IntegerBase, int]) -> None: ...
|
| 49 |
+
def multiply_accumulate(self, a: Union[IntegerBase, int], b: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 50 |
+
def set(self, source: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 51 |
+
def inplace_inverse(self, modulus: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 52 |
+
def inverse(self, modulus: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 53 |
+
def gcd(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 54 |
+
def lcm(self, term: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 55 |
+
@staticmethod
|
| 56 |
+
def jacobi_symbol(a: Union[IntegerBase, int], n: Union[IntegerBase, int]) -> IntegerBase: ...
|
| 57 |
+
@staticmethod
|
| 58 |
+
def _tonelli_shanks(n: Union[IntegerBase, int], p: Union[IntegerBase, int]) -> IntegerBase : ...
|
| 59 |
+
@classmethod
|
| 60 |
+
def random(cls, **kwargs: Union[int,RandFunc]) -> IntegerBase : ...
|
| 61 |
+
@classmethod
|
| 62 |
+
def random_range(cls, **kwargs: Union[int,RandFunc]) -> IntegerBase : ...
|
| 63 |
+
@staticmethod
|
| 64 |
+
def _mult_modulo_bytes(term1: Union[IntegerBase, int],
|
| 65 |
+
term2: Union[IntegerBase, int],
|
| 66 |
+
modulus: Union[IntegerBase, int]) -> bytes: ...
|
| 67 |
+
|
wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerCustom.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2018, Helder Eijs <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
from ._IntegerNative import IntegerNative
|
| 32 |
+
|
| 33 |
+
from Crypto.Util.number import long_to_bytes, bytes_to_long
|
| 34 |
+
|
| 35 |
+
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
|
| 36 |
+
create_string_buffer,
|
| 37 |
+
get_raw_buffer, backend,
|
| 38 |
+
c_size_t, c_ulonglong)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
from Crypto.Random.random import getrandbits
|
| 42 |
+
|
| 43 |
+
c_defs = """
|
| 44 |
+
int monty_pow(uint8_t *out,
|
| 45 |
+
const uint8_t *base,
|
| 46 |
+
const uint8_t *exp,
|
| 47 |
+
const uint8_t *modulus,
|
| 48 |
+
size_t len,
|
| 49 |
+
uint64_t seed);
|
| 50 |
+
|
| 51 |
+
int monty_multiply(uint8_t *out,
|
| 52 |
+
const uint8_t *term1,
|
| 53 |
+
const uint8_t *term2,
|
| 54 |
+
const uint8_t *modulus,
|
| 55 |
+
size_t len);
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_raw_montgomery = load_pycryptodome_raw_lib("Crypto.Math._modexp", c_defs)
|
| 60 |
+
implementation = {"library": "custom", "api": backend}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class IntegerCustom(IntegerNative):
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def from_bytes(byte_string, byteorder='big'):
|
| 67 |
+
if byteorder == 'big':
|
| 68 |
+
pass
|
| 69 |
+
elif byteorder == 'little':
|
| 70 |
+
byte_string = bytearray(byte_string)
|
| 71 |
+
byte_string.reverse()
|
| 72 |
+
else:
|
| 73 |
+
raise ValueError("Incorrect byteorder")
|
| 74 |
+
return IntegerCustom(bytes_to_long(byte_string))
|
| 75 |
+
|
| 76 |
+
def inplace_pow(self, exponent, modulus=None):
|
| 77 |
+
exp_value = int(exponent)
|
| 78 |
+
if exp_value < 0:
|
| 79 |
+
raise ValueError("Exponent must not be negative")
|
| 80 |
+
|
| 81 |
+
# No modular reduction
|
| 82 |
+
if modulus is None:
|
| 83 |
+
self._value = pow(self._value, exp_value)
|
| 84 |
+
return self
|
| 85 |
+
|
| 86 |
+
# With modular reduction
|
| 87 |
+
mod_value = int(modulus)
|
| 88 |
+
if mod_value < 0:
|
| 89 |
+
raise ValueError("Modulus must be positive")
|
| 90 |
+
if mod_value == 0:
|
| 91 |
+
raise ZeroDivisionError("Modulus cannot be zero")
|
| 92 |
+
|
| 93 |
+
# C extension only works with odd moduli
|
| 94 |
+
if (mod_value & 1) == 0:
|
| 95 |
+
self._value = pow(self._value, exp_value, mod_value)
|
| 96 |
+
return self
|
| 97 |
+
|
| 98 |
+
# C extension only works with bases smaller than modulus
|
| 99 |
+
if self._value >= mod_value:
|
| 100 |
+
self._value %= mod_value
|
| 101 |
+
|
| 102 |
+
max_len = len(long_to_bytes(max(self._value, exp_value, mod_value)))
|
| 103 |
+
|
| 104 |
+
base_b = long_to_bytes(self._value, max_len)
|
| 105 |
+
exp_b = long_to_bytes(exp_value, max_len)
|
| 106 |
+
modulus_b = long_to_bytes(mod_value, max_len)
|
| 107 |
+
|
| 108 |
+
out = create_string_buffer(max_len)
|
| 109 |
+
|
| 110 |
+
error = _raw_montgomery.monty_pow(
|
| 111 |
+
out,
|
| 112 |
+
base_b,
|
| 113 |
+
exp_b,
|
| 114 |
+
modulus_b,
|
| 115 |
+
c_size_t(max_len),
|
| 116 |
+
c_ulonglong(getrandbits(64))
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
if error:
|
| 120 |
+
raise ValueError("monty_pow failed with error: %d" % error)
|
| 121 |
+
|
| 122 |
+
result = bytes_to_long(get_raw_buffer(out))
|
| 123 |
+
self._value = result
|
| 124 |
+
return self
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def _mult_modulo_bytes(term1, term2, modulus):
|
| 128 |
+
|
| 129 |
+
# With modular reduction
|
| 130 |
+
mod_value = int(modulus)
|
| 131 |
+
if mod_value < 0:
|
| 132 |
+
raise ValueError("Modulus must be positive")
|
| 133 |
+
if mod_value == 0:
|
| 134 |
+
raise ZeroDivisionError("Modulus cannot be zero")
|
| 135 |
+
|
| 136 |
+
# C extension only works with odd moduli
|
| 137 |
+
if (mod_value & 1) == 0:
|
| 138 |
+
raise ValueError("Odd modulus is required")
|
| 139 |
+
|
| 140 |
+
# C extension only works with non-negative terms smaller than modulus
|
| 141 |
+
if term1 >= mod_value or term1 < 0:
|
| 142 |
+
term1 %= mod_value
|
| 143 |
+
if term2 >= mod_value or term2 < 0:
|
| 144 |
+
term2 %= mod_value
|
| 145 |
+
|
| 146 |
+
modulus_b = long_to_bytes(mod_value)
|
| 147 |
+
numbers_len = len(modulus_b)
|
| 148 |
+
term1_b = long_to_bytes(term1, numbers_len)
|
| 149 |
+
term2_b = long_to_bytes(term2, numbers_len)
|
| 150 |
+
out = create_string_buffer(numbers_len)
|
| 151 |
+
|
| 152 |
+
error = _raw_montgomery.monty_multiply(
|
| 153 |
+
out,
|
| 154 |
+
term1_b,
|
| 155 |
+
term2_b,
|
| 156 |
+
modulus_b,
|
| 157 |
+
c_size_t(numbers_len)
|
| 158 |
+
)
|
| 159 |
+
if error:
|
| 160 |
+
raise ValueError("monty_multiply failed with error: %d" % error)
|
| 161 |
+
|
| 162 |
+
return get_raw_buffer(out)
|
wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerNative.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
from ._IntegerBase import IntegerBase
|
| 32 |
+
|
| 33 |
+
from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse, GCD
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class IntegerNative(IntegerBase):
|
| 37 |
+
"""A class to model a natural integer (including zero)"""
|
| 38 |
+
|
| 39 |
+
def __init__(self, value):
|
| 40 |
+
if isinstance(value, float):
|
| 41 |
+
raise ValueError("A floating point type is not a natural number")
|
| 42 |
+
try:
|
| 43 |
+
self._value = value._value
|
| 44 |
+
except AttributeError:
|
| 45 |
+
self._value = value
|
| 46 |
+
|
| 47 |
+
# Conversions
|
| 48 |
+
def __int__(self):
|
| 49 |
+
return self._value
|
| 50 |
+
|
| 51 |
+
def __str__(self):
|
| 52 |
+
return str(int(self))
|
| 53 |
+
|
| 54 |
+
def __repr__(self):
|
| 55 |
+
return "Integer(%s)" % str(self)
|
| 56 |
+
|
| 57 |
+
# Only Python 2.x
|
| 58 |
+
def __hex__(self):
|
| 59 |
+
return hex(self._value)
|
| 60 |
+
|
| 61 |
+
# Only Python 3.x
|
| 62 |
+
def __index__(self):
|
| 63 |
+
return int(self._value)
|
| 64 |
+
|
| 65 |
+
def to_bytes(self, block_size=0, byteorder='big'):
|
| 66 |
+
if self._value < 0:
|
| 67 |
+
raise ValueError("Conversion only valid for non-negative numbers")
|
| 68 |
+
result = long_to_bytes(self._value, block_size)
|
| 69 |
+
if len(result) > block_size > 0:
|
| 70 |
+
raise ValueError("Value too large to encode")
|
| 71 |
+
if byteorder == 'big':
|
| 72 |
+
pass
|
| 73 |
+
elif byteorder == 'little':
|
| 74 |
+
result = bytearray(result)
|
| 75 |
+
result.reverse()
|
| 76 |
+
result = bytes(result)
|
| 77 |
+
else:
|
| 78 |
+
raise ValueError("Incorrect byteorder")
|
| 79 |
+
return result
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def from_bytes(cls, byte_string, byteorder='big'):
|
| 83 |
+
if byteorder == 'big':
|
| 84 |
+
pass
|
| 85 |
+
elif byteorder == 'little':
|
| 86 |
+
byte_string = bytearray(byte_string)
|
| 87 |
+
byte_string.reverse()
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError("Incorrect byteorder")
|
| 90 |
+
return cls(bytes_to_long(byte_string))
|
| 91 |
+
|
| 92 |
+
# Relations
|
| 93 |
+
def __eq__(self, term):
|
| 94 |
+
if term is None:
|
| 95 |
+
return False
|
| 96 |
+
return self._value == int(term)
|
| 97 |
+
|
| 98 |
+
def __ne__(self, term):
|
| 99 |
+
return not self.__eq__(term)
|
| 100 |
+
|
| 101 |
+
def __lt__(self, term):
|
| 102 |
+
return self._value < int(term)
|
| 103 |
+
|
| 104 |
+
def __le__(self, term):
|
| 105 |
+
return self.__lt__(term) or self.__eq__(term)
|
| 106 |
+
|
| 107 |
+
def __gt__(self, term):
|
| 108 |
+
return not self.__le__(term)
|
| 109 |
+
|
| 110 |
+
def __ge__(self, term):
|
| 111 |
+
return not self.__lt__(term)
|
| 112 |
+
|
| 113 |
+
def __nonzero__(self):
|
| 114 |
+
return self._value != 0
|
| 115 |
+
__bool__ = __nonzero__
|
| 116 |
+
|
| 117 |
+
def is_negative(self):
|
| 118 |
+
return self._value < 0
|
| 119 |
+
|
| 120 |
+
# Arithmetic operations
|
| 121 |
+
def __add__(self, term):
|
| 122 |
+
try:
|
| 123 |
+
return self.__class__(self._value + int(term))
|
| 124 |
+
except (ValueError, AttributeError, TypeError):
|
| 125 |
+
return NotImplemented
|
| 126 |
+
|
| 127 |
+
def __sub__(self, term):
|
| 128 |
+
try:
|
| 129 |
+
return self.__class__(self._value - int(term))
|
| 130 |
+
except (ValueError, AttributeError, TypeError):
|
| 131 |
+
return NotImplemented
|
| 132 |
+
|
| 133 |
+
def __mul__(self, factor):
|
| 134 |
+
try:
|
| 135 |
+
return self.__class__(self._value * int(factor))
|
| 136 |
+
except (ValueError, AttributeError, TypeError):
|
| 137 |
+
return NotImplemented
|
| 138 |
+
|
| 139 |
+
def __floordiv__(self, divisor):
|
| 140 |
+
return self.__class__(self._value // int(divisor))
|
| 141 |
+
|
| 142 |
+
def __mod__(self, divisor):
|
| 143 |
+
divisor_value = int(divisor)
|
| 144 |
+
if divisor_value < 0:
|
| 145 |
+
raise ValueError("Modulus must be positive")
|
| 146 |
+
return self.__class__(self._value % divisor_value)
|
| 147 |
+
|
| 148 |
+
def inplace_pow(self, exponent, modulus=None):
|
| 149 |
+
exp_value = int(exponent)
|
| 150 |
+
if exp_value < 0:
|
| 151 |
+
raise ValueError("Exponent must not be negative")
|
| 152 |
+
|
| 153 |
+
if modulus is not None:
|
| 154 |
+
mod_value = int(modulus)
|
| 155 |
+
if mod_value < 0:
|
| 156 |
+
raise ValueError("Modulus must be positive")
|
| 157 |
+
if mod_value == 0:
|
| 158 |
+
raise ZeroDivisionError("Modulus cannot be zero")
|
| 159 |
+
else:
|
| 160 |
+
mod_value = None
|
| 161 |
+
self._value = pow(self._value, exp_value, mod_value)
|
| 162 |
+
return self
|
| 163 |
+
|
| 164 |
+
def __pow__(self, exponent, modulus=None):
|
| 165 |
+
result = self.__class__(self)
|
| 166 |
+
return result.inplace_pow(exponent, modulus)
|
| 167 |
+
|
| 168 |
+
def __abs__(self):
|
| 169 |
+
return abs(self._value)
|
| 170 |
+
|
| 171 |
+
def sqrt(self, modulus=None):
|
| 172 |
+
|
| 173 |
+
value = self._value
|
| 174 |
+
if modulus is None:
|
| 175 |
+
if value < 0:
|
| 176 |
+
raise ValueError("Square root of negative value")
|
| 177 |
+
# http://stackoverflow.com/questions/15390807/integer-square-root-in-python
|
| 178 |
+
|
| 179 |
+
x = value
|
| 180 |
+
y = (x + 1) // 2
|
| 181 |
+
while y < x:
|
| 182 |
+
x = y
|
| 183 |
+
y = (x + value // x) // 2
|
| 184 |
+
result = x
|
| 185 |
+
else:
|
| 186 |
+
if modulus <= 0:
|
| 187 |
+
raise ValueError("Modulus must be positive")
|
| 188 |
+
result = self._tonelli_shanks(self % modulus, modulus)
|
| 189 |
+
|
| 190 |
+
return self.__class__(result)
|
| 191 |
+
|
| 192 |
+
def __iadd__(self, term):
|
| 193 |
+
self._value += int(term)
|
| 194 |
+
return self
|
| 195 |
+
|
| 196 |
+
def __isub__(self, term):
|
| 197 |
+
self._value -= int(term)
|
| 198 |
+
return self
|
| 199 |
+
|
| 200 |
+
def __imul__(self, term):
|
| 201 |
+
self._value *= int(term)
|
| 202 |
+
return self
|
| 203 |
+
|
| 204 |
+
def __imod__(self, term):
|
| 205 |
+
modulus = int(term)
|
| 206 |
+
if modulus == 0:
|
| 207 |
+
raise ZeroDivisionError("Division by zero")
|
| 208 |
+
if modulus < 0:
|
| 209 |
+
raise ValueError("Modulus must be positive")
|
| 210 |
+
self._value %= modulus
|
| 211 |
+
return self
|
| 212 |
+
|
| 213 |
+
# Boolean/bit operations
|
| 214 |
+
def __and__(self, term):
|
| 215 |
+
return self.__class__(self._value & int(term))
|
| 216 |
+
|
| 217 |
+
def __or__(self, term):
|
| 218 |
+
return self.__class__(self._value | int(term))
|
| 219 |
+
|
| 220 |
+
def __rshift__(self, pos):
|
| 221 |
+
try:
|
| 222 |
+
return self.__class__(self._value >> int(pos))
|
| 223 |
+
except OverflowError:
|
| 224 |
+
if self._value >= 0:
|
| 225 |
+
return 0
|
| 226 |
+
else:
|
| 227 |
+
return -1
|
| 228 |
+
|
| 229 |
+
def __irshift__(self, pos):
|
| 230 |
+
try:
|
| 231 |
+
self._value >>= int(pos)
|
| 232 |
+
except OverflowError:
|
| 233 |
+
if self._value >= 0:
|
| 234 |
+
return 0
|
| 235 |
+
else:
|
| 236 |
+
return -1
|
| 237 |
+
return self
|
| 238 |
+
|
| 239 |
+
def __lshift__(self, pos):
|
| 240 |
+
try:
|
| 241 |
+
return self.__class__(self._value << int(pos))
|
| 242 |
+
except OverflowError:
|
| 243 |
+
raise ValueError("Incorrect shift count")
|
| 244 |
+
|
| 245 |
+
def __ilshift__(self, pos):
|
| 246 |
+
try:
|
| 247 |
+
self._value <<= int(pos)
|
| 248 |
+
except OverflowError:
|
| 249 |
+
raise ValueError("Incorrect shift count")
|
| 250 |
+
return self
|
| 251 |
+
|
| 252 |
+
def get_bit(self, n):
|
| 253 |
+
if self._value < 0:
|
| 254 |
+
raise ValueError("no bit representation for negative values")
|
| 255 |
+
try:
|
| 256 |
+
try:
|
| 257 |
+
result = (self._value >> n._value) & 1
|
| 258 |
+
if n._value < 0:
|
| 259 |
+
raise ValueError("negative bit count")
|
| 260 |
+
except AttributeError:
|
| 261 |
+
result = (self._value >> n) & 1
|
| 262 |
+
if n < 0:
|
| 263 |
+
raise ValueError("negative bit count")
|
| 264 |
+
except OverflowError:
|
| 265 |
+
result = 0
|
| 266 |
+
return result
|
| 267 |
+
|
| 268 |
+
# Extra
|
| 269 |
+
def is_odd(self):
|
| 270 |
+
return (self._value & 1) == 1
|
| 271 |
+
|
| 272 |
+
def is_even(self):
|
| 273 |
+
return (self._value & 1) == 0
|
| 274 |
+
|
| 275 |
+
def size_in_bits(self):
|
| 276 |
+
|
| 277 |
+
if self._value < 0:
|
| 278 |
+
raise ValueError("Conversion only valid for non-negative numbers")
|
| 279 |
+
|
| 280 |
+
if self._value == 0:
|
| 281 |
+
return 1
|
| 282 |
+
|
| 283 |
+
return self._value.bit_length()
|
| 284 |
+
|
| 285 |
+
def size_in_bytes(self):
|
| 286 |
+
return (self.size_in_bits() - 1) // 8 + 1
|
| 287 |
+
|
| 288 |
+
def is_perfect_square(self):
|
| 289 |
+
if self._value < 0:
|
| 290 |
+
return False
|
| 291 |
+
if self._value in (0, 1):
|
| 292 |
+
return True
|
| 293 |
+
|
| 294 |
+
x = self._value // 2
|
| 295 |
+
square_x = x ** 2
|
| 296 |
+
|
| 297 |
+
while square_x > self._value:
|
| 298 |
+
x = (square_x + self._value) // (2 * x)
|
| 299 |
+
square_x = x ** 2
|
| 300 |
+
|
| 301 |
+
return self._value == x ** 2
|
| 302 |
+
|
| 303 |
+
def fail_if_divisible_by(self, small_prime):
|
| 304 |
+
if (self._value % int(small_prime)) == 0:
|
| 305 |
+
raise ValueError("Value is composite")
|
| 306 |
+
|
| 307 |
+
def multiply_accumulate(self, a, b):
|
| 308 |
+
self._value += int(a) * int(b)
|
| 309 |
+
return self
|
| 310 |
+
|
| 311 |
+
def set(self, source):
|
| 312 |
+
self._value = int(source)
|
| 313 |
+
|
| 314 |
+
def inplace_inverse(self, modulus):
|
| 315 |
+
self._value = inverse(self._value, int(modulus))
|
| 316 |
+
return self
|
| 317 |
+
|
| 318 |
+
def inverse(self, modulus):
|
| 319 |
+
result = self.__class__(self)
|
| 320 |
+
result.inplace_inverse(modulus)
|
| 321 |
+
return result
|
| 322 |
+
|
| 323 |
+
def gcd(self, term):
|
| 324 |
+
return self.__class__(GCD(abs(self._value), abs(int(term))))
|
| 325 |
+
|
| 326 |
+
def lcm(self, term):
|
| 327 |
+
term = int(term)
|
| 328 |
+
if self._value == 0 or term == 0:
|
| 329 |
+
return self.__class__(0)
|
| 330 |
+
return self.__class__(abs((self._value * term) // self.gcd(term)._value))
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def jacobi_symbol(a, n):
|
| 334 |
+
a = int(a)
|
| 335 |
+
n = int(n)
|
| 336 |
+
|
| 337 |
+
if n <= 0:
|
| 338 |
+
raise ValueError("n must be a positive integer")
|
| 339 |
+
|
| 340 |
+
if (n & 1) == 0:
|
| 341 |
+
raise ValueError("n must be odd for the Jacobi symbol")
|
| 342 |
+
|
| 343 |
+
# Step 1
|
| 344 |
+
a = a % n
|
| 345 |
+
# Step 2
|
| 346 |
+
if a == 1 or n == 1:
|
| 347 |
+
return 1
|
| 348 |
+
# Step 3
|
| 349 |
+
if a == 0:
|
| 350 |
+
return 0
|
| 351 |
+
# Step 4
|
| 352 |
+
e = 0
|
| 353 |
+
a1 = a
|
| 354 |
+
while (a1 & 1) == 0:
|
| 355 |
+
a1 >>= 1
|
| 356 |
+
e += 1
|
| 357 |
+
# Step 5
|
| 358 |
+
if (e & 1) == 0:
|
| 359 |
+
s = 1
|
| 360 |
+
elif n % 8 in (1, 7):
|
| 361 |
+
s = 1
|
| 362 |
+
else:
|
| 363 |
+
s = -1
|
| 364 |
+
# Step 6
|
| 365 |
+
if n % 4 == 3 and a1 % 4 == 3:
|
| 366 |
+
s = -s
|
| 367 |
+
# Step 7
|
| 368 |
+
n1 = n % a1
|
| 369 |
+
# Step 8
|
| 370 |
+
return s * IntegerNative.jacobi_symbol(n1, a1)
|
| 371 |
+
|
| 372 |
+
@staticmethod
|
| 373 |
+
def _mult_modulo_bytes(term1, term2, modulus):
|
| 374 |
+
if modulus < 0:
|
| 375 |
+
raise ValueError("Modulus must be positive")
|
| 376 |
+
if modulus == 0:
|
| 377 |
+
raise ZeroDivisionError("Modulus cannot be zero")
|
| 378 |
+
if (modulus & 1) == 0:
|
| 379 |
+
raise ValueError("Odd modulus is required")
|
| 380 |
+
|
| 381 |
+
number_len = len(long_to_bytes(modulus))
|
| 382 |
+
return long_to_bytes((term1 * term2) % modulus, number_len)
|
wemm/lib/python3.10/site-packages/Crypto/Math/_IntegerNative.pyi
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._IntegerBase import IntegerBase
|
| 2 |
+
class IntegerNative(IntegerBase):
|
| 3 |
+
pass
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/Numbers.cpython-310.pyc
ADDED
|
Binary file (629 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/Primality.cpython-310.pyc
ADDED
|
Binary file (7.44 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerBase.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerCustom.cpython-310.pyc
ADDED
|
Binary file (2.96 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerGMP.cpython-310.pyc
ADDED
|
Binary file (20.9 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/_IntegerNative.cpython-310.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Math/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (161 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_AES.cpython-310.pyc
ADDED
|
Binary file (50.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_CBC.cpython-310.pyc
ADDED
|
Binary file (14.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_ChaCha20.cpython-310.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_DES.cpython-310.pyc
ADDED
|
Binary file (13 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_DES3.cpython-310.pyc
ADDED
|
Binary file (4.21 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/__pycache__/test_GCM.cpython-310.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/common.py
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 4 |
+
#
|
| 5 |
+
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
| 6 |
+
#
|
| 7 |
+
# ===================================================================
|
| 8 |
+
# The contents of this file are dedicated to the public domain. To
|
| 9 |
+
# the extent that dedication to the public domain is not available,
|
| 10 |
+
# everyone is granted a worldwide, perpetual, royalty-free,
|
| 11 |
+
# non-exclusive license to exercise all rights associated with the
|
| 12 |
+
# contents of this file for any purpose whatsoever.
|
| 13 |
+
# No rights are reserved.
|
| 14 |
+
#
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 16 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 17 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 18 |
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
| 19 |
+
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
| 20 |
+
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 21 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
# SOFTWARE.
|
| 23 |
+
# ===================================================================
|
| 24 |
+
|
| 25 |
+
"""Self-testing for PyCrypto hash modules"""
|
| 26 |
+
|
| 27 |
+
import unittest
|
| 28 |
+
from binascii import a2b_hex, b2a_hex, hexlify
|
| 29 |
+
|
| 30 |
+
from Crypto.Util.py3compat import b
|
| 31 |
+
from Crypto.Util.strxor import strxor_c
|
| 32 |
+
|
| 33 |
+
class _NoDefault: pass # sentinel object
|
| 34 |
+
def _extract(d, k, default=_NoDefault):
|
| 35 |
+
"""Get an item from a dictionary, and remove it from the dictionary."""
|
| 36 |
+
try:
|
| 37 |
+
retval = d[k]
|
| 38 |
+
except KeyError:
|
| 39 |
+
if default is _NoDefault:
|
| 40 |
+
raise
|
| 41 |
+
return default
|
| 42 |
+
del d[k]
|
| 43 |
+
return retval
|
| 44 |
+
|
| 45 |
+
# Generic cipher test case
|
| 46 |
+
class CipherSelfTest(unittest.TestCase):
|
| 47 |
+
|
| 48 |
+
def __init__(self, module, params):
|
| 49 |
+
unittest.TestCase.__init__(self)
|
| 50 |
+
self.module = module
|
| 51 |
+
|
| 52 |
+
# Extract the parameters
|
| 53 |
+
params = params.copy()
|
| 54 |
+
self.description = _extract(params, 'description')
|
| 55 |
+
self.key = b(_extract(params, 'key'))
|
| 56 |
+
self.plaintext = b(_extract(params, 'plaintext'))
|
| 57 |
+
self.ciphertext = b(_extract(params, 'ciphertext'))
|
| 58 |
+
self.module_name = _extract(params, 'module_name', None)
|
| 59 |
+
self.assoc_data = _extract(params, 'assoc_data', None)
|
| 60 |
+
self.mac = _extract(params, 'mac', None)
|
| 61 |
+
if self.assoc_data:
|
| 62 |
+
self.mac = b(self.mac)
|
| 63 |
+
|
| 64 |
+
mode = _extract(params, 'mode', None)
|
| 65 |
+
self.mode_name = str(mode)
|
| 66 |
+
|
| 67 |
+
if mode is not None:
|
| 68 |
+
# Block cipher
|
| 69 |
+
self.mode = getattr(self.module, "MODE_" + mode)
|
| 70 |
+
|
| 71 |
+
self.iv = _extract(params, 'iv', None)
|
| 72 |
+
if self.iv is None:
|
| 73 |
+
self.iv = _extract(params, 'nonce', None)
|
| 74 |
+
if self.iv is not None:
|
| 75 |
+
self.iv = b(self.iv)
|
| 76 |
+
|
| 77 |
+
else:
|
| 78 |
+
# Stream cipher
|
| 79 |
+
self.mode = None
|
| 80 |
+
self.iv = _extract(params, 'iv', None)
|
| 81 |
+
if self.iv is not None:
|
| 82 |
+
self.iv = b(self.iv)
|
| 83 |
+
|
| 84 |
+
self.extra_params = params
|
| 85 |
+
|
| 86 |
+
def shortDescription(self):
|
| 87 |
+
return self.description
|
| 88 |
+
|
| 89 |
+
def _new(self):
|
| 90 |
+
params = self.extra_params.copy()
|
| 91 |
+
key = a2b_hex(self.key)
|
| 92 |
+
|
| 93 |
+
old_style = []
|
| 94 |
+
if self.mode is not None:
|
| 95 |
+
old_style = [ self.mode ]
|
| 96 |
+
if self.iv is not None:
|
| 97 |
+
old_style += [ a2b_hex(self.iv) ]
|
| 98 |
+
|
| 99 |
+
return self.module.new(key, *old_style, **params)
|
| 100 |
+
|
| 101 |
+
def isMode(self, name):
|
| 102 |
+
if not hasattr(self.module, "MODE_"+name):
|
| 103 |
+
return False
|
| 104 |
+
return self.mode == getattr(self.module, "MODE_"+name)
|
| 105 |
+
|
| 106 |
+
def runTest(self):
|
| 107 |
+
plaintext = a2b_hex(self.plaintext)
|
| 108 |
+
ciphertext = a2b_hex(self.ciphertext)
|
| 109 |
+
assoc_data = []
|
| 110 |
+
if self.assoc_data:
|
| 111 |
+
assoc_data = [ a2b_hex(b(x)) for x in self.assoc_data]
|
| 112 |
+
|
| 113 |
+
ct = None
|
| 114 |
+
pt = None
|
| 115 |
+
|
| 116 |
+
#
|
| 117 |
+
# Repeat the same encryption or decryption twice and verify
|
| 118 |
+
# that the result is always the same
|
| 119 |
+
#
|
| 120 |
+
for i in range(2):
|
| 121 |
+
cipher = self._new()
|
| 122 |
+
decipher = self._new()
|
| 123 |
+
|
| 124 |
+
# Only AEAD modes
|
| 125 |
+
for comp in assoc_data:
|
| 126 |
+
cipher.update(comp)
|
| 127 |
+
decipher.update(comp)
|
| 128 |
+
|
| 129 |
+
ctX = b2a_hex(cipher.encrypt(plaintext))
|
| 130 |
+
ptX = b2a_hex(decipher.decrypt(ciphertext))
|
| 131 |
+
|
| 132 |
+
if ct:
|
| 133 |
+
self.assertEqual(ct, ctX)
|
| 134 |
+
self.assertEqual(pt, ptX)
|
| 135 |
+
ct, pt = ctX, ptX
|
| 136 |
+
|
| 137 |
+
self.assertEqual(self.ciphertext, ct) # encrypt
|
| 138 |
+
self.assertEqual(self.plaintext, pt) # decrypt
|
| 139 |
+
|
| 140 |
+
if self.mac:
|
| 141 |
+
mac = b2a_hex(cipher.digest())
|
| 142 |
+
self.assertEqual(self.mac, mac)
|
| 143 |
+
decipher.verify(a2b_hex(self.mac))
|
| 144 |
+
|
| 145 |
+
class CipherStreamingSelfTest(CipherSelfTest):
|
| 146 |
+
|
| 147 |
+
def shortDescription(self):
|
| 148 |
+
desc = self.module_name
|
| 149 |
+
if self.mode is not None:
|
| 150 |
+
desc += " in %s mode" % (self.mode_name,)
|
| 151 |
+
return "%s should behave like a stream cipher" % (desc,)
|
| 152 |
+
|
| 153 |
+
def runTest(self):
|
| 154 |
+
plaintext = a2b_hex(self.plaintext)
|
| 155 |
+
ciphertext = a2b_hex(self.ciphertext)
|
| 156 |
+
|
| 157 |
+
# The cipher should work like a stream cipher
|
| 158 |
+
|
| 159 |
+
# Test counter mode encryption, 3 bytes at a time
|
| 160 |
+
ct3 = []
|
| 161 |
+
cipher = self._new()
|
| 162 |
+
for i in range(0, len(plaintext), 3):
|
| 163 |
+
ct3.append(cipher.encrypt(plaintext[i:i+3]))
|
| 164 |
+
ct3 = b2a_hex(b("").join(ct3))
|
| 165 |
+
self.assertEqual(self.ciphertext, ct3) # encryption (3 bytes at a time)
|
| 166 |
+
|
| 167 |
+
# Test counter mode decryption, 3 bytes at a time
|
| 168 |
+
pt3 = []
|
| 169 |
+
cipher = self._new()
|
| 170 |
+
for i in range(0, len(ciphertext), 3):
|
| 171 |
+
pt3.append(cipher.encrypt(ciphertext[i:i+3]))
|
| 172 |
+
# PY3K: This is meant to be text, do not change to bytes (data)
|
| 173 |
+
pt3 = b2a_hex(b("").join(pt3))
|
| 174 |
+
self.assertEqual(self.plaintext, pt3) # decryption (3 bytes at a time)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class RoundtripTest(unittest.TestCase):
|
| 178 |
+
def __init__(self, module, params):
|
| 179 |
+
from Crypto import Random
|
| 180 |
+
unittest.TestCase.__init__(self)
|
| 181 |
+
self.module = module
|
| 182 |
+
self.iv = Random.get_random_bytes(module.block_size)
|
| 183 |
+
self.key = b(params['key'])
|
| 184 |
+
self.plaintext = 100 * b(params['plaintext'])
|
| 185 |
+
self.module_name = params.get('module_name', None)
|
| 186 |
+
|
| 187 |
+
def shortDescription(self):
|
| 188 |
+
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
|
| 189 |
+
|
| 190 |
+
def runTest(self):
|
| 191 |
+
|
| 192 |
+
## ECB mode
|
| 193 |
+
mode = self.module.MODE_ECB
|
| 194 |
+
encryption_cipher = self.module.new(a2b_hex(self.key), mode)
|
| 195 |
+
ciphertext = encryption_cipher.encrypt(self.plaintext)
|
| 196 |
+
decryption_cipher = self.module.new(a2b_hex(self.key), mode)
|
| 197 |
+
decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
|
| 198 |
+
self.assertEqual(self.plaintext, decrypted_plaintext)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class IVLengthTest(unittest.TestCase):
|
| 202 |
+
def __init__(self, module, params):
|
| 203 |
+
unittest.TestCase.__init__(self)
|
| 204 |
+
self.module = module
|
| 205 |
+
self.key = b(params['key'])
|
| 206 |
+
|
| 207 |
+
def shortDescription(self):
|
| 208 |
+
return "Check that all modes except MODE_ECB and MODE_CTR require an IV of the proper length"
|
| 209 |
+
|
| 210 |
+
def runTest(self):
|
| 211 |
+
self.assertRaises(TypeError, self.module.new, a2b_hex(self.key),
|
| 212 |
+
self.module.MODE_ECB, b(""))
|
| 213 |
+
|
| 214 |
+
def _dummy_counter(self):
|
| 215 |
+
return "\0" * self.module.block_size
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class NoDefaultECBTest(unittest.TestCase):
|
| 219 |
+
def __init__(self, module, params):
|
| 220 |
+
unittest.TestCase.__init__(self)
|
| 221 |
+
self.module = module
|
| 222 |
+
self.key = b(params['key'])
|
| 223 |
+
|
| 224 |
+
def runTest(self):
|
| 225 |
+
self.assertRaises(TypeError, self.module.new, a2b_hex(self.key))
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class BlockSizeTest(unittest.TestCase):
|
| 229 |
+
def __init__(self, module, params):
|
| 230 |
+
unittest.TestCase.__init__(self)
|
| 231 |
+
self.module = module
|
| 232 |
+
self.key = a2b_hex(b(params['key']))
|
| 233 |
+
|
| 234 |
+
def runTest(self):
|
| 235 |
+
cipher = self.module.new(self.key, self.module.MODE_ECB)
|
| 236 |
+
self.assertEqual(cipher.block_size, self.module.block_size)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class ByteArrayTest(unittest.TestCase):
|
| 240 |
+
"""Verify we can use bytearray's for encrypting and decrypting"""
|
| 241 |
+
|
| 242 |
+
def __init__(self, module, params):
|
| 243 |
+
unittest.TestCase.__init__(self)
|
| 244 |
+
self.module = module
|
| 245 |
+
|
| 246 |
+
# Extract the parameters
|
| 247 |
+
params = params.copy()
|
| 248 |
+
self.description = _extract(params, 'description')
|
| 249 |
+
self.key = b(_extract(params, 'key'))
|
| 250 |
+
self.plaintext = b(_extract(params, 'plaintext'))
|
| 251 |
+
self.ciphertext = b(_extract(params, 'ciphertext'))
|
| 252 |
+
self.module_name = _extract(params, 'module_name', None)
|
| 253 |
+
self.assoc_data = _extract(params, 'assoc_data', None)
|
| 254 |
+
self.mac = _extract(params, 'mac', None)
|
| 255 |
+
if self.assoc_data:
|
| 256 |
+
self.mac = b(self.mac)
|
| 257 |
+
|
| 258 |
+
mode = _extract(params, 'mode', None)
|
| 259 |
+
self.mode_name = str(mode)
|
| 260 |
+
|
| 261 |
+
if mode is not None:
|
| 262 |
+
# Block cipher
|
| 263 |
+
self.mode = getattr(self.module, "MODE_" + mode)
|
| 264 |
+
|
| 265 |
+
self.iv = _extract(params, 'iv', None)
|
| 266 |
+
if self.iv is None:
|
| 267 |
+
self.iv = _extract(params, 'nonce', None)
|
| 268 |
+
if self.iv is not None:
|
| 269 |
+
self.iv = b(self.iv)
|
| 270 |
+
else:
|
| 271 |
+
# Stream cipher
|
| 272 |
+
self.mode = None
|
| 273 |
+
self.iv = _extract(params, 'iv', None)
|
| 274 |
+
if self.iv is not None:
|
| 275 |
+
self.iv = b(self.iv)
|
| 276 |
+
|
| 277 |
+
self.extra_params = params
|
| 278 |
+
|
| 279 |
+
def _new(self):
|
| 280 |
+
params = self.extra_params.copy()
|
| 281 |
+
key = a2b_hex(self.key)
|
| 282 |
+
|
| 283 |
+
old_style = []
|
| 284 |
+
if self.mode is not None:
|
| 285 |
+
old_style = [ self.mode ]
|
| 286 |
+
if self.iv is not None:
|
| 287 |
+
old_style += [ a2b_hex(self.iv) ]
|
| 288 |
+
|
| 289 |
+
return self.module.new(key, *old_style, **params)
|
| 290 |
+
|
| 291 |
+
def runTest(self):
|
| 292 |
+
|
| 293 |
+
plaintext = a2b_hex(self.plaintext)
|
| 294 |
+
ciphertext = a2b_hex(self.ciphertext)
|
| 295 |
+
assoc_data = []
|
| 296 |
+
if self.assoc_data:
|
| 297 |
+
assoc_data = [ bytearray(a2b_hex(b(x))) for x in self.assoc_data]
|
| 298 |
+
|
| 299 |
+
cipher = self._new()
|
| 300 |
+
decipher = self._new()
|
| 301 |
+
|
| 302 |
+
# Only AEAD modes
|
| 303 |
+
for comp in assoc_data:
|
| 304 |
+
cipher.update(comp)
|
| 305 |
+
decipher.update(comp)
|
| 306 |
+
|
| 307 |
+
ct = b2a_hex(cipher.encrypt(bytearray(plaintext)))
|
| 308 |
+
pt = b2a_hex(decipher.decrypt(bytearray(ciphertext)))
|
| 309 |
+
|
| 310 |
+
self.assertEqual(self.ciphertext, ct) # encrypt
|
| 311 |
+
self.assertEqual(self.plaintext, pt) # decrypt
|
| 312 |
+
|
| 313 |
+
if self.mac:
|
| 314 |
+
mac = b2a_hex(cipher.digest())
|
| 315 |
+
self.assertEqual(self.mac, mac)
|
| 316 |
+
decipher.verify(bytearray(a2b_hex(self.mac)))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class MemoryviewTest(unittest.TestCase):
|
| 320 |
+
"""Verify we can use memoryviews for encrypting and decrypting"""
|
| 321 |
+
|
| 322 |
+
def __init__(self, module, params):
|
| 323 |
+
unittest.TestCase.__init__(self)
|
| 324 |
+
self.module = module
|
| 325 |
+
|
| 326 |
+
# Extract the parameters
|
| 327 |
+
params = params.copy()
|
| 328 |
+
self.description = _extract(params, 'description')
|
| 329 |
+
self.key = b(_extract(params, 'key'))
|
| 330 |
+
self.plaintext = b(_extract(params, 'plaintext'))
|
| 331 |
+
self.ciphertext = b(_extract(params, 'ciphertext'))
|
| 332 |
+
self.module_name = _extract(params, 'module_name', None)
|
| 333 |
+
self.assoc_data = _extract(params, 'assoc_data', None)
|
| 334 |
+
self.mac = _extract(params, 'mac', None)
|
| 335 |
+
if self.assoc_data:
|
| 336 |
+
self.mac = b(self.mac)
|
| 337 |
+
|
| 338 |
+
mode = _extract(params, 'mode', None)
|
| 339 |
+
self.mode_name = str(mode)
|
| 340 |
+
|
| 341 |
+
if mode is not None:
|
| 342 |
+
# Block cipher
|
| 343 |
+
self.mode = getattr(self.module, "MODE_" + mode)
|
| 344 |
+
|
| 345 |
+
self.iv = _extract(params, 'iv', None)
|
| 346 |
+
if self.iv is None:
|
| 347 |
+
self.iv = _extract(params, 'nonce', None)
|
| 348 |
+
if self.iv is not None:
|
| 349 |
+
self.iv = b(self.iv)
|
| 350 |
+
else:
|
| 351 |
+
# Stream cipher
|
| 352 |
+
self.mode = None
|
| 353 |
+
self.iv = _extract(params, 'iv', None)
|
| 354 |
+
if self.iv is not None:
|
| 355 |
+
self.iv = b(self.iv)
|
| 356 |
+
|
| 357 |
+
self.extra_params = params
|
| 358 |
+
|
| 359 |
+
def _new(self):
|
| 360 |
+
params = self.extra_params.copy()
|
| 361 |
+
key = a2b_hex(self.key)
|
| 362 |
+
|
| 363 |
+
old_style = []
|
| 364 |
+
if self.mode is not None:
|
| 365 |
+
old_style = [ self.mode ]
|
| 366 |
+
if self.iv is not None:
|
| 367 |
+
old_style += [ a2b_hex(self.iv) ]
|
| 368 |
+
|
| 369 |
+
return self.module.new(key, *old_style, **params)
|
| 370 |
+
|
| 371 |
+
def runTest(self):
|
| 372 |
+
|
| 373 |
+
plaintext = a2b_hex(self.plaintext)
|
| 374 |
+
ciphertext = a2b_hex(self.ciphertext)
|
| 375 |
+
assoc_data = []
|
| 376 |
+
if self.assoc_data:
|
| 377 |
+
assoc_data = [ memoryview(a2b_hex(b(x))) for x in self.assoc_data]
|
| 378 |
+
|
| 379 |
+
cipher = self._new()
|
| 380 |
+
decipher = self._new()
|
| 381 |
+
|
| 382 |
+
# Only AEAD modes
|
| 383 |
+
for comp in assoc_data:
|
| 384 |
+
cipher.update(comp)
|
| 385 |
+
decipher.update(comp)
|
| 386 |
+
|
| 387 |
+
ct = b2a_hex(cipher.encrypt(memoryview(plaintext)))
|
| 388 |
+
pt = b2a_hex(decipher.decrypt(memoryview(ciphertext)))
|
| 389 |
+
|
| 390 |
+
self.assertEqual(self.ciphertext, ct) # encrypt
|
| 391 |
+
self.assertEqual(self.plaintext, pt) # decrypt
|
| 392 |
+
|
| 393 |
+
if self.mac:
|
| 394 |
+
mac = b2a_hex(cipher.digest())
|
| 395 |
+
self.assertEqual(self.mac, mac)
|
| 396 |
+
decipher.verify(memoryview(a2b_hex(self.mac)))
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def make_block_tests(module, module_name, test_data, additional_params=dict()):
|
| 400 |
+
tests = []
|
| 401 |
+
extra_tests_added = False
|
| 402 |
+
for i in range(len(test_data)):
|
| 403 |
+
row = test_data[i]
|
| 404 |
+
|
| 405 |
+
# Build the "params" dictionary with
|
| 406 |
+
# - plaintext
|
| 407 |
+
# - ciphertext
|
| 408 |
+
# - key
|
| 409 |
+
# - mode (default is ECB)
|
| 410 |
+
# - (optionally) description
|
| 411 |
+
# - (optionally) any other parameter that this cipher mode requires
|
| 412 |
+
params = {}
|
| 413 |
+
if len(row) == 3:
|
| 414 |
+
(params['plaintext'], params['ciphertext'], params['key']) = row
|
| 415 |
+
elif len(row) == 4:
|
| 416 |
+
(params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
|
| 417 |
+
elif len(row) == 5:
|
| 418 |
+
(params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
|
| 419 |
+
params.update(extra_params)
|
| 420 |
+
else:
|
| 421 |
+
raise AssertionError("Unsupported tuple size %d" % (len(row),))
|
| 422 |
+
|
| 423 |
+
if not "mode" in params:
|
| 424 |
+
params["mode"] = "ECB"
|
| 425 |
+
|
| 426 |
+
# Build the display-name for the test
|
| 427 |
+
p2 = params.copy()
|
| 428 |
+
p_key = _extract(p2, 'key')
|
| 429 |
+
p_plaintext = _extract(p2, 'plaintext')
|
| 430 |
+
p_ciphertext = _extract(p2, 'ciphertext')
|
| 431 |
+
p_mode = _extract(p2, 'mode')
|
| 432 |
+
p_description = _extract(p2, 'description', None)
|
| 433 |
+
|
| 434 |
+
if p_description is not None:
|
| 435 |
+
description = p_description
|
| 436 |
+
elif p_mode == 'ECB' and not p2:
|
| 437 |
+
description = "p=%s, k=%s" % (p_plaintext, p_key)
|
| 438 |
+
else:
|
| 439 |
+
description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
|
| 440 |
+
name = "%s #%d: %s" % (module_name, i+1, description)
|
| 441 |
+
params['description'] = name
|
| 442 |
+
params['module_name'] = module_name
|
| 443 |
+
params.update(additional_params)
|
| 444 |
+
|
| 445 |
+
# Add extra test(s) to the test suite before the current test
|
| 446 |
+
if not extra_tests_added:
|
| 447 |
+
tests += [
|
| 448 |
+
RoundtripTest(module, params),
|
| 449 |
+
IVLengthTest(module, params),
|
| 450 |
+
NoDefaultECBTest(module, params),
|
| 451 |
+
ByteArrayTest(module, params),
|
| 452 |
+
BlockSizeTest(module, params),
|
| 453 |
+
]
|
| 454 |
+
extra_tests_added = True
|
| 455 |
+
|
| 456 |
+
# Add the current test to the test suite
|
| 457 |
+
tests.append(CipherSelfTest(module, params))
|
| 458 |
+
|
| 459 |
+
return tests
|
| 460 |
+
|
| 461 |
+
def make_stream_tests(module, module_name, test_data):
|
| 462 |
+
tests = []
|
| 463 |
+
extra_tests_added = False
|
| 464 |
+
for i in range(len(test_data)):
|
| 465 |
+
row = test_data[i]
|
| 466 |
+
|
| 467 |
+
# Build the "params" dictionary
|
| 468 |
+
params = {}
|
| 469 |
+
if len(row) == 3:
|
| 470 |
+
(params['plaintext'], params['ciphertext'], params['key']) = row
|
| 471 |
+
elif len(row) == 4:
|
| 472 |
+
(params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
|
| 473 |
+
elif len(row) == 5:
|
| 474 |
+
(params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
|
| 475 |
+
params.update(extra_params)
|
| 476 |
+
else:
|
| 477 |
+
raise AssertionError("Unsupported tuple size %d" % (len(row),))
|
| 478 |
+
|
| 479 |
+
# Build the display-name for the test
|
| 480 |
+
p2 = params.copy()
|
| 481 |
+
p_key = _extract(p2, 'key')
|
| 482 |
+
p_plaintext = _extract(p2, 'plaintext')
|
| 483 |
+
p_ciphertext = _extract(p2, 'ciphertext')
|
| 484 |
+
p_description = _extract(p2, 'description', None)
|
| 485 |
+
|
| 486 |
+
if p_description is not None:
|
| 487 |
+
description = p_description
|
| 488 |
+
elif not p2:
|
| 489 |
+
description = "p=%s, k=%s" % (p_plaintext, p_key)
|
| 490 |
+
else:
|
| 491 |
+
description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
|
| 492 |
+
name = "%s #%d: %s" % (module_name, i+1, description)
|
| 493 |
+
params['description'] = name
|
| 494 |
+
params['module_name'] = module_name
|
| 495 |
+
|
| 496 |
+
# Add extra test(s) to the test suite before the current test
|
| 497 |
+
if not extra_tests_added:
|
| 498 |
+
tests += [
|
| 499 |
+
ByteArrayTest(module, params),
|
| 500 |
+
]
|
| 501 |
+
|
| 502 |
+
tests.append(MemoryviewTest(module, params))
|
| 503 |
+
extra_tests_added = True
|
| 504 |
+
|
| 505 |
+
# Add the test to the test suite
|
| 506 |
+
tests.append(CipherSelfTest(module, params))
|
| 507 |
+
tests.append(CipherSt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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
import os
|
| 32 |
+
import re
|
| 33 |
+
import unittest
|
| 34 |
+
from binascii import hexlify, unhexlify
|
| 35 |
+
|
| 36 |
+
from Crypto.Util.py3compat import b, tobytes, bchr
|
| 37 |
+
from Crypto.Util.strxor import strxor_c
|
| 38 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 39 |
+
|
| 40 |
+
from Crypto.Cipher import ChaCha20
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ChaCha20Test(unittest.TestCase):
|
| 44 |
+
|
| 45 |
+
def test_new_positive(self):
|
| 46 |
+
cipher = ChaCha20.new(key=b("0")*32, nonce=b"0"*8)
|
| 47 |
+
self.assertEqual(cipher.nonce, b"0" * 8)
|
| 48 |
+
cipher = ChaCha20.new(key=b("0")*32, nonce=b"0"*12)
|
| 49 |
+
self.assertEqual(cipher.nonce, b"0" * 12)
|
| 50 |
+
|
| 51 |
+
def test_new_negative(self):
|
| 52 |
+
new = ChaCha20.new
|
| 53 |
+
self.assertRaises(TypeError, new)
|
| 54 |
+
self.assertRaises(TypeError, new, nonce=b("0"))
|
| 55 |
+
self.assertRaises(ValueError, new, nonce=b("0")*8, key=b("0"))
|
| 56 |
+
self.assertRaises(ValueError, new, nonce=b("0"), key=b("0")*32)
|
| 57 |
+
|
| 58 |
+
def test_default_nonce(self):
|
| 59 |
+
cipher1 = ChaCha20.new(key=bchr(1) * 32)
|
| 60 |
+
cipher2 = ChaCha20.new(key=bchr(1) * 32)
|
| 61 |
+
self.assertEqual(len(cipher1.nonce), 8)
|
| 62 |
+
self.assertNotEqual(cipher1.nonce, cipher2.nonce)
|
| 63 |
+
|
| 64 |
+
def test_nonce(self):
|
| 65 |
+
key = b'A' * 32
|
| 66 |
+
|
| 67 |
+
nonce1 = b'P' * 8
|
| 68 |
+
cipher1 = ChaCha20.new(key=key, nonce=nonce1)
|
| 69 |
+
self.assertEqual(nonce1, cipher1.nonce)
|
| 70 |
+
|
| 71 |
+
nonce2 = b'Q' * 12
|
| 72 |
+
cipher2 = ChaCha20.new(key=key, nonce=nonce2)
|
| 73 |
+
self.assertEqual(nonce2, cipher2.nonce)
|
| 74 |
+
|
| 75 |
+
def test_eiter_encrypt_or_decrypt(self):
|
| 76 |
+
"""Verify that a cipher cannot be used for both decrypting and encrypting"""
|
| 77 |
+
|
| 78 |
+
c1 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8)
|
| 79 |
+
c1.encrypt(b("8"))
|
| 80 |
+
self.assertRaises(TypeError, c1.decrypt, b("9"))
|
| 81 |
+
|
| 82 |
+
c2 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8)
|
| 83 |
+
c2.decrypt(b("8"))
|
| 84 |
+
self.assertRaises(TypeError, c2.encrypt, b("9"))
|
| 85 |
+
|
| 86 |
+
def test_round_trip(self):
|
| 87 |
+
pt = b("A") * 1024
|
| 88 |
+
c1 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8)
|
| 89 |
+
c2 = ChaCha20.new(key=b("5") * 32, nonce=b("6") * 8)
|
| 90 |
+
ct = c1.encrypt(pt)
|
| 91 |
+
self.assertEqual(c2.decrypt(ct), pt)
|
| 92 |
+
|
| 93 |
+
self.assertEqual(c1.encrypt(b("")), b(""))
|
| 94 |
+
self.assertEqual(c2.decrypt(b("")), b(""))
|
| 95 |
+
|
| 96 |
+
def test_streaming(self):
|
| 97 |
+
"""Verify that an arbitrary number of bytes can be encrypted/decrypted"""
|
| 98 |
+
from Crypto.Hash import SHA1
|
| 99 |
+
|
| 100 |
+
segments = (1, 3, 5, 7, 11, 17, 23)
|
| 101 |
+
total = sum(segments)
|
| 102 |
+
|
| 103 |
+
pt = b("")
|
| 104 |
+
while len(pt) < total:
|
| 105 |
+
pt += SHA1.new(pt).digest()
|
| 106 |
+
|
| 107 |
+
cipher1 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8)
|
| 108 |
+
ct = cipher1.encrypt(pt)
|
| 109 |
+
|
| 110 |
+
cipher2 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8)
|
| 111 |
+
cipher3 = ChaCha20.new(key=b("7") * 32, nonce=b("t") * 8)
|
| 112 |
+
idx = 0
|
| 113 |
+
for segment in segments:
|
| 114 |
+
self.assertEqual(cipher2.decrypt(ct[idx:idx+segment]), pt[idx:idx+segment])
|
| 115 |
+
self.assertEqual(cipher3.encrypt(pt[idx:idx+segment]), ct[idx:idx+segment])
|
| 116 |
+
idx += segment
|
| 117 |
+
|
| 118 |
+
def test_seek(self):
|
| 119 |
+
cipher1 = ChaCha20.new(key=b("9") * 32, nonce=b("e") * 8)
|
| 120 |
+
|
| 121 |
+
offset = 64 * 900 + 7
|
| 122 |
+
pt = b("1") * 64
|
| 123 |
+
|
| 124 |
+
cipher1.encrypt(b("0") * offset)
|
| 125 |
+
ct1 = cipher1.encrypt(pt)
|
| 126 |
+
|
| 127 |
+
cipher2 = ChaCha20.new(key=b("9") * 32, nonce=b("e") * 8)
|
| 128 |
+
cipher2.seek(offset)
|
| 129 |
+
ct2 = cipher2.encrypt(pt)
|
| 130 |
+
|
| 131 |
+
self.assertEqual(ct1, ct2)
|
| 132 |
+
|
| 133 |
+
def test_seek_tv(self):
|
| 134 |
+
# Test Vector #4, A.1 from
|
| 135 |
+
# http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
|
| 136 |
+
key = bchr(0) + bchr(255) + bchr(0) * 30
|
| 137 |
+
nonce = bchr(0) * 8
|
| 138 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 139 |
+
cipher.seek(64 * 2)
|
| 140 |
+
expected_key_stream = unhexlify(b(
|
| 141 |
+
"72d54dfbf12ec44b362692df94137f32"
|
| 142 |
+
"8fea8da73990265ec1bbbea1ae9af0ca"
|
| 143 |
+
"13b25aa26cb4a648cb9b9d1be65b2c09"
|
| 144 |
+
"24a66c54d545ec1b7374f4872e99f096"
|
| 145 |
+
))
|
| 146 |
+
ct = cipher.encrypt(bchr(0) * len(expected_key_stream))
|
| 147 |
+
self.assertEqual(expected_key_stream, ct)
|
| 148 |
+
|
| 149 |
+
def test_rfc7539(self):
|
| 150 |
+
# from https://tools.ietf.org/html/rfc7539 Annex A.1
|
| 151 |
+
# Each item is: key, nonce, block #, plaintext, ciphertext
|
| 152 |
+
tvs = [
|
| 153 |
+
# Test Vector #1
|
| 154 |
+
(
|
| 155 |
+
"00"*32,
|
| 156 |
+
"00"*12,
|
| 157 |
+
0,
|
| 158 |
+
"00"*16*4,
|
| 159 |
+
"76b8e0ada0f13d90405d6ae55386bd28"
|
| 160 |
+
"bdd219b8a08ded1aa836efcc8b770dc7"
|
| 161 |
+
"da41597c5157488d7724e03fb8d84a37"
|
| 162 |
+
"6a43b8f41518a11cc387b669b2ee6586"
|
| 163 |
+
),
|
| 164 |
+
# Test Vector #2
|
| 165 |
+
(
|
| 166 |
+
"00"*31 + "01",
|
| 167 |
+
"00"*11 + "02",
|
| 168 |
+
1,
|
| 169 |
+
"416e79207375626d697373696f6e2074"
|
| 170 |
+
"6f20746865204945544620696e74656e"
|
| 171 |
+
"6465642062792074686520436f6e7472"
|
| 172 |
+
"696275746f7220666f72207075626c69"
|
| 173 |
+
"636174696f6e20617320616c6c206f72"
|
| 174 |
+
"2070617274206f6620616e2049455446"
|
| 175 |
+
"20496e7465726e65742d447261667420"
|
| 176 |
+
"6f722052464320616e6420616e792073"
|
| 177 |
+
"746174656d656e74206d616465207769"
|
| 178 |
+
"7468696e2074686520636f6e74657874"
|
| 179 |
+
"206f6620616e20494554462061637469"
|
| 180 |
+
"7669747920697320636f6e7369646572"
|
| 181 |
+
"656420616e20224945544620436f6e74"
|
| 182 |
+
"7269627574696f6e222e205375636820"
|
| 183 |
+
"73746174656d656e747320696e636c75"
|
| 184 |
+
"6465206f72616c2073746174656d656e"
|
| 185 |
+
"747320696e2049455446207365737369"
|
| 186 |
+
"6f6e732c2061732077656c6c20617320"
|
| 187 |
+
"7772697474656e20616e6420656c6563"
|
| 188 |
+
"74726f6e696320636f6d6d756e696361"
|
| 189 |
+
"74696f6e73206d61646520617420616e"
|
| 190 |
+
"792074696d65206f7220706c6163652c"
|
| 191 |
+
"20776869636820617265206164647265"
|
| 192 |
+
"7373656420746f",
|
| 193 |
+
"a3fbf07df3fa2fde4f376ca23e827370"
|
| 194 |
+
"41605d9f4f4f57bd8cff2c1d4b7955ec"
|
| 195 |
+
"2a97948bd3722915c8f3d337f7d37005"
|
| 196 |
+
"0e9e96d647b7c39f56e031ca5eb6250d"
|
| 197 |
+
"4042e02785ececfa4b4bb5e8ead0440e"
|
| 198 |
+
"20b6e8db09d881a7c6132f420e527950"
|
| 199 |
+
"42bdfa7773d8a9051447b3291ce1411c"
|
| 200 |
+
"680465552aa6c405b7764d5e87bea85a"
|
| 201 |
+
"d00f8449ed8f72d0d662ab052691ca66"
|
| 202 |
+
"424bc86d2df80ea41f43abf937d3259d"
|
| 203 |
+
"c4b2d0dfb48a6c9139ddd7f76966e928"
|
| 204 |
+
"e635553ba76c5c879d7b35d49eb2e62b"
|
| 205 |
+
"0871cdac638939e25e8a1e0ef9d5280f"
|
| 206 |
+
"a8ca328b351c3c765989cbcf3daa8b6c"
|
| 207 |
+
"cc3aaf9f3979c92b3720fc88dc95ed84"
|
| 208 |
+
"a1be059c6499b9fda236e7e818b04b0b"
|
| 209 |
+
"c39c1e876b193bfe5569753f88128cc0"
|
| 210 |
+
"8aaa9b63d1a16f80ef2554d7189c411f"
|
| 211 |
+
"5869ca52c5b83fa36ff216b9c1d30062"
|
| 212 |
+
"bebcfd2dc5bce0911934fda79a86f6e6"
|
| 213 |
+
"98ced759c3ff9b6477338f3da4f9cd85"
|
| 214 |
+
"14ea9982ccafb341b2384dd902f3d1ab"
|
| 215 |
+
"7ac61dd29c6f21ba5b862f3730e37cfd"
|
| 216 |
+
"c4fd806c22f221"
|
| 217 |
+
),
|
| 218 |
+
# Test Vector #3
|
| 219 |
+
(
|
| 220 |
+
"1c9240a5eb55d38af333888604f6b5f0"
|
| 221 |
+
"473917c1402b80099dca5cbc207075c0",
|
| 222 |
+
"00"*11 + "02",
|
| 223 |
+
42,
|
| 224 |
+
"2754776173206272696c6c69672c2061"
|
| 225 |
+
"6e642074686520736c6974687920746f"
|
| 226 |
+
"7665730a446964206779726520616e64"
|
| 227 |
+
"2067696d626c6520696e207468652077"
|
| 228 |
+
"6162653a0a416c6c206d696d73792077"
|
| 229 |
+
"6572652074686520626f726f676f7665"
|
| 230 |
+
"732c0a416e6420746865206d6f6d6520"
|
| 231 |
+
"7261746873206f757467726162652e",
|
| 232 |
+
"62e6347f95ed87a45ffae7426f27a1df"
|
| 233 |
+
"5fb69110044c0d73118effa95b01e5cf"
|
| 234 |
+
"166d3df2d721caf9b21e5fb14c616871"
|
| 235 |
+
"fd84c54f9d65b283196c7fe4f60553eb"
|
| 236 |
+
"f39c6402c42234e32a356b3e764312a6"
|
| 237 |
+
"1a5532055716ead6962568f87d3f3f77"
|
| 238 |
+
"04c6a8d1bcd1bf4d50d6154b6da731b1"
|
| 239 |
+
"87b58dfd728afa36757a797ac188d1"
|
| 240 |
+
)
|
| 241 |
+
]
|
| 242 |
+
|
| 243 |
+
for tv in tvs:
|
| 244 |
+
key = unhexlify(tv[0])
|
| 245 |
+
nonce = unhexlify(tv[1])
|
| 246 |
+
offset = tv[2] * 64
|
| 247 |
+
pt = unhexlify(tv[3])
|
| 248 |
+
ct_expect = unhexlify(tv[4])
|
| 249 |
+
|
| 250 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 251 |
+
if offset != 0:
|
| 252 |
+
cipher.seek(offset)
|
| 253 |
+
ct = cipher.encrypt(pt)
|
| 254 |
+
assert(ct == ct_expect)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class XChaCha20Test(unittest.TestCase):
|
| 258 |
+
|
| 259 |
+
# From https://tools.ietf.org/html/draft-arciszewski-xchacha-03
|
| 260 |
+
|
| 261 |
+
def test_hchacha20(self):
|
| 262 |
+
# Section 2.2.1
|
| 263 |
+
|
| 264 |
+
from Crypto.Cipher.ChaCha20 import _HChaCha20
|
| 265 |
+
|
| 266 |
+
key = b"00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f"
|
| 267 |
+
key = unhexlify(key.replace(b":", b""))
|
| 268 |
+
|
| 269 |
+
nonce = b"00:00:00:09:00:00:00:4a:00:00:00:00:31:41:59:27"
|
| 270 |
+
nonce = unhexlify(nonce.replace(b":", b""))
|
| 271 |
+
|
| 272 |
+
subkey = _HChaCha20(key, nonce)
|
| 273 |
+
|
| 274 |
+
expected = b"82413b42 27b27bfe d30e4250 8a877d73 a0f9e4d5 8a74a853 c12ec413 26d3ecdc"
|
| 275 |
+
expected = unhexlify(expected.replace(b" ", b""))
|
| 276 |
+
|
| 277 |
+
self.assertEqual(subkey, expected)
|
| 278 |
+
|
| 279 |
+
def test_nonce(self):
|
| 280 |
+
key = b'A' * 32
|
| 281 |
+
nonce = b'P' * 24
|
| 282 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 283 |
+
self.assertEqual(nonce, cipher.nonce)
|
| 284 |
+
|
| 285 |
+
def test_encrypt(self):
|
| 286 |
+
# Section A.3.2
|
| 287 |
+
|
| 288 |
+
pt = b"""
|
| 289 |
+
5468652064686f6c65202870726f6e6f756e6365642022646f6c652229206973
|
| 290 |
+
20616c736f206b6e6f776e2061732074686520417369617469632077696c6420
|
| 291 |
+
646f672c2072656420646f672c20616e642077686973746c696e6720646f672e
|
| 292 |
+
2049742069732061626f7574207468652073697a65206f662061204765726d61
|
| 293 |
+
6e20736865706865726420627574206c6f6f6b73206d6f7265206c696b652061
|
| 294 |
+
206c6f6e672d6c656767656420666f782e205468697320686967686c7920656c
|
| 295 |
+
757369766520616e6420736b696c6c6564206a756d70657220697320636c6173
|
| 296 |
+
736966696564207769746820776f6c7665732c20636f796f7465732c206a6163
|
| 297 |
+
6b616c732c20616e6420666f78657320696e20746865207461786f6e6f6d6963
|
| 298 |
+
2066616d696c792043616e696461652e"""
|
| 299 |
+
pt = unhexlify(pt.replace(b"\n", b"").replace(b" ", b""))
|
| 300 |
+
|
| 301 |
+
key = unhexlify(b"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f")
|
| 302 |
+
iv = unhexlify(b"404142434445464748494a4b4c4d4e4f5051525354555658")
|
| 303 |
+
|
| 304 |
+
ct = b"""
|
| 305 |
+
7d0a2e6b7f7c65a236542630294e063b7ab9b555a5d5149aa21e4ae1e4fbce87
|
| 306 |
+
ecc8e08a8b5e350abe622b2ffa617b202cfad72032a3037e76ffdcdc4376ee05
|
| 307 |
+
3a190d7e46ca1de04144850381b9cb29f051915386b8a710b8ac4d027b8b050f
|
| 308 |
+
7cba5854e028d564e453b8a968824173fc16488b8970cac828f11ae53cabd201
|
| 309 |
+
12f87107df24ee6183d2274fe4c8b1485534ef2c5fbc1ec24bfc3663efaa08bc
|
| 310 |
+
047d29d25043532db8391a8a3d776bf4372a6955827ccb0cdd4af403a7ce4c63
|
| 311 |
+
d595c75a43e045f0cce1f29c8b93bd65afc5974922f214a40b7c402cdb91ae73
|
| 312 |
+
c0b63615cdad0480680f16515a7ace9d39236464328a37743ffc28f4ddb324f4
|
| 313 |
+
d0f5bbdc270c65b1749a6efff1fbaa09536175ccd29fb9e6057b307320d31683
|
| 314 |
+
8a9c71f70b5b5907a66f7ea49aadc409"""
|
| 315 |
+
ct = unhexlify(ct.replace(b"\n", b"").replace(b" ", b""))
|
| 316 |
+
|
| 317 |
+
cipher = ChaCha20.new(key=key, nonce=iv)
|
| 318 |
+
cipher.seek(64) # Counter = 1
|
| 319 |
+
ct_test = cipher.encrypt(pt)
|
| 320 |
+
self.assertEqual(ct, ct_test)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class ByteArrayTest(unittest.TestCase):
|
| 324 |
+
"""Verify we can encrypt or decrypt bytearrays"""
|
| 325 |
+
|
| 326 |
+
def runTest(self):
|
| 327 |
+
|
| 328 |
+
data = b"0123"
|
| 329 |
+
key = b"9" * 32
|
| 330 |
+
nonce = b"t" * 8
|
| 331 |
+
|
| 332 |
+
# Encryption
|
| 333 |
+
data_ba = bytearray(data)
|
| 334 |
+
key_ba = bytearray(key)
|
| 335 |
+
nonce_ba = bytearray(nonce)
|
| 336 |
+
|
| 337 |
+
cipher1 = ChaCha20.new(key=key, nonce=nonce)
|
| 338 |
+
ct = cipher1.encrypt(data)
|
| 339 |
+
|
| 340 |
+
cipher2 = ChaCha20.new(key=key_ba, nonce=nonce_ba)
|
| 341 |
+
key_ba[:1] = b'\xFF'
|
| 342 |
+
nonce_ba[:1] = b'\xFF'
|
| 343 |
+
ct_test = cipher2.encrypt(data_ba)
|
| 344 |
+
|
| 345 |
+
self.assertEqual(ct, ct_test)
|
| 346 |
+
self.assertEqual(cipher1.nonce, cipher2.nonce)
|
| 347 |
+
|
| 348 |
+
# Decryption
|
| 349 |
+
key_ba = bytearray(key)
|
| 350 |
+
nonce_ba = bytearray(nonce)
|
| 351 |
+
ct_ba = bytearray(ct)
|
| 352 |
+
|
| 353 |
+
cipher3 = ChaCha20.new(key=key_ba, nonce=nonce_ba)
|
| 354 |
+
key_ba[:1] = b'\xFF'
|
| 355 |
+
nonce_ba[:1] = b'\xFF'
|
| 356 |
+
pt_test = cipher3.decrypt(ct_ba)
|
| 357 |
+
|
| 358 |
+
self.assertEqual(data, pt_test)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class MemoryviewTest(unittest.TestCase):
|
| 362 |
+
"""Verify we can encrypt or decrypt bytearrays"""
|
| 363 |
+
|
| 364 |
+
def runTest(self):
|
| 365 |
+
|
| 366 |
+
data = b"0123"
|
| 367 |
+
key = b"9" * 32
|
| 368 |
+
nonce = b"t" * 8
|
| 369 |
+
|
| 370 |
+
# Encryption
|
| 371 |
+
data_mv = memoryview(bytearray(data))
|
| 372 |
+
key_mv = memoryview(bytearray(key))
|
| 373 |
+
nonce_mv = memoryview(bytearray(nonce))
|
| 374 |
+
|
| 375 |
+
cipher1 = ChaCha20.new(key=key, nonce=nonce)
|
| 376 |
+
ct = cipher1.encrypt(data)
|
| 377 |
+
|
| 378 |
+
cipher2 = ChaCha20.new(key=key_mv, nonce=nonce_mv)
|
| 379 |
+
key_mv[:1] = b'\xFF'
|
| 380 |
+
nonce_mv[:1] = b'\xFF'
|
| 381 |
+
ct_test = cipher2.encrypt(data_mv)
|
| 382 |
+
|
| 383 |
+
self.assertEqual(ct, ct_test)
|
| 384 |
+
self.assertEqual(cipher1.nonce, cipher2.nonce)
|
| 385 |
+
|
| 386 |
+
# Decryption
|
| 387 |
+
key_mv = memoryview(bytearray(key))
|
| 388 |
+
nonce_mv = memoryview(bytearray(nonce))
|
| 389 |
+
ct_mv = memoryview(bytearray(ct))
|
| 390 |
+
|
| 391 |
+
cipher3 = ChaCha20.new(key=key_mv, nonce=nonce_mv)
|
| 392 |
+
key_mv[:1] = b'\xFF'
|
| 393 |
+
nonce_mv[:1] = b'\xFF'
|
| 394 |
+
pt_test = cipher3.decrypt(ct_mv)
|
| 395 |
+
|
| 396 |
+
self.assertEqual(data, pt_test)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class ChaCha20_AGL_NIR(unittest.TestCase):
|
| 400 |
+
|
| 401 |
+
# From http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04
|
| 402 |
+
# and http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
|
| 403 |
+
tv = [
|
| 404 |
+
( "00" * 32,
|
| 405 |
+
"00" * 8,
|
| 406 |
+
"76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc"
|
| 407 |
+
"8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11c"
|
| 408 |
+
"c387b669b2ee6586"
|
| 409 |
+
"9f07e7be5551387a98ba977c732d080d"
|
| 410 |
+
"cb0f29a048e3656912c6533e32ee7aed"
|
| 411 |
+
"29b721769ce64e43d57133b074d839d5"
|
| 412 |
+
"31ed1f28510afb45ace10a1f4b794d6f"
|
| 413 |
+
),
|
| 414 |
+
( "00" * 31 + "01",
|
| 415 |
+
"00" * 8,
|
| 416 |
+
"4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952"
|
| 417 |
+
"ed432d41bbe2a0b6ea7566d2a5d1e7e20d42af2c53d792b1c43fea81"
|
| 418 |
+
"7e9ad275ae546963"
|
| 419 |
+
"3aeb5224ecf849929b9d828db1ced4dd"
|
| 420 |
+
"832025e8018b8160b82284f3c949aa5a"
|
| 421 |
+
"8eca00bbb4a73bdad192b5c42f73f2fd"
|
| 422 |
+
"4e273644c8b36125a64addeb006c13a0"
|
| 423 |
+
),
|
| 424 |
+
( "00" * 32,
|
| 425 |
+
"00" * 7 + "01",
|
| 426 |
+
"de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df1"
|
| 427 |
+
"37821031e85a050278a7084527214f73efc7fa5b5277062eb7a0433e"
|
| 428 |
+
"445f41e3"
|
| 429 |
+
),
|
| 430 |
+
( "00" * 32,
|
| 431 |
+
"01" + "00" * 7,
|
| 432 |
+
"ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd1"
|
| 433 |
+
"38e50d32111e4caf237ee53ca8ad6426194a88545ddc497a0b466e7d"
|
| 434 |
+
"6bbdb0041b2f586b"
|
| 435 |
+
),
|
| 436 |
+
( "000102030405060708090a0b0c0d0e0f101112131415161718191a1b"
|
| 437 |
+
"1c1d1e1f",
|
| 438 |
+
"0001020304050607",
|
| 439 |
+
"f798a189f195e66982105ffb640bb7757f579da31602fc93ec01ac56"
|
| 440 |
+
"f85ac3c134a4547b733b46413042c9440049176905d3be59ea1c53f1"
|
| 441 |
+
"5916155c2be8241a38008b9a26bc35941e2444177c8ade6689de9526"
|
| 442 |
+
"4986d95889fb60e84629c9bd9a5acb1cc118be563eb9b3a4a472f82e"
|
| 443 |
+
"09a7e778492b562ef7130e88dfe031c79db9d4f7c7a899151b9a4750"
|
| 444 |
+
"32b63fc385245fe054e3dd5a97a5f576fe064025d3ce042c566ab2c5"
|
| 445 |
+
"07b138db853e3d6959660996546cc9c4a6eafdc777c040d70eaf46f7"
|
| 446 |
+
"6dad3979e5c5360c3317166a1c894c94a371876a94df7628fe4eaaf2"
|
| 447 |
+
"ccb27d5aaae0ad7ad0f9d4b6ad3b54098746d4524d38407a6deb3ab7"
|
| 448 |
+
"8fab78c9"
|
| 449 |
+
),
|
| 450 |
+
( "00" * 32,
|
| 451 |
+
"00" * 7 + "02",
|
| 452 |
+
"c2c64d378cd536374ae204b9ef933fcd"
|
| 453 |
+
"1a8b2288b3dfa49672ab765b54ee27c7"
|
| 454 |
+
"8a970e0e955c14f3a88e741b97c286f7"
|
| 455 |
+
"5f8fc299e8148362fa198a39531bed6d"
|
| 456 |
+
),
|
| 457 |
+
]
|
| 458 |
+
|
| 459 |
+
def runTest(self):
|
| 460 |
+
for (key, nonce, stream) in self.tv:
|
| 461 |
+
c = ChaCha20.new(key=unhexlify(b(key)), nonce=unhexlify(b(nonce)))
|
| 462 |
+
ct = unhexlify(b(stream))
|
| 463 |
+
pt = b("\x00") * len(ct)
|
| 464 |
+
self.assertEqual(c.encrypt(pt), ct)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class TestOutput(unittest.TestCase):
|
| 468 |
+
|
| 469 |
+
def runTest(self):
|
| 470 |
+
# Encrypt/Decrypt data and test output parameter
|
| 471 |
+
|
| 472 |
+
key = b'4' * 32
|
| 473 |
+
nonce = b'5' * 8
|
| 474 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 475 |
+
|
| 476 |
+
pt = b'5' * 300
|
| 477 |
+
ct = cipher.encrypt(pt)
|
| 478 |
+
|
| 479 |
+
output = bytearray(len(pt))
|
| 480 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 481 |
+
res = cipher.encrypt(pt, output=output)
|
| 482 |
+
self.assertEqual(ct, output)
|
| 483 |
+
self.assertEqual(res, None)
|
| 484 |
+
|
| 485 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 486 |
+
res = cipher.decrypt(ct, output=output)
|
| 487 |
+
self.assertEqual(pt, output)
|
| 488 |
+
self.assertEqual(res, None)
|
| 489 |
+
|
| 490 |
+
output = memoryview(bytearray(len(pt)))
|
| 491 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 492 |
+
cipher.encrypt(pt, output=output)
|
| 493 |
+
self.assertEqual(ct, output)
|
| 494 |
+
|
| 495 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 496 |
+
cipher.decrypt(ct, output=output)
|
| 497 |
+
self.assertEqual(pt, output)
|
| 498 |
+
|
| 499 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 500 |
+
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*len(pt))
|
| 501 |
+
|
| 502 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 503 |
+
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*len(pt))
|
| 504 |
+
|
| 505 |
+
shorter_output = bytearray(len(pt) - 1)
|
| 506 |
+
|
| 507 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 508 |
+
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
|
| 509 |
+
|
| 510 |
+
cipher = ChaCha20.new(key=key, nonce=nonce)
|
| 511 |
+
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def get_tests(config={}):
|
| 515 |
+
tests = []
|
| 516 |
+
tests += list_test_cases(ChaCha20Test)
|
| 517 |
+
tests += list_test_cases(XChaCha20Test)
|
| 518 |
+
tests.append(ChaCha20_AGL_NIR())
|
| 519 |
+
tests.append(ByteArrayTest())
|
| 520 |
+
tests.append(MemoryviewTest())
|
| 521 |
+
tests.append(TestOutput())
|
| 522 |
+
|
| 523 |
+
return tests
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
if __name__ == '__main__':
|
| 527 |
+
import unittest
|
| 528 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 529 |
+
unittest.main(defaultTest='suite')
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/Cipher/test_pkcs1_15.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# SelfTest/Cipher/test_pkcs1_15.py: Self-test for PKCS#1 v1.5 encryption
|
| 4 |
+
#
|
| 5 |
+
# ===================================================================
|
| 6 |
+
# The contents of this file are dedicated to the public domain. To
|
| 7 |
+
# the extent that dedication to the public domain is not available,
|
| 8 |
+
# everyone is granted a worldwide, perpetual, royalty-free,
|
| 9 |
+
# non-exclusive license to exercise all rights associated with the
|
| 10 |
+
# contents of this file for any purpose whatsoever.
|
| 11 |
+
# No rights are reserved.
|
| 12 |
+
#
|
| 13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 14 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 15 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 16 |
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
| 17 |
+
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
| 18 |
+
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 19 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
# SOFTWARE.
|
| 21 |
+
# ===================================================================
|
| 22 |
+
|
| 23 |
+
from __future__ import print_function
|
| 24 |
+
|
| 25 |
+
import unittest
|
| 26 |
+
|
| 27 |
+
from Crypto.PublicKey import RSA
|
| 28 |
+
from Crypto.SelfTest.st_common import list_test_cases, a2b_hex
|
| 29 |
+
from Crypto import Random
|
| 30 |
+
from Crypto.Cipher import PKCS1_v1_5 as PKCS
|
| 31 |
+
from Crypto.Util.py3compat import b
|
| 32 |
+
from Crypto.Util.number import bytes_to_long, long_to_bytes
|
| 33 |
+
from Crypto.SelfTest.loader import load_test_vectors_wycheproof
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def rws(t):
|
| 37 |
+
"""Remove white spaces, tabs, and new lines from a string"""
|
| 38 |
+
for c in ['\n', '\t', ' ']:
|
| 39 |
+
t = t.replace(c, '')
|
| 40 |
+
return t
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def t2b(t):
|
| 44 |
+
"""Convert a text string with bytes in hex form to a byte string"""
|
| 45 |
+
clean = b(rws(t))
|
| 46 |
+
if len(clean) % 2 == 1:
|
| 47 |
+
raise ValueError("Even number of characters expected")
|
| 48 |
+
return a2b_hex(clean)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class PKCS1_15_Tests(unittest.TestCase):
|
| 52 |
+
|
| 53 |
+
def setUp(self):
|
| 54 |
+
self.rng = Random.new().read
|
| 55 |
+
self.key1024 = RSA.generate(1024, self.rng)
|
| 56 |
+
|
| 57 |
+
# List of tuples with test data for PKCS#1 v1.5.
|
| 58 |
+
# Each tuple is made up by:
|
| 59 |
+
# Item #0: dictionary with RSA key component, or key to import
|
| 60 |
+
# Item #1: plaintext
|
| 61 |
+
# Item #2: ciphertext
|
| 62 |
+
# Item #3: random data
|
| 63 |
+
|
| 64 |
+
_testData = (
|
| 65 |
+
|
| 66 |
+
#
|
| 67 |
+
# Generated with openssl 0.9.8o
|
| 68 |
+
#
|
| 69 |
+
(
|
| 70 |
+
# Private key
|
| 71 |
+
'''-----BEGIN RSA PRIVATE KEY-----
|
| 72 |
+
MIICXAIBAAKBgQDAiAnvIAOvqVwJTaYzsKnefZftgtXGE2hPJppGsWl78yz9jeXY
|
| 73 |
+
W/FxX/gTPURArNhdnhP6n3p2ZaDIBrO2zizbgIXs0IsljTTcr4vnI8fMXzyNUOjA
|
| 74 |
+
zP3nzMqZDZK6757XQAobOssMkBFqRWwilT/3DsBhRpl3iMUhF+wvpTSHewIDAQAB
|
| 75 |
+
AoGAC4HV/inOrpgTvSab8Wj0riyZgQOZ3U3ZpSlsfR8ra9Ib9Uee3jCYnKscu6Gk
|
| 76 |
+
y6zI/cdt8EPJ4PuwAWSNJzbpbVaDvUq25OD+CX8/uRT08yBS4J8TzBitZJTD4lS7
|
| 77 |
+
atdTnKT0Wmwk+u8tDbhvMKwnUHdJLcuIsycts9rwJVapUtkCQQDvDpx2JMun0YKG
|
| 78 |
+
uUttjmL8oJ3U0m3ZvMdVwBecA0eebZb1l2J5PvI3EJD97eKe91Nsw8T3lwpoN40k
|
| 79 |
+
IocSVDklAkEAzi1HLHE6EzVPOe5+Y0kGvrIYRRhncOb72vCvBZvD6wLZpQgqo6c4
|
| 80 |
+
d3XHFBBQWA6xcvQb5w+VVEJZzw64y25sHwJBAMYReRl6SzL0qA0wIYrYWrOt8JeQ
|
| 81 |
+
8mthulcWHXmqTgC6FEXP9Es5GD7/fuKl4wqLKZgIbH4nqvvGay7xXLCXD/ECQH9a
|
| 82 |
+
1JYNMtRen5unSAbIOxRcKkWz92F0LKpm9ZW/S9vFHO+mBcClMGoKJHiuQxLBsLbT
|
| 83 |
+
NtEZfSJZAeS2sUtn3/0CQDb2M2zNBTF8LlM0nxmh0k9VGm5TVIyBEMcipmvOgqIs
|
| 84 |
+
HKukWBcq9f/UOmS0oEhai/6g+Uf7VHJdWaeO5LzuvwU=
|
| 85 |
+
-----END RSA PRIVATE KEY-----''',
|
| 86 |
+
# Plaintext
|
| 87 |
+
'''THIS IS PLAINTEXT\x0A''',
|
| 88 |
+
# Ciphertext
|
| 89 |
+
'''3f dc fd 3c cd 5c 9b 12 af 65 32 e3 f7 d0 da 36
|
| 90 |
+
8f 8f d9 e3 13 1c 7f c8 b3 f9 c1 08 e4 eb 79 9c
|
| 91 |
+
91 89 1f 96 3b 94 77 61 99 a4 b1 ee 5d e6 17 c9
|
| 92 |
+
5d 0a b5 63 52 0a eb 00 45 38 2a fb b0 71 3d 11
|
| 93 |
+
f7 a1 9e a7 69 b3 af 61 c0 bb 04 5b 5d 4b 27 44
|
| 94 |
+
1f 5b 97 89 ba 6a 08 95 ee 4f a2 eb 56 64 e5 0f
|
| 95 |
+
da 7c f9 9a 61 61 06 62 ed a0 bc 5f aa 6c 31 78
|
| 96 |
+
70 28 1a bb 98 3c e3 6a 60 3c d1 0b 0f 5a f4 75''',
|
| 97 |
+
# Random data
|
| 98 |
+
'''eb d7 7d 86 a4 35 23 a3 54 7e 02 0b 42 1d
|
| 99 |
+
61 6c af 67 b8 4e 17 56 80 66 36 04 64 34 26 8a
|
| 100 |
+
47 dd 44 b3 1a b2 17 60 f4 91 2e e2 b5 95 64 cc
|
| 101 |
+
f9 da c8 70 94 54 86 4c ef 5b 08 7d 18 c4 ab 8d
|
| 102 |
+
04 06 33 8f ca 15 5f 52 60 8a a1 0c f5 08 b5 4c
|
| 103 |
+
bb 99 b8 94 25 04 9c e6 01 75 e6 f9 63 7a 65 61
|
| 104 |
+
13 8a a7 47 77 81 ae 0d b8 2c 4d 50 a5'''
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def testEncrypt1(self):
|
| 109 |
+
for test in self._testData:
|
| 110 |
+
# Build the key
|
| 111 |
+
key = RSA.importKey(test[0])
|
| 112 |
+
# RNG that takes its random numbers from a pool given
|
| 113 |
+
# at initialization
|
| 114 |
+
class randGen:
|
| 115 |
+
def __init__(self, data):
|
| 116 |
+
self.data = data
|
| 117 |
+
self.idx = 0
|
| 118 |
+
def __call__(self, N):
|
| 119 |
+
r = self.data[self.idx:self.idx+N]
|
| 120 |
+
self.idx += N
|
| 121 |
+
return r
|
| 122 |
+
# The real test
|
| 123 |
+
cipher = PKCS.new(key, randfunc=randGen(t2b(test[3])))
|
| 124 |
+
ct = cipher.encrypt(b(test[1]))
|
| 125 |
+
self.assertEqual(ct, t2b(test[2]))
|
| 126 |
+
|
| 127 |
+
def testEncrypt2(self):
|
| 128 |
+
# Verify that encryption fail if plaintext is too long
|
| 129 |
+
pt = '\x00'*(128-11+1)
|
| 130 |
+
cipher = PKCS.new(self.key1024)
|
| 131 |
+
self.assertRaises(ValueError, cipher.encrypt, pt)
|
| 132 |
+
|
| 133 |
+
def testVerify1(self):
|
| 134 |
+
for test in self._testData:
|
| 135 |
+
key = RSA.importKey(test[0])
|
| 136 |
+
expected_pt = b(test[1])
|
| 137 |
+
ct = t2b(test[2])
|
| 138 |
+
cipher = PKCS.new(key)
|
| 139 |
+
|
| 140 |
+
# The real test
|
| 141 |
+
pt = cipher.decrypt(ct, None)
|
| 142 |
+
self.assertEqual(pt, expected_pt)
|
| 143 |
+
|
| 144 |
+
pt = cipher.decrypt(ct, b'\xFF' * len(expected_pt))
|
| 145 |
+
self.assertEqual(pt, expected_pt)
|
| 146 |
+
|
| 147 |
+
def testVerify2(self):
|
| 148 |
+
# Verify that decryption fails if ciphertext is not as long as
|
| 149 |
+
# RSA modulus
|
| 150 |
+
cipher = PKCS.new(self.key1024)
|
| 151 |
+
self.assertRaises(ValueError, cipher.decrypt, '\x00'*127, "---")
|
| 152 |
+
self.assertRaises(ValueError, cipher.decrypt, '\x00'*129, "---")
|
| 153 |
+
|
| 154 |
+
# Verify that decryption fails if there are less then 8 non-zero padding
|
| 155 |
+
# bytes
|
| 156 |
+
pt = b('\x00\x02' + '\xFF'*7 + '\x00' + '\x45'*118)
|
| 157 |
+
pt_int = bytes_to_long(pt)
|
| 158 |
+
ct_int = self.key1024._encrypt(pt_int)
|
| 159 |
+
ct = long_to_bytes(ct_int, 128)
|
| 160 |
+
self.assertEqual(b"---", cipher.decrypt(ct, b"---"))
|
| 161 |
+
|
| 162 |
+
def testEncryptVerify1(self):
|
| 163 |
+
# Encrypt/Verify messages of length [0..RSAlen-11]
|
| 164 |
+
# and therefore padding [8..117]
|
| 165 |
+
for pt_len in range(0, 128 - 11 + 1):
|
| 166 |
+
pt = self.rng(pt_len)
|
| 167 |
+
cipher = PKCS.new(self.key1024)
|
| 168 |
+
ct = cipher.encrypt(pt)
|
| 169 |
+
pt2 = cipher.decrypt(ct, b'\xAA' * pt_len)
|
| 170 |
+
self.assertEqual(pt, pt2)
|
| 171 |
+
|
| 172 |
+
def test_encrypt_verify_exp_pt_len(self):
|
| 173 |
+
|
| 174 |
+
cipher = PKCS.new(self.key1024)
|
| 175 |
+
pt = b'5' * 16
|
| 176 |
+
ct = cipher.encrypt(pt)
|
| 177 |
+
sentinel = b'\xAA' * 16
|
| 178 |
+
|
| 179 |
+
pt_A = cipher.decrypt(ct, sentinel, 16)
|
| 180 |
+
self.assertEqual(pt, pt_A)
|
| 181 |
+
|
| 182 |
+
pt_B = cipher.decrypt(ct, sentinel, 15)
|
| 183 |
+
self.assertEqual(sentinel, pt_B)
|
| 184 |
+
|
| 185 |
+
pt_C = cipher.decrypt(ct, sentinel, 17)
|
| 186 |
+
self.assertEqual(sentinel, pt_C)
|
| 187 |
+
|
| 188 |
+
def testByteArray(self):
|
| 189 |
+
pt = b"XER"
|
| 190 |
+
cipher = PKCS.new(self.key1024)
|
| 191 |
+
ct = cipher.encrypt(bytearray(pt))
|
| 192 |
+
pt2 = cipher.decrypt(bytearray(ct), '\xFF' * len(pt))
|
| 193 |
+
self.assertEqual(pt, pt2)
|
| 194 |
+
|
| 195 |
+
def testMemoryview(self):
|
| 196 |
+
pt = b"XER"
|
| 197 |
+
cipher = PKCS.new(self.key1024)
|
| 198 |
+
ct = cipher.encrypt(memoryview(bytearray(pt)))
|
| 199 |
+
pt2 = cipher.decrypt(memoryview(bytearray(ct)), b'\xFF' * len(pt))
|
| 200 |
+
self.assertEqual(pt, pt2)
|
| 201 |
+
|
| 202 |
+
def test_return_type(self):
|
| 203 |
+
pt = b"XYZ"
|
| 204 |
+
cipher = PKCS.new(self.key1024)
|
| 205 |
+
ct = cipher.encrypt(pt)
|
| 206 |
+
self.assertTrue(isinstance(ct, bytes))
|
| 207 |
+
pt2 = cipher.decrypt(ct, b'\xAA' * 3)
|
| 208 |
+
self.assertTrue(isinstance(pt2, bytes))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class TestVectorsWycheproof(unittest.TestCase):
|
| 212 |
+
|
| 213 |
+
def __init__(self, wycheproof_warnings, skip_slow_tests):
|
| 214 |
+
unittest.TestCase.__init__(self)
|
| 215 |
+
self._wycheproof_warnings = wycheproof_warnings
|
| 216 |
+
self._skip_slow_tests = skip_slow_tests
|
| 217 |
+
self._id = "None"
|
| 218 |
+
|
| 219 |
+
def load_tests(self, filename):
|
| 220 |
+
|
| 221 |
+
def filter_rsa(group):
|
| 222 |
+
return RSA.import_key(group['privateKeyPem'])
|
| 223 |
+
|
| 224 |
+
result = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
|
| 225 |
+
filename,
|
| 226 |
+
"Wycheproof PKCS#1v1.5 (%s)" % filename,
|
| 227 |
+
group_tag={'rsa_key': filter_rsa}
|
| 228 |
+
)
|
| 229 |
+
return result
|
| 230 |
+
|
| 231 |
+
def setUp(self):
|
| 232 |
+
self.tv = []
|
| 233 |
+
self.tv.extend(self.load_tests("rsa_pkcs1_2048_test.json"))
|
| 234 |
+
if not self._skip_slow_tests:
|
| 235 |
+
self.tv.extend(self.load_tests("rsa_pkcs1_3072_test.json"))
|
| 236 |
+
self.tv.extend(self.load_tests("rsa_pkcs1_4096_test.json"))
|
| 237 |
+
|
| 238 |
+
def shortDescription(self):
|
| 239 |
+
return self._id
|
| 240 |
+
|
| 241 |
+
def warn(self, tv):
|
| 242 |
+
if tv.warning and self._wycheproof_warnings:
|
| 243 |
+
import warnings
|
| 244 |
+
warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
|
| 245 |
+
|
| 246 |
+
def test_decrypt(self, tv):
|
| 247 |
+
self._id = "Wycheproof Decrypt PKCS#1v1.5 Test #%s" % tv.id
|
| 248 |
+
sentinel = b'\xAA' * max(3, len(tv.msg))
|
| 249 |
+
cipher = PKCS.new(tv.rsa_key)
|
| 250 |
+
try:
|
| 251 |
+
pt = cipher.decrypt(tv.ct, sentinel=sentinel)
|
| 252 |
+
except ValueError:
|
| 253 |
+
assert not tv.valid
|
| 254 |
+
else:
|
| 255 |
+
if pt == sentinel:
|
| 256 |
+
assert not tv.valid
|
| 257 |
+
else:
|
| 258 |
+
assert tv.valid
|
| 259 |
+
self.assertEqual(pt, tv.msg)
|
| 260 |
+
self.warn(tv)
|
| 261 |
+
|
| 262 |
+
def runTest(self):
|
| 263 |
+
|
| 264 |
+
for tv in self.tv:
|
| 265 |
+
self.test_decrypt(tv)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def get_tests(config={}):
|
| 269 |
+
skip_slow_tests = not config.get('slow_tests')
|
| 270 |
+
wycheproof_warnings = config.get('wycheproof_warnings')
|
| 271 |
+
|
| 272 |
+
tests = []
|
| 273 |
+
tests += list_test_cases(PKCS1_15_Tests)
|
| 274 |
+
tests += [TestVectorsWycheproof(wycheproof_warnings, skip_slow_tests)]
|
| 275 |
+
return tests
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if __name__ == '__main__':
|
| 279 |
+
def suite():
|
| 280 |
+
return unittest.TestSuite(get_tests())
|
| 281 |
+
unittest.main(defaultTest='suite')
|
| 282 |
+
|
| 283 |
+
# vim:set ts=4 sw=4 sts=4 expandtab:
|
wemm/lib/python3.10/site-packages/Crypto/SelfTest/PublicKey/test_ElGamal.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# SelfTest/PublicKey/test_ElGamal.py: Self-test for the ElGamal primitive
|
| 4 |
+
#
|
| 5 |
+
# ===================================================================
|
| 6 |
+
# The contents of this file are dedicated to the public domain. To
|
| 7 |
+
# the extent that dedication to the public domain is not available,
|
| 8 |
+
# everyone is granted a worldwide, perpetual, royalty-free,
|
| 9 |
+
# non-exclusive license to exercise all rights associated with the
|
| 10 |
+
# contents of this file for any purpose whatsoever.
|
| 11 |
+
# No rights are reserved.
|
| 12 |
+
#
|
| 13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 14 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 15 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 16 |
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
| 17 |
+
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
| 18 |
+
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 19 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
# SOFTWARE.
|
| 21 |
+
# ===================================================================
|
| 22 |
+
|
| 23 |
+
"""Self-test suite for Crypto.PublicKey.ElGamal"""
|
| 24 |
+
|
| 25 |
+
__revision__ = "$Id$"
|
| 26 |
+
|
| 27 |
+
import unittest
|
| 28 |
+
from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
|
| 29 |
+
from Crypto import Random
|
| 30 |
+
from Crypto.PublicKey import ElGamal
|
| 31 |
+
from Crypto.Util.number import bytes_to_long
|
| 32 |
+
from Crypto.Util.py3compat import *
|
| 33 |
+
|
| 34 |
+
class ElGamalTest(unittest.TestCase):
|
| 35 |
+
|
| 36 |
+
#
|
| 37 |
+
# Test vectors
|
| 38 |
+
#
|
| 39 |
+
# There seem to be no real ElGamal test vectors available in the
|
| 40 |
+
# public domain. The following test vectors have been generated
|
| 41 |
+
# with libgcrypt 1.5.0.
|
| 42 |
+
#
|
| 43 |
+
# Encryption
|
| 44 |
+
tve=[
|
| 45 |
+
{
|
| 46 |
+
# 256 bits
|
| 47 |
+
'p' :'BA4CAEAAED8CBE952AFD2126C63EB3B345D65C2A0A73D2A3AD4138B6D09BD933',
|
| 48 |
+
'g' :'05',
|
| 49 |
+
'y' :'60D063600ECED7C7C55146020E7A31C4476E9793BEAED420FEC9E77604CAE4EF',
|
| 50 |
+
'x' :'1D391BA2EE3C37FE1BA175A69B2C73A11238AD77675932',
|
| 51 |
+
'k' :'F5893C5BAB4131264066F57AB3D8AD89E391A0B68A68A1',
|
| 52 |
+
'pt' :'48656C6C6F207468657265',
|
| 53 |
+
'ct1':'32BFD5F487966CEA9E9356715788C491EC515E4ED48B58F0F00971E93AAA5EC7',
|
| 54 |
+
'ct2':'7BE8FBFF317C93E82FCEF9BD515284BA506603FEA25D01C0CB874A31F315EE68'
|
| 55 |
+
},
|
| 56 |
+
|
| 57 |
+
{
|
| 58 |
+
# 512 bits
|
| 59 |
+
'p' :'F1B18AE9F7B4E08FDA9A04832F4E919D89462FD31BF12F92791A93519F75076D6CE3942689CDFF2F344CAFF0F82D01864F69F3AECF566C774CBACF728B81A227',
|
| 60 |
+
'g' :'07',
|
| 61 |
+
'y' :'688628C676E4F05D630E1BE39D0066178CA7AA83836B645DE5ADD359B4825A12B02EF4252E4E6FA9BEC1DB0BE90F6D7C8629CABB6E531F472B2664868156E20C',
|
| 62 |
+
'x' :'14E60B1BDFD33436C0DA8A22FDC14A2CCDBBED0627CE68',
|
| 63 |
+
'k' :'38DBF14E1F319BDA9BAB33EEEADCAF6B2EA5250577ACE7',
|
| 64 |
+
'pt' :'48656C6C6F207468657265',
|
| 65 |
+
'ct1':'290F8530C2CC312EC46178724F196F308AD4C523CEABB001FACB0506BFED676083FE0F27AC688B5C749AB3CB8A80CD6F7094DBA421FB19442F5A413E06A9772B',
|
| 66 |
+
'ct2':'1D69AAAD1DC50493FB1B8E8721D621D683F3BF1321BE21BC4A43E11B40C9D4D9C80DE3AAC2AB60D31782B16B61112E68220889D53C4C3136EE6F6CE61F8A23A0'
|
| 67 |
+
}
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
# Signature
|
| 71 |
+
tvs=[
|
| 72 |
+
{
|
| 73 |
+
# 256 bits
|
| 74 |
+
'p' :'D2F3C41EA66530838A704A48FFAC9334F4701ECE3A97CEE4C69DD01AE7129DD7',
|
| 75 |
+
'g' :'05',
|
| 76 |
+
'y' :'C3F9417DC0DAFEA6A05C1D2333B7A95E63B3F4F28CC962254B3256984D1012E7',
|
| 77 |
+
'x' :'165E4A39BE44D5A2D8B1332D416BC559616F536BC735BB',
|
| 78 |
+
'k' :'C7F0C794A7EAD726E25A47FF8928013680E73C51DD3D7D99BFDA8F492585928F',
|
| 79 |
+
'h' :'48656C6C6F207468657265',
|
| 80 |
+
'sig1':'35CA98133779E2073EF31165AFCDEB764DD54E96ADE851715495F9C635E1E7C2',
|
| 81 |
+
'sig2':'0135B88B1151279FE5D8078D4FC685EE81177EE9802AB123A73925FC1CB059A7',
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
# 512 bits
|
| 85 |
+
'p' :'E24CF3A4B8A6AF749DCA6D714282FE4AABEEE44A53BB6ED15FBE32B5D3C3EF9CC4124A2ECA331F3C1C1B667ACA3766825217E7B5F9856648D95F05330C6A19CF',
|
| 86 |
+
'g' :'0B',
|
| 87 |
+
'y' :'2AD3A1049CA5D4ED207B2431C79A8719BB4073D4A94E450EA6CEE8A760EB07ADB67C0D52C275EE85D7B52789061EE45F2F37D9B2AE522A51C28329766BFE68AC',
|
| 88 |
+
'x' :'16CBB4F46D9ECCF24FF9F7E63CAA3BD8936341555062AB',
|
| 89 |
+
'k' :'8A3D89A4E429FD2476D7D717251FB79BF900FFE77444E6BB8299DC3F84D0DD57ABAB50732AE158EA52F5B9E7D8813E81FD9F79470AE22F8F1CF9AEC820A78C69',
|
| 90 |
+
'h' :'48656C6C6F207468657265',
|
| 91 |
+
'sig1':'BE001AABAFFF976EC9016198FBFEA14CBEF96B000CCC0063D3324016F9E91FE80D8F9325812ED24DDB2B4D4CF4430B169880B3CE88313B53255BD4EC0378586F',
|
| 92 |
+
'sig2':'5E266F3F837BA204E3BBB6DBECC0611429D96F8C7CE8F4EFDF9D4CB681C2A954468A357BF4242CEC7418B51DFC081BCD21299EF5B5A0DDEF3A139A1817503DDE',
|
| 93 |
+
}
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
def test_generate_180(self):
|
| 97 |
+
self._test_random_key(180)
|
| 98 |
+
|
| 99 |
+
def test_encryption(self):
|
| 100 |
+
for tv in self.tve:
|
| 101 |
+
d = self.convert_tv(tv, True)
|
| 102 |
+
key = ElGamal.construct(d['key'])
|
| 103 |
+
ct = key._encrypt(d['pt'], d['k'])
|
| 104 |
+
self.assertEqual(ct[0], d['ct1'])
|
| 105 |
+
self.assertEqual(ct[1], d['ct2'])
|
| 106 |
+
|
| 107 |
+
def test_decryption(self):
|
| 108 |
+
for tv in self.tve:
|
| 109 |
+
d = self.convert_tv(tv, True)
|
| 110 |
+
key = ElGamal.construct(d['key'])
|
| 111 |
+
pt = key._decrypt((d['ct1'], d['ct2']))
|
| 112 |
+
self.assertEqual(pt, d['pt'])
|
| 113 |
+
|
| 114 |
+
def test_signing(self):
|
| 115 |
+
for tv in self.tvs:
|
| 116 |
+
d = self.convert_tv(tv, True)
|
| 117 |
+
key = ElGamal.construct(d['key'])
|
| 118 |
+
sig1, sig2 = key._sign(d['h'], d['k'])
|
| 119 |
+
self.assertEqual(sig1, d['sig1'])
|
| 120 |
+
self.assertEqual(sig2, d['sig2'])
|
| 121 |
+
|
| 122 |
+
def test_verification(self):
|
| 123 |
+
for tv in self.tvs:
|
| 124 |
+
d = self.convert_tv(tv, True)
|
| 125 |
+
key = ElGamal.construct(d['key'])
|
| 126 |
+
# Positive test
|
| 127 |
+
res = key._verify( d['h'], (d['sig1'],d['sig2']) )
|
| 128 |
+
self.assertTrue(res)
|
| 129 |
+
# Negative test
|
| 130 |
+
res = key._verify( d['h'], (d['sig1']+1,d['sig2']) )
|
| 131 |
+
self.assertFalse(res)
|
| 132 |
+
|
| 133 |
+
def test_bad_key3(self):
|
| 134 |
+
tup = tup0 = list(self.convert_tv(self.tvs[0], 1)['key'])[:3]
|
| 135 |
+
tup[0] += 1 # p += 1 (not prime)
|
| 136 |
+
self.assertRaises(ValueError, ElGamal.construct, tup)
|
| 137 |
+
|
| 138 |
+
tup = tup0
|
| 139 |
+
tup[1] = 1 # g = 1
|
| 140 |
+
self.assertRaises(ValueError, ElGamal.construct, tup)
|
| 141 |
+
|
| 142 |
+
tup = tup0
|
| 143 |
+
tup[2] = tup[0]*2 # y = 2*p
|
| 144 |
+
self.assertRaises(ValueError, ElGamal.construct, tup)
|
| 145 |
+
|
| 146 |
+
def test_bad_key4(self):
|
| 147 |
+
tup = tup0 = list(self.convert_tv(self.tvs[0], 1)['key'])
|
| 148 |
+
tup[3] += 1 # x += 1
|
| 149 |
+
self.assertRaises(ValueError, ElGamal.construct, tup)
|
| 150 |
+
|
| 151 |
+
def convert_tv(self, tv, as_longs=0):
|
| 152 |
+
"""Convert a test vector from textual form (hexadecimal ascii
|
| 153 |
+
to either integers or byte strings."""
|
| 154 |
+
key_comps = 'p','g','y','x'
|
| 155 |
+
tv2 = {}
|
| 156 |
+
for c in tv.keys():
|
| 157 |
+
tv2[c] = a2b_hex(tv[c])
|
| 158 |
+
if as_longs or c in key_comps or c in ('sig1','sig2'):
|
| 159 |
+
tv2[c] = bytes_to_long(tv2[c])
|
| 160 |
+
tv2['key']=[]
|
| 161 |
+
for c in key_comps:
|
| 162 |
+
tv2['key'] += [tv2[c]]
|
| 163 |
+
del tv2[c]
|
| 164 |
+
return tv2
|
| 165 |
+
|
| 166 |
+
def _test_random_key(self, bits):
|
| 167 |
+
elgObj = ElGamal.generate(bits, Random.new().read)
|
| 168 |
+
self._check_private_key(elgObj)
|
| 169 |
+
self._exercise_primitive(elgObj)
|
| 170 |
+
pub = elgObj.publickey()
|
| 171 |
+
self._check_public_key(pub)
|
| 172 |
+
self._exercise_public_primitive(elgObj)
|
| 173 |
+
|
| 174 |
+
def _check_private_key(self, elgObj):
|
| 175 |
+
|
| 176 |
+
# Check capabilities
|
| 177 |
+
self.assertTrue(elgObj.has_private())
|
| 178 |
+
|
| 179 |
+
# Sanity check key data
|
| 180 |
+
self.assertTrue(1<elgObj.g<(elgObj.p-1))
|
| 181 |
+
self.assertEqual(pow(elgObj.g, elgObj.p-1, elgObj.p), 1)
|
| 182 |
+
self.assertTrue(1<elgObj.x<(elgObj.p-1))
|
| 183 |
+
self.assertEqual(pow(elgObj.g, elgObj.x, elgObj.p), elgObj.y)
|
| 184 |
+
|
| 185 |
+
def _check_public_key(self, elgObj):
|
| 186 |
+
|
| 187 |
+
# Check capabilities
|
| 188 |
+
self.assertFalse(elgObj.has_private())
|
| 189 |
+
|
| 190 |
+
# Sanity check key data
|
| 191 |
+
self.assertTrue(1<elgObj.g<(elgObj.p-1))
|
| 192 |
+
self.assertEqual(pow(elgObj.g, elgObj.p-1, elgObj.p), 1)
|
| 193 |
+
|
| 194 |
+
def _exercise_primitive(self, elgObj):
|
| 195 |
+
# Test encryption/decryption
|
| 196 |
+
plaintext = 127218
|
| 197 |
+
ciphertext = elgObj._encrypt(plaintext, 123456789)
|
| 198 |
+
plaintextP = elgObj._decrypt(ciphertext)
|
| 199 |
+
self.assertEqual(plaintext, plaintextP)
|
| 200 |
+
|
| 201 |
+
# Test signature/verification
|
| 202 |
+
signature = elgObj._sign(plaintext, 987654321)
|
| 203 |
+
elgObj._verify(plaintext, signature)
|
| 204 |
+
|
| 205 |
+
def _exercise_public_primitive(self, elgObj):
|
| 206 |
+
plaintext = 92987276
|
| 207 |
+
ciphertext = elgObj._encrypt(plaintext, 123456789)
|
| 208 |
+
|
| 209 |
+
def get_tests(config={}):
|
| 210 |
+
tests = []
|
| 211 |
+
tests += list_test_cases(ElGamalTest)
|
| 212 |
+
return tests
|
| 213 |
+
|
| 214 |
+
if __name__ == '__main__':
|
| 215 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 216 |
+
unittest.main(defaultTest='suite')
|
| 217 |
+
|
wemm/lib/python3.10/site-packages/Crypto/Signature/DSS.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Signature/DSS.py : DSS.py
|
| 3 |
+
#
|
| 4 |
+
# ===================================================================
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 7 |
+
# All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Redistribution and use in source and binary forms, with or without
|
| 10 |
+
# modification, are permitted provided that the following conditions
|
| 11 |
+
# are met:
|
| 12 |
+
#
|
| 13 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 14 |
+
# notice, this list of conditions and the following disclaimer.
|
| 15 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 16 |
+
# notice, this list of conditions and the following disclaimer in
|
| 17 |
+
# the documentation and/or other materials provided with the
|
| 18 |
+
# distribution.
|
| 19 |
+
#
|
| 20 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 21 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 22 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 23 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 24 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 25 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 26 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 27 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 28 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 29 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 30 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 31 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 32 |
+
# ===================================================================
|
| 33 |
+
|
| 34 |
+
from Crypto.Util.asn1 import DerSequence
|
| 35 |
+
from Crypto.Util.number import long_to_bytes
|
| 36 |
+
from Crypto.Math.Numbers import Integer
|
| 37 |
+
|
| 38 |
+
from Crypto.Hash import HMAC
|
| 39 |
+
from Crypto.PublicKey.ECC import EccKey
|
| 40 |
+
from Crypto.PublicKey.DSA import DsaKey
|
| 41 |
+
|
| 42 |
+
__all__ = ['DssSigScheme', 'new']
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DssSigScheme(object):
|
| 46 |
+
"""A (EC)DSA signature object.
|
| 47 |
+
Do not instantiate directly.
|
| 48 |
+
Use :func:`Crypto.Signature.DSS.new`.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(self, key, encoding, order):
|
| 52 |
+
"""Create a new Digital Signature Standard (DSS) object.
|
| 53 |
+
|
| 54 |
+
Do not instantiate this object directly,
|
| 55 |
+
use `Crypto.Signature.DSS.new` instead.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
self._key = key
|
| 59 |
+
self._encoding = encoding
|
| 60 |
+
self._order = order
|
| 61 |
+
|
| 62 |
+
self._order_bits = self._order.size_in_bits()
|
| 63 |
+
self._order_bytes = (self._order_bits - 1) // 8 + 1
|
| 64 |
+
|
| 65 |
+
def can_sign(self):
|
| 66 |
+
"""Return ``True`` if this signature object can be used
|
| 67 |
+
for signing messages."""
|
| 68 |
+
|
| 69 |
+
return self._key.has_private()
|
| 70 |
+
|
| 71 |
+
def _compute_nonce(self, msg_hash):
|
| 72 |
+
raise NotImplementedError("To be provided by subclasses")
|
| 73 |
+
|
| 74 |
+
def _valid_hash(self, msg_hash):
|
| 75 |
+
raise NotImplementedError("To be provided by subclasses")
|
| 76 |
+
|
| 77 |
+
def sign(self, msg_hash):
|
| 78 |
+
"""Compute the DSA/ECDSA signature of a message.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
msg_hash (hash object):
|
| 82 |
+
The hash that was carried out over the message.
|
| 83 |
+
The object belongs to the :mod:`Crypto.Hash` package.
|
| 84 |
+
Under mode ``'fips-186-3'``, the hash must be a FIPS
|
| 85 |
+
approved secure hash (SHA-2 or SHA-3).
|
| 86 |
+
|
| 87 |
+
:return: The signature as ``bytes``
|
| 88 |
+
:raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key
|
| 89 |
+
:raise TypeError: if the (EC)DSA key has no private half
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
if not self._key.has_private():
|
| 93 |
+
raise TypeError("Private key is needed to sign")
|
| 94 |
+
|
| 95 |
+
if not self._valid_hash(msg_hash):
|
| 96 |
+
raise ValueError("Hash is not sufficiently strong")
|
| 97 |
+
|
| 98 |
+
# Generate the nonce k (critical!)
|
| 99 |
+
nonce = self._compute_nonce(msg_hash)
|
| 100 |
+
|
| 101 |
+
# Perform signature using the raw API
|
| 102 |
+
z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
|
| 103 |
+
sig_pair = self._key._sign(z, nonce)
|
| 104 |
+
|
| 105 |
+
# Encode the signature into a single byte string
|
| 106 |
+
if self._encoding == 'binary':
|
| 107 |
+
output = b"".join([long_to_bytes(x, self._order_bytes)
|
| 108 |
+
for x in sig_pair])
|
| 109 |
+
else:
|
| 110 |
+
# Dss-sig ::= SEQUENCE {
|
| 111 |
+
# r INTEGER,
|
| 112 |
+
# s INTEGER
|
| 113 |
+
# }
|
| 114 |
+
# Ecdsa-Sig-Value ::= SEQUENCE {
|
| 115 |
+
# r INTEGER,
|
| 116 |
+
# s INTEGER
|
| 117 |
+
# }
|
| 118 |
+
output = DerSequence(sig_pair).encode()
|
| 119 |
+
|
| 120 |
+
return output
|
| 121 |
+
|
| 122 |
+
def verify(self, msg_hash, signature):
|
| 123 |
+
"""Check if a certain (EC)DSA signature is authentic.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
msg_hash (hash object):
|
| 127 |
+
The hash that was carried out over the message.
|
| 128 |
+
This is an object belonging to the :mod:`Crypto.Hash` module.
|
| 129 |
+
Under mode ``'fips-186-3'``, the hash must be a FIPS
|
| 130 |
+
approved secure hash (SHA-2 or SHA-3).
|
| 131 |
+
|
| 132 |
+
signature (``bytes``):
|
| 133 |
+
The signature that needs to be validated.
|
| 134 |
+
|
| 135 |
+
:raise ValueError: if the signature is not authentic
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
if not self._valid_hash(msg_hash):
|
| 139 |
+
raise ValueError("Hash is not sufficiently strong")
|
| 140 |
+
|
| 141 |
+
if self._encoding == 'binary':
|
| 142 |
+
if len(signature) != (2 * self._order_bytes):
|
| 143 |
+
raise ValueError("The signature is not authentic (length)")
|
| 144 |
+
r_prime, s_prime = [Integer.from_bytes(x)
|
| 145 |
+
for x in (signature[:self._order_bytes],
|
| 146 |
+
signature[self._order_bytes:])]
|
| 147 |
+
else:
|
| 148 |
+
try:
|
| 149 |
+
der_seq = DerSequence().decode(signature, strict=True)
|
| 150 |
+
except (ValueError, IndexError):
|
| 151 |
+
raise ValueError("The signature is not authentic (DER)")
|
| 152 |
+
if len(der_seq) != 2 or not der_seq.hasOnlyInts():
|
| 153 |
+
raise ValueError("The signature is not authentic (DER content)")
|
| 154 |
+
r_prime, s_prime = Integer(der_seq[0]), Integer(der_seq[1])
|
| 155 |
+
|
| 156 |
+
if not (0 < r_prime < self._order) or not (0 < s_prime < self._order):
|
| 157 |
+
raise ValueError("The signature is not authentic (d)")
|
| 158 |
+
|
| 159 |
+
z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
|
| 160 |
+
result = self._key._verify(z, (r_prime, s_prime))
|
| 161 |
+
if not result:
|
| 162 |
+
raise ValueError("The signature is not authentic")
|
| 163 |
+
# Make PyCrypto code to fail
|
| 164 |
+
return False
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class DeterministicDsaSigScheme(DssSigScheme):
|
| 168 |
+
# Also applicable to ECDSA
|
| 169 |
+
|
| 170 |
+
def __init__(self, key, encoding, order, private_key):
|
| 171 |
+
super(DeterministicDsaSigScheme, self).__init__(key, encoding, order)
|
| 172 |
+
self._private_key = private_key
|
| 173 |
+
|
| 174 |
+
def _bits2int(self, bstr):
|
| 175 |
+
"""See 2.3.2 in RFC6979"""
|
| 176 |
+
|
| 177 |
+
result = Integer.from_bytes(bstr)
|
| 178 |
+
q_len = self._order.size_in_bits()
|
| 179 |
+
b_len = len(bstr) * 8
|
| 180 |
+
if b_len > q_len:
|
| 181 |
+
# Only keep leftmost q_len bits
|
| 182 |
+
result >>= (b_len - q_len)
|
| 183 |
+
return result
|
| 184 |
+
|
| 185 |
+
def _int2octets(self, int_mod_q):
|
| 186 |
+
"""See 2.3.3 in RFC6979"""
|
| 187 |
+
|
| 188 |
+
assert 0 < int_mod_q < self._order
|
| 189 |
+
return long_to_bytes(int_mod_q, self._order_bytes)
|
| 190 |
+
|
| 191 |
+
def _bits2octets(self, bstr):
|
| 192 |
+
"""See 2.3.4 in RFC6979"""
|
| 193 |
+
|
| 194 |
+
z1 = self._bits2int(bstr)
|
| 195 |
+
if z1 < self._order:
|
| 196 |
+
z2 = z1
|
| 197 |
+
else:
|
| 198 |
+
z2 = z1 - self._order
|
| 199 |
+
return self._int2octets(z2)
|
| 200 |
+
|
| 201 |
+
def _compute_nonce(self, mhash):
|
| 202 |
+
"""Generate k in a deterministic way"""
|
| 203 |
+
|
| 204 |
+
# See section 3.2 in RFC6979.txt
|
| 205 |
+
# Step a
|
| 206 |
+
h1 = mhash.digest()
|
| 207 |
+
# Step b
|
| 208 |
+
mask_v = b'\x01' * mhash.digest_size
|
| 209 |
+
# Step c
|
| 210 |
+
nonce_k = b'\x00' * mhash.digest_size
|
| 211 |
+
|
| 212 |
+
for int_oct in (b'\x00', b'\x01'):
|
| 213 |
+
# Step d/f
|
| 214 |
+
nonce_k = HMAC.new(nonce_k,
|
| 215 |
+
mask_v + int_oct +
|
| 216 |
+
self._int2octets(self._private_key) +
|
| 217 |
+
self._bits2octets(h1), mhash).digest()
|
| 218 |
+
# Step e/g
|
| 219 |
+
mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
|
| 220 |
+
|
| 221 |
+
nonce = -1
|
| 222 |
+
while not (0 < nonce < self._order):
|
| 223 |
+
# Step h.C (second part)
|
| 224 |
+
if nonce != -1:
|
| 225 |
+
nonce_k = HMAC.new(nonce_k, mask_v + b'\x00',
|
| 226 |
+
mhash).digest()
|
| 227 |
+
mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
|
| 228 |
+
|
| 229 |
+
# Step h.A
|
| 230 |
+
mask_t = b""
|
| 231 |
+
|
| 232 |
+
# Step h.B
|
| 233 |
+
while len(mask_t) < self._order_bytes:
|
| 234 |
+
mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
|
| 235 |
+
mask_t += mask_v
|
| 236 |
+
|
| 237 |
+
# Step h.C (first part)
|
| 238 |
+
nonce = self._bits2int(mask_t)
|
| 239 |
+
return nonce
|
| 240 |
+
|
| 241 |
+
def _valid_hash(self, msg_hash):
|
| 242 |
+
return True
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class FipsDsaSigScheme(DssSigScheme):
|
| 246 |
+
|
| 247 |
+
#: List of L (bit length of p) and N (bit length of q) combinations
|
| 248 |
+
#: that are allowed by FIPS 186-3. The security level is provided in
|
| 249 |
+
#: Table 2 of FIPS 800-57 (rev3).
|
| 250 |
+
_fips_186_3_L_N = (
|
| 251 |
+
(1024, 160), # 80 bits (SHA-1 or stronger)
|
| 252 |
+
(2048, 224), # 112 bits (SHA-224 or stronger)
|
| 253 |
+
(2048, 256), # 128 bits (SHA-256 or stronger)
|
| 254 |
+
(3072, 256) # 256 bits (SHA-512)
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
def __init__(self, key, encoding, order, randfunc):
|
| 258 |
+
super(FipsDsaSigScheme, self).__init__(key, encoding, order)
|
| 259 |
+
self._randfunc = randfunc
|
| 260 |
+
|
| 261 |
+
L = Integer(key.p).size_in_bits()
|
| 262 |
+
if (L, self._order_bits) not in self._fips_186_3_L_N:
|
| 263 |
+
error = ("L/N (%d, %d) is not compliant to FIPS 186-3"
|
| 264 |
+
% (L, self._order_bits))
|
| 265 |
+
raise ValueError(error)
|
| 266 |
+
|
| 267 |
+
def _compute_nonce(self, msg_hash):
|
| 268 |
+
# hash is not used
|
| 269 |
+
return Integer.random_range(min_inclusive=1,
|
| 270 |
+
max_exclusive=self._order,
|
| 271 |
+
randfunc=self._randfunc)
|
| 272 |
+
|
| 273 |
+
def _valid_hash(self, msg_hash):
|
| 274 |
+
"""Verify that SHA-1, SHA-2 or SHA-3 are used"""
|
| 275 |
+
return (msg_hash.oid == "1.3.14.3.2.26" or
|
| 276 |
+
msg_hash.oid.startswith("2.16.840.1.101.3.4.2."))
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class FipsEcDsaSigScheme(DssSigScheme):
|
| 280 |
+
|
| 281 |
+
def __init__(self, key, encoding, order, randfunc):
|
| 282 |
+
super(FipsEcDsaSigScheme, self).__init__(key, encoding, order)
|
| 283 |
+
self._randfunc = randfunc
|
| 284 |
+
|
| 285 |
+
def _compute_nonce(self, msg_hash):
|
| 286 |
+
return Integer.random_range(min_inclusive=1,
|
| 287 |
+
max_exclusive=self._key._curve.order,
|
| 288 |
+
randfunc=self._randfunc)
|
| 289 |
+
|
| 290 |
+
def _valid_hash(self, msg_hash):
|
| 291 |
+
"""Verify that the strength of the hash matches or exceeds
|
| 292 |
+
the strength of the EC. We fail if the hash is too weak."""
|
| 293 |
+
|
| 294 |
+
modulus_bits = self._key.pointQ.size_in_bits()
|
| 295 |
+
|
| 296 |
+
# SHS: SHA-2, SHA-3, truncated SHA-512
|
| 297 |
+
sha224 = ("2.16.840.1.101.3.4.2.4", "2.16.840.1.101.3.4.2.7", "2.16.840.1.101.3.4.2.5")
|
| 298 |
+
sha256 = ("2.16.840.1.101.3.4.2.1", "2.16.840.1.101.3.4.2.8", "2.16.840.1.101.3.4.2.6")
|
| 299 |
+
sha384 = ("2.16.840.1.101.3.4.2.2", "2.16.840.1.101.3.4.2.9")
|
| 300 |
+
sha512 = ("2.16.840.1.101.3.4.2.3", "2.16.840.1.101.3.4.2.10")
|
| 301 |
+
shs = sha224 + sha256 + sha384 + sha512
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
result = msg_hash.oid in shs
|
| 305 |
+
except AttributeError:
|
| 306 |
+
result = False
|
| 307 |
+
return result
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def new(key, mode, encoding='binary', randfunc=None):
|
| 311 |
+
"""Create a signature object :class:`DssSigScheme` that
|
| 312 |
+
can perform (EC)DSA signature or verification.
|
| 313 |
+
|
| 314 |
+
.. note::
|
| 315 |
+
Refer to `NIST SP 800 Part 1 Rev 4`_ (or newer release) for an
|
| 316 |
+
overview of the recommended key lengths.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
key (:class:`Crypto.PublicKey.DSA` or :class:`Crypto.PublicKey.ECC`):
|
| 320 |
+
The key to use for computing the signature (*private* keys only)
|
| 321 |
+
or for verifying one.
|
| 322 |
+
For DSA keys, let ``L`` and ``N`` be the bit lengths of the modulus ``p``
|
| 323 |
+
and of ``q``: the pair ``(L,N)`` must appear in the following list,
|
| 324 |
+
in compliance to section 4.2 of `FIPS 186-4`_:
|
| 325 |
+
|
| 326 |
+
- (1024, 160) *legacy only; do not create new signatures with this*
|
| 327 |
+
- (2048, 224) *deprecated; do not create new signatures with this*
|
| 328 |
+
- (2048, 256)
|
| 329 |
+
- (3072, 256)
|
| 330 |
+
|
| 331 |
+
For ECC, only keys over P-224, P-256, P-384, and P-521 are accepted.
|
| 332 |
+
|
| 333 |
+
mode (string):
|
| 334 |
+
The parameter can take these values:
|
| 335 |
+
|
| 336 |
+
- ``'fips-186-3'``. The signature generation is randomized and carried out
|
| 337 |
+
according to `FIPS 186-3`_: the nonce ``k`` is taken from the RNG.
|
| 338 |
+
- ``'deterministic-rfc6979'``. The signature generation is not
|
| 339 |
+
randomized. See RFC6979_.
|
| 340 |
+
|
| 341 |
+
encoding (string):
|
| 342 |
+
How the signature is encoded. This value determines the output of
|
| 343 |
+
:meth:`sign` and the input to :meth:`verify`.
|
| 344 |
+
|
| 345 |
+
The following values are accepted:
|
| 346 |
+
|
| 347 |
+
- ``'binary'`` (default), the signature is the raw concatenation
|
| 348 |
+
of ``r`` and ``s``. It is defined in the IEEE P.1363 standard.
|
| 349 |
+
For DSA, the size in bytes of the signature is ``N/4`` bytes
|
| 350 |
+
(e.g. 64 for ``N=256``).
|
| 351 |
+
For ECDSA, the signature is always twice the length of a point
|
| 352 |
+
coordinate (e.g. 64 bytes for P-256).
|
| 353 |
+
|
| 354 |
+
- ``'der'``, the signature is a ASN.1 DER SEQUENCE
|
| 355 |
+
with two INTEGERs (``r`` and ``s``). It is defined in RFC3279_.
|
| 356 |
+
The size of the signature is variable.
|
| 357 |
+
|
| 358 |
+
randfunc (callable):
|
| 359 |
+
A function that returns random ``bytes``, of a given length.
|
| 360 |
+
If omitted, the internal RNG is used.
|
| 361 |
+
Only applicable for the *'fips-186-3'* mode.
|
| 362 |
+
|
| 363 |
+
.. _FIPS 186-3: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
|
| 364 |
+
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
| 365 |
+
.. _NIST SP 800 Part 1 Rev 4: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf
|
| 366 |
+
.. _RFC6979: http://tools.ietf.org/html/rfc6979
|
| 367 |
+
.. _RFC3279: https://tools.ietf.org/html/rfc3279#section-2.2.2
|
| 368 |
+
"""
|
| 369 |
+
|
| 370 |
+
# The goal of the 'mode' parameter is to avoid to
|
| 371 |
+
# have the current version of the standard as default.
|
| 372 |
+
#
|
| 373 |
+
# Over time, such version will be superseded by (for instance)
|
| 374 |
+
# FIPS 186-4 and it will be odd to have -3 as default.
|
| 375 |
+
|
| 376 |
+
if encoding not in ('binary', 'der'):
|
| 377 |
+
raise ValueError("Unknown encoding '%s'" % encoding)
|
| 378 |
+
|
| 379 |
+
if isinstance(key, EccKey):
|
| 380 |
+
order = key._curve.order
|
| 381 |
+
private_key_attr = 'd'
|
| 382 |
+
if not key.curve.startswith("NIST"):
|
| 383 |
+
raise ValueError("ECC key is not on a NIST P curve")
|
| 384 |
+
elif isinstance(key, DsaKey):
|
| 385 |
+
order = Integer(key.q)
|
| 386 |
+
private_key_attr = 'x'
|
| 387 |
+
else:
|
| 388 |
+
raise ValueError("Unsupported key type " + str(type(key)))
|
| 389 |
+
|
| 390 |
+
if key.has_private():
|
| 391 |
+
private_key = getattr(key, private_key_attr)
|
| 392 |
+
else:
|
| 393 |
+
private_key = None
|
| 394 |
+
|
| 395 |
+
if mode == 'deterministic-rfc6979':
|
| 396 |
+
return DeterministicDsaSigScheme(key, encoding, order, private_key)
|
| 397 |
+
elif mode == 'fips-186-3':
|
| 398 |
+
if isinstance(key, EccKey):
|
| 399 |
+
return FipsEcDsaSigScheme(key, encoding, order, randfunc)
|
| 400 |
+
else:
|
| 401 |
+
return FipsDsaSigScheme(key, encoding, order, randfunc)
|
| 402 |
+
else:
|
| 403 |
+
raise ValueError("Unknown DSS mode '%s'" % mode)
|
wemm/lib/python3.10/site-packages/Crypto/Signature/DSS.pyi
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Union, Optional, Callable
|
| 2 |
+
from typing_extensions import Protocol
|
| 3 |
+
|
| 4 |
+
from Crypto.PublicKey.DSA import DsaKey
|
| 5 |
+
from Crypto.PublicKey.ECC import EccKey
|
| 6 |
+
|
| 7 |
+
class Hash(Protocol):
|
| 8 |
+
def digest(self) -> bytes: ...
|
| 9 |
+
|
| 10 |
+
__all__ = ['new']
|
| 11 |
+
|
| 12 |
+
class DssSigScheme:
|
| 13 |
+
def __init__(self, key: Union[DsaKey, EccKey], encoding: str, order: int) -> None: ...
|
| 14 |
+
def can_sign(self) -> bool: ...
|
| 15 |
+
def sign(self, msg_hash: Hash) -> bytes: ...
|
| 16 |
+
def verify(self, msg_hash: Hash, signature: bytes) -> bool: ...
|
| 17 |
+
|
| 18 |
+
class DeterministicDsaSigScheme(DssSigScheme):
|
| 19 |
+
def __init__(self, key, encoding, order, private_key) -> None: ...
|
| 20 |
+
|
| 21 |
+
class FipsDsaSigScheme(DssSigScheme):
|
| 22 |
+
def __init__(self, key: DsaKey, encoding: str, order: int, randfunc: Callable) -> None: ...
|
| 23 |
+
|
| 24 |
+
class FipsEcDsaSigScheme(DssSigScheme):
|
| 25 |
+
def __init__(self, key: EccKey, encoding: str, order: int, randfunc: Callable) -> None: ...
|
| 26 |
+
|
| 27 |
+
def new(key: Union[DsaKey, EccKey], mode: str, encoding: Optional[str]='binary', randfunc: Optional[Callable]=None) -> Union[DeterministicDsaSigScheme, FipsDsaSigScheme, FipsEcDsaSigScheme]: ...
|
wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/DSS.cpython-310.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/PKCS1_v1_5.cpython-310.pyc
ADDED
|
Binary file (732 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/pkcs1_15.cpython-310.pyc
ADDED
|
Binary file (5.62 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Signature/__pycache__/pss.cpython-310.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/Crypto/Signature/eddsa.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2022, Legrandin <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
from Crypto.Math.Numbers import Integer
|
| 32 |
+
|
| 33 |
+
from Crypto.Hash import SHA512, SHAKE256
|
| 34 |
+
from Crypto.Util.py3compat import bchr, is_bytes
|
| 35 |
+
from Crypto.PublicKey.ECC import (EccKey,
|
| 36 |
+
construct,
|
| 37 |
+
_import_ed25519_public_key,
|
| 38 |
+
_import_ed448_public_key)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def import_public_key(encoded):
|
| 42 |
+
"""Create a new Ed25519 or Ed448 public key object,
|
| 43 |
+
starting from the key encoded as raw ``bytes``,
|
| 44 |
+
in the format described in RFC8032.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
encoded (bytes):
|
| 48 |
+
The EdDSA public key to import.
|
| 49 |
+
It must be 32 bytes for Ed25519, and 57 bytes for Ed448.
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
:class:`Crypto.PublicKey.EccKey` : a new ECC key object.
|
| 53 |
+
|
| 54 |
+
Raises:
|
| 55 |
+
ValueError: when the given key cannot be parsed.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
if len(encoded) == 32:
|
| 59 |
+
x, y = _import_ed25519_public_key(encoded)
|
| 60 |
+
curve_name = "Ed25519"
|
| 61 |
+
elif len(encoded) == 57:
|
| 62 |
+
x, y = _import_ed448_public_key(encoded)
|
| 63 |
+
curve_name = "Ed448"
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError("Not an EdDSA key (%d bytes)" % len(encoded))
|
| 66 |
+
return construct(curve=curve_name, point_x=x, point_y=y)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def import_private_key(encoded):
|
| 70 |
+
"""Create a new Ed25519 or Ed448 private key object,
|
| 71 |
+
starting from the key encoded as raw ``bytes``,
|
| 72 |
+
in the format described in RFC8032.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
encoded (bytes):
|
| 76 |
+
The EdDSA private key to import.
|
| 77 |
+
It must be 32 bytes for Ed25519, and 57 bytes for Ed448.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
:class:`Crypto.PublicKey.EccKey` : a new ECC key object.
|
| 81 |
+
|
| 82 |
+
Raises:
|
| 83 |
+
ValueError: when the given key cannot be parsed.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
if len(encoded) == 32:
|
| 87 |
+
curve_name = "ed25519"
|
| 88 |
+
elif len(encoded) == 57:
|
| 89 |
+
curve_name = "ed448"
|
| 90 |
+
else:
|
| 91 |
+
raise ValueError("Incorrect length. Only EdDSA private keys are supported.")
|
| 92 |
+
|
| 93 |
+
# Note that the private key is truly a sequence of random bytes,
|
| 94 |
+
# so we cannot check its correctness in any way.
|
| 95 |
+
|
| 96 |
+
return construct(seed=encoded, curve=curve_name)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class EdDSASigScheme(object):
|
| 100 |
+
"""An EdDSA signature object.
|
| 101 |
+
Do not instantiate directly.
|
| 102 |
+
Use :func:`Crypto.Signature.eddsa.new`.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
def __init__(self, key, context):
|
| 106 |
+
"""Create a new EdDSA object.
|
| 107 |
+
|
| 108 |
+
Do not instantiate this object directly,
|
| 109 |
+
use `Crypto.Signature.DSS.new` instead.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
self._key = key
|
| 113 |
+
self._context = context
|
| 114 |
+
self._A = key._export_eddsa_public()
|
| 115 |
+
self._order = key._curve.order
|
| 116 |
+
|
| 117 |
+
def can_sign(self):
|
| 118 |
+
"""Return ``True`` if this signature object can be used
|
| 119 |
+
for signing messages."""
|
| 120 |
+
|
| 121 |
+
return self._key.has_private()
|
| 122 |
+
|
| 123 |
+
def sign(self, msg_or_hash):
|
| 124 |
+
"""Compute the EdDSA signature of a message.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
msg_or_hash (bytes or a hash object):
|
| 128 |
+
The message to sign (``bytes``, in case of *PureEdDSA*) or
|
| 129 |
+
the hash that was carried out over the message (hash object, for *HashEdDSA*).
|
| 130 |
+
|
| 131 |
+
The hash object must be :class:`Crypto.Hash.SHA512` for Ed25519,
|
| 132 |
+
and :class:`Crypto.Hash.SHAKE256` object for Ed448.
|
| 133 |
+
|
| 134 |
+
:return: The signature as ``bytes``. It is always 64 bytes for Ed25519, and 114 bytes for Ed448.
|
| 135 |
+
:raise TypeError: if the EdDSA key has no private half
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
if not self._key.has_private():
|
| 139 |
+
raise TypeError("Private key is needed to sign")
|
| 140 |
+
|
| 141 |
+
if self._key.curve == "Ed25519":
|
| 142 |
+
ph = isinstance(msg_or_hash, SHA512.SHA512Hash)
|
| 143 |
+
if not (ph or is_bytes(msg_or_hash)):
|
| 144 |
+
raise TypeError("'msg_or_hash' must be bytes of a SHA-512 hash")
|
| 145 |
+
eddsa_sign_method = self._sign_ed25519
|
| 146 |
+
|
| 147 |
+
elif self._key.curve == "Ed448":
|
| 148 |
+
ph = isinstance(msg_or_hash, SHAKE256.SHAKE256_XOF)
|
| 149 |
+
if not (ph or is_bytes(msg_or_hash)):
|
| 150 |
+
raise TypeError("'msg_or_hash' must be bytes of a SHAKE256 hash")
|
| 151 |
+
eddsa_sign_method = self._sign_ed448
|
| 152 |
+
|
| 153 |
+
else:
|
| 154 |
+
raise ValueError("Incorrect curve for EdDSA")
|
| 155 |
+
|
| 156 |
+
return eddsa_sign_method(msg_or_hash, ph)
|
| 157 |
+
|
| 158 |
+
def _sign_ed25519(self, msg_or_hash, ph):
|
| 159 |
+
|
| 160 |
+
if self._context or ph:
|
| 161 |
+
flag = int(ph)
|
| 162 |
+
# dom2(flag, self._context)
|
| 163 |
+
dom2 = b'SigEd25519 no Ed25519 collisions' + bchr(flag) + \
|
| 164 |
+
bchr(len(self._context)) + self._context
|
| 165 |
+
else:
|
| 166 |
+
dom2 = b''
|
| 167 |
+
|
| 168 |
+
PHM = msg_or_hash.digest() if ph else msg_or_hash
|
| 169 |
+
|
| 170 |
+
# See RFC 8032, section 5.1.6
|
| 171 |
+
|
| 172 |
+
# Step 2
|
| 173 |
+
r_hash = SHA512.new(dom2 + self._key._prefix + PHM).digest()
|
| 174 |
+
r = Integer.from_bytes(r_hash, 'little') % self._order
|
| 175 |
+
# Step 3
|
| 176 |
+
R_pk = EccKey(point=r * self._key._curve.G)._export_eddsa_public()
|
| 177 |
+
# Step 4
|
| 178 |
+
k_hash = SHA512.new(dom2 + R_pk + self._A + PHM).digest()
|
| 179 |
+
k = Integer.from_bytes(k_hash, 'little') % self._order
|
| 180 |
+
# Step 5
|
| 181 |
+
s = (r + k * self._key.d) % self._order
|
| 182 |
+
|
| 183 |
+
return R_pk + s.to_bytes(32, 'little')
|
| 184 |
+
|
| 185 |
+
def _sign_ed448(self, msg_or_hash, ph):
|
| 186 |
+
|
| 187 |
+
flag = int(ph)
|
| 188 |
+
# dom4(flag, self._context)
|
| 189 |
+
dom4 = b'SigEd448' + bchr(flag) + \
|
| 190 |
+
bchr(len(self._context)) + self._context
|
| 191 |
+
|
| 192 |
+
PHM = msg_or_hash.read(64) if ph else msg_or_hash
|
| 193 |
+
|
| 194 |
+
# See RFC 8032, section 5.2.6
|
| 195 |
+
|
| 196 |
+
# Step 2
|
| 197 |
+
r_hash = SHAKE256.new(dom4 + self._key._prefix + PHM).read(114)
|
| 198 |
+
r = Integer.from_bytes(r_hash, 'little') % self._order
|
| 199 |
+
# Step 3
|
| 200 |
+
R_pk = EccKey(point=r * self._key._curve.G)._export_eddsa_public()
|
| 201 |
+
# Step 4
|
| 202 |
+
k_hash = SHAKE256.new(dom4 + R_pk + self._A + PHM).read(114)
|
| 203 |
+
k = Integer.from_bytes(k_hash, 'little') % self._order
|
| 204 |
+
# Step 5
|
| 205 |
+
s = (r + k * self._key.d) % self._order
|
| 206 |
+
|
| 207 |
+
return R_pk + s.to_bytes(57, 'little')
|
| 208 |
+
|
| 209 |
+
def verify(self, msg_or_hash, signature):
|
| 210 |
+
"""Check if an EdDSA signature is authentic.
|
| 211 |
+
|
| 212 |
+
Args:
|
| 213 |
+
msg_or_hash (bytes or a hash object):
|
| 214 |
+
The message to verify (``bytes``, in case of *PureEdDSA*) or
|
| 215 |
+
the hash that was carried out over the message (hash object, for *HashEdDSA*).
|
| 216 |
+
|
| 217 |
+
The hash object must be :class:`Crypto.Hash.SHA512` object for Ed25519,
|
| 218 |
+
and :class:`Crypto.Hash.SHAKE256` for Ed448.
|
| 219 |
+
|
| 220 |
+
signature (``bytes``):
|
| 221 |
+
The signature that needs to be validated.
|
| 222 |
+
It must be 64 bytes for Ed25519, and 114 bytes for Ed448.
|
| 223 |
+
|
| 224 |
+
:raise ValueError: if the signature is not authentic
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
if self._key.curve == "Ed25519":
|
| 228 |
+
ph = isinstance(msg_or_hash, SHA512.SHA512Hash)
|
| 229 |
+
if not (ph or is_bytes(msg_or_hash)):
|
| 230 |
+
raise TypeError("'msg_or_hash' must be bytes of a SHA-512 hash")
|
| 231 |
+
eddsa_verify_method = self._verify_ed25519
|
| 232 |
+
|
| 233 |
+
elif self._key.curve == "Ed448":
|
| 234 |
+
ph = isinstance(msg_or_hash, SHAKE256.SHAKE256_XOF)
|
| 235 |
+
if not (ph or is_bytes(msg_or_hash)):
|
| 236 |
+
raise TypeError("'msg_or_hash' must be bytes of a SHAKE256 hash")
|
| 237 |
+
eddsa_verify_method = self._verify_ed448
|
| 238 |
+
|
| 239 |
+
else:
|
| 240 |
+
raise ValueError("Incorrect curve for EdDSA")
|
| 241 |
+
|
| 242 |
+
return eddsa_verify_method(msg_or_hash, signature, ph)
|
| 243 |
+
|
| 244 |
+
def _verify_ed25519(self, msg_or_hash, signature, ph):
|
| 245 |
+
|
| 246 |
+
if len(signature) != 64:
|
| 247 |
+
raise ValueError("The signature is not authentic (length)")
|
| 248 |
+
|
| 249 |
+
if self._context or ph:
|
| 250 |
+
flag = int(ph)
|
| 251 |
+
dom2 = b'SigEd25519 no Ed25519 collisions' + bchr(flag) + \
|
| 252 |
+
bchr(len(self._context)) + self._context
|
| 253 |
+
else:
|
| 254 |
+
dom2 = b''
|
| 255 |
+
|
| 256 |
+
PHM = msg_or_hash.digest() if ph else msg_or_hash
|
| 257 |
+
|
| 258 |
+
# Section 5.1.7
|
| 259 |
+
|
| 260 |
+
# Step 1
|
| 261 |
+
try:
|
| 262 |
+
R = import_public_key(signature[:32]).pointQ
|
| 263 |
+
except ValueError:
|
| 264 |
+
raise ValueError("The signature is not authentic (R)")
|
| 265 |
+
s = Integer.from_bytes(signature[32:], 'little')
|
| 266 |
+
if s > self._order:
|
| 267 |
+
raise ValueError("The signature is not authentic (S)")
|
| 268 |
+
# Step 2
|
| 269 |
+
k_hash = SHA512.new(dom2 + signature[:32] + self._A + PHM).digest()
|
| 270 |
+
k = Integer.from_bytes(k_hash, 'little') % self._order
|
| 271 |
+
# Step 3
|
| 272 |
+
point1 = s * 8 * self._key._curve.G
|
| 273 |
+
# OPTIMIZE: with double-scalar multiplication, with no SCA
|
| 274 |
+
# countermeasures because it is public values
|
| 275 |
+
point2 = 8 * R + k * 8 * self._key.pointQ
|
| 276 |
+
if point1 != point2:
|
| 277 |
+
raise ValueError("The signature is not authentic")
|
| 278 |
+
|
| 279 |
+
def _verify_ed448(self, msg_or_hash, signature, ph):
|
| 280 |
+
|
| 281 |
+
if len(signature) != 114:
|
| 282 |
+
raise ValueError("The signature is not authentic (length)")
|
| 283 |
+
|
| 284 |
+
flag = int(ph)
|
| 285 |
+
# dom4(flag, self._context)
|
| 286 |
+
dom4 = b'SigEd448' + bchr(flag) + \
|
| 287 |
+
bchr(len(self._context)) + self._context
|
| 288 |
+
|
| 289 |
+
PHM = msg_or_hash.read(64) if ph else msg_or_hash
|
| 290 |
+
|
| 291 |
+
# Section 5.2.7
|
| 292 |
+
|
| 293 |
+
# Step 1
|
| 294 |
+
try:
|
| 295 |
+
R = import_public_key(signature[:57]).pointQ
|
| 296 |
+
except ValueError:
|
| 297 |
+
raise ValueError("The signature is not authentic (R)")
|
| 298 |
+
s = Integer.from_bytes(signature[57:], 'little')
|
| 299 |
+
if s > self._order:
|
| 300 |
+
raise ValueError("The signature is not authentic (S)")
|
| 301 |
+
# Step 2
|
| 302 |
+
k_hash = SHAKE256.new(dom4 + signature[:57] + self._A + PHM).read(114)
|
| 303 |
+
k = Integer.from_bytes(k_hash, 'little') % self._order
|
| 304 |
+
# Step 3
|
| 305 |
+
point1 = s * 8 * self._key._curve.G
|
| 306 |
+
# OPTIMIZE: with double-scalar multiplication, with no SCA
|
| 307 |
+
# countermeasures because it is public values
|
| 308 |
+
point2 = 8 * R + k * 8 * self._key.pointQ
|
| 309 |
+
if point1 != point2:
|
| 310 |
+
raise ValueError("The signature is not authentic")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def new(key, mode, context=None):
|
| 314 |
+
"""Create a signature object :class:`EdDSASigScheme` that
|
| 315 |
+
can perform or verify an EdDSA signature.
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
key (:class:`Crypto.PublicKey.ECC` object):
|
| 319 |
+
The key to use for computing the signature (*private* keys only)
|
| 320 |
+
or for verifying one.
|
| 321 |
+
The key must be on the curve ``Ed25519`` or ``Ed448``.
|
| 322 |
+
|
| 323 |
+
mode (string):
|
| 324 |
+
This parameter must be ``'rfc8032'``.
|
| 325 |
+
|
| 326 |
+
context (bytes):
|
| 327 |
+
Up to 255 bytes of `context <https://datatracker.ietf.org/doc/html/rfc8032#page-41>`_,
|
| 328 |
+
which is a constant byte string to segregate different protocols or
|
| 329 |
+
different applications of the same key.
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
if not isinstance(key, EccKey) or key.curve not in ("Ed25519", "Ed448"):
|
| 333 |
+
raise ValueError("EdDSA can only be used with EdDSA keys")
|
| 334 |
+
|
| 335 |
+
if mode != 'rfc8032':
|
| 336 |
+
raise ValueError("Mode must be 'rfc8032'")
|
| 337 |
+
|
| 338 |
+
if context is None:
|
| 339 |
+
context = b''
|
| 340 |
+
elif len(context) > 255:
|
| 341 |
+
raise ValueError("Context for EdDSA must not be longer than 255 bytes")
|
| 342 |
+
|
| 343 |
+
return EdDSASigScheme(key, context)
|
wemm/lib/python3.10/site-packages/Crypto/Signature/eddsa.pyi
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Union, Optional
|
| 2 |
+
from typing_extensions import Protocol
|
| 3 |
+
from Crypto.PublicKey.ECC import EccKey
|
| 4 |
+
|
| 5 |
+
class Hash(Protocol):
|
| 6 |
+
def digest(self) -> bytes: ...
|
| 7 |
+
|
| 8 |
+
class XOF(Protocol):
|
| 9 |
+
def read(self, len: int) -> bytes: ...
|
| 10 |
+
|
| 11 |
+
def import_public_key(encoded: bytes) -> EccKey: ...
|
| 12 |
+
def import_private_key(encoded: bytes) -> EccKey: ...
|
| 13 |
+
|
| 14 |
+
class EdDSASigScheme(object):
|
| 15 |
+
|
| 16 |
+
def __init__(self, key: EccKey, context: bytes) -> None: ...
|
| 17 |
+
def can_sign(self) -> bool: ...
|
| 18 |
+
def sign(self, msg_or_hash: Union[bytes, Hash, XOF]) -> bytes: ...
|
| 19 |
+
def verify(self, msg_or_hash: Union[bytes, Hash, XOF], signature: bytes) -> None: ...
|
| 20 |
+
|
| 21 |
+
def new(key: EccKey, mode: str, context: Optional[bytes]=None) -> EdDSASigScheme: ...
|
wemm/lib/python3.10/site-packages/Crypto/Signature/pss.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================================================================
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Redistribution and use in source and binary forms, with or without
|
| 7 |
+
# modification, are permitted provided that the following conditions
|
| 8 |
+
# are met:
|
| 9 |
+
#
|
| 10 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 11 |
+
# notice, this list of conditions and the following disclaimer.
|
| 12 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 13 |
+
# notice, this list of conditions and the following disclaimer in
|
| 14 |
+
# the documentation and/or other materials provided with the
|
| 15 |
+
# distribution.
|
| 16 |
+
#
|
| 17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 18 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 19 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 20 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 21 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 22 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 23 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 24 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 26 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 27 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 28 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
# ===================================================================
|
| 30 |
+
|
| 31 |
+
from Crypto.Util.py3compat import bchr, bord, iter_range
|
| 32 |
+
import Crypto.Util.number
|
| 33 |
+
from Crypto.Util.number import (ceil_div,
|
| 34 |
+
long_to_bytes,
|
| 35 |
+
bytes_to_long
|
| 36 |
+
)
|
| 37 |
+
from Crypto.Util.strxor import strxor
|
| 38 |
+
from Crypto import Random
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class PSS_SigScheme:
|
| 42 |
+
"""A signature object for ``RSASSA-PSS``.
|
| 43 |
+
Do not instantiate directly.
|
| 44 |
+
Use :func:`Crypto.Signature.pss.new`.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self, key, mgfunc, saltLen, randfunc):
|
| 48 |
+
"""Initialize this PKCS#1 PSS signature scheme object.
|
| 49 |
+
|
| 50 |
+
:Parameters:
|
| 51 |
+
key : an RSA key object
|
| 52 |
+
If a private half is given, both signature and
|
| 53 |
+
verification are possible.
|
| 54 |
+
If a public half is given, only verification is possible.
|
| 55 |
+
mgfunc : callable
|
| 56 |
+
A mask generation function that accepts two parameters:
|
| 57 |
+
a string to use as seed, and the lenth of the mask to
|
| 58 |
+
generate, in bytes.
|
| 59 |
+
saltLen : integer
|
| 60 |
+
Length of the salt, in bytes.
|
| 61 |
+
randfunc : callable
|
| 62 |
+
A function that returns random bytes.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
self._key = key
|
| 66 |
+
self._saltLen = saltLen
|
| 67 |
+
self._mgfunc = mgfunc
|
| 68 |
+
self._randfunc = randfunc
|
| 69 |
+
|
| 70 |
+
def can_sign(self):
|
| 71 |
+
"""Return ``True`` if this object can be used to sign messages."""
|
| 72 |
+
return self._key.has_private()
|
| 73 |
+
|
| 74 |
+
def sign(self, msg_hash):
|
| 75 |
+
"""Create the PKCS#1 PSS signature of a message.
|
| 76 |
+
|
| 77 |
+
This function is also called ``RSASSA-PSS-SIGN`` and
|
| 78 |
+
it is specified in
|
| 79 |
+
`section 8.1.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#section-8.1.1>`_.
|
| 80 |
+
|
| 81 |
+
:parameter msg_hash:
|
| 82 |
+
This is an object from the :mod:`Crypto.Hash` package.
|
| 83 |
+
It has been used to digest the message to sign.
|
| 84 |
+
:type msg_hash: hash object
|
| 85 |
+
|
| 86 |
+
:return: the signature encoded as a *byte string*.
|
| 87 |
+
:raise ValueError: if the RSA key is not long enough for the given hash algorithm.
|
| 88 |
+
:raise TypeError: if the RSA key has no private half.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
# Set defaults for salt length and mask generation function
|
| 92 |
+
if self._saltLen is None:
|
| 93 |
+
sLen = msg_hash.digest_size
|
| 94 |
+
else:
|
| 95 |
+
sLen = self._saltLen
|
| 96 |
+
|
| 97 |
+
if self._mgfunc is None:
|
| 98 |
+
mgf = lambda x, y: MGF1(x, y, msg_hash)
|
| 99 |
+
else:
|
| 100 |
+
mgf = self._mgfunc
|
| 101 |
+
|
| 102 |
+
modBits = Crypto.Util.number.size(self._key.n)
|
| 103 |
+
|
| 104 |
+
# See 8.1.1 in RFC3447
|
| 105 |
+
k = ceil_div(modBits, 8) # k is length in bytes of the modulus
|
| 106 |
+
# Step 1
|
| 107 |
+
em = _EMSA_PSS_ENCODE(msg_hash, modBits-1, self._randfunc, mgf, sLen)
|
| 108 |
+
# Step 2a (OS2IP)
|
| 109 |
+
em_int = bytes_to_long(em)
|
| 110 |
+
# Step 2b (RSASP1) and Step 2c (I2OSP)
|
| 111 |
+
signature = self._key._decrypt_to_bytes(em_int)
|
| 112 |
+
# Verify no faults occurred
|
| 113 |
+
if em_int != pow(bytes_to_long(signature), self._key.e, self._key.n):
|
| 114 |
+
raise ValueError("Fault detected in RSA private key operation")
|
| 115 |
+
return signature
|
| 116 |
+
|
| 117 |
+
def verify(self, msg_hash, signature):
|
| 118 |
+
"""Check if the PKCS#1 PSS signature over a message is valid.
|
| 119 |
+
|
| 120 |
+
This function is also called ``RSASSA-PSS-VERIFY`` and
|
| 121 |
+
it is specified in
|
| 122 |
+
`section 8.1.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#section-8.1.2>`_.
|
| 123 |
+
|
| 124 |
+
:parameter msg_hash:
|
| 125 |
+
The hash that was carried out over the message. This is an object
|
| 126 |
+
belonging to the :mod:`Crypto.Hash` module.
|
| 127 |
+
:type parameter: hash object
|
| 128 |
+
|
| 129 |
+
:parameter signature:
|
| 130 |
+
The signature that needs to be validated.
|
| 131 |
+
:type signature: bytes
|
| 132 |
+
|
| 133 |
+
:raise ValueError: if the signature is not valid.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
# Set defaults for salt length and mask generation function
|
| 137 |
+
if self._saltLen is None:
|
| 138 |
+
sLen = msg_hash.digest_size
|
| 139 |
+
else:
|
| 140 |
+
sLen = self._saltLen
|
| 141 |
+
if self._mgfunc:
|
| 142 |
+
mgf = self._mgfunc
|
| 143 |
+
else:
|
| 144 |
+
mgf = lambda x, y: MGF1(x, y, msg_hash)
|
| 145 |
+
|
| 146 |
+
modBits = Crypto.Util.number.size(self._key.n)
|
| 147 |
+
|
| 148 |
+
# See 8.1.2 in RFC3447
|
| 149 |
+
k = ceil_div(modBits, 8) # Convert from bits to bytes
|
| 150 |
+
# Step 1
|
| 151 |
+
if len(signature) != k:
|
| 152 |
+
raise ValueError("Incorrect signature")
|
| 153 |
+
# Step 2a (O2SIP)
|
| 154 |
+
signature_int = bytes_to_long(signature)
|
| 155 |
+
# Step 2b (RSAVP1)
|
| 156 |
+
em_int = self._key._encrypt(signature_int)
|
| 157 |
+
# Step 2c (I2OSP)
|
| 158 |
+
emLen = ceil_div(modBits - 1, 8)
|
| 159 |
+
em = long_to_bytes(em_int, emLen)
|
| 160 |
+
# Step 3/4
|
| 161 |
+
_EMSA_PSS_VERIFY(msg_hash, em, modBits-1, mgf, sLen)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def MGF1(mgfSeed, maskLen, hash_gen):
|
| 165 |
+
"""Mask Generation Function, described in `B.2.1 of RFC8017
|
| 166 |
+
<https://tools.ietf.org/html/rfc8017>`_.
|
| 167 |
+
|
| 168 |
+
:param mfgSeed:
|
| 169 |
+
seed from which the mask is generated
|
| 170 |
+
:type mfgSeed: byte string
|
| 171 |
+
|
| 172 |
+
:param maskLen:
|
| 173 |
+
intended length in bytes of the mask
|
| 174 |
+
:type maskLen: integer
|
| 175 |
+
|
| 176 |
+
:param hash_gen:
|
| 177 |
+
A module or a hash object from :mod:`Crypto.Hash`
|
| 178 |
+
:type hash_object:
|
| 179 |
+
|
| 180 |
+
:return: the mask, as a *byte string*
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
T = b""
|
| 184 |
+
for counter in iter_range(ceil_div(maskLen, hash_gen.digest_size)):
|
| 185 |
+
c = long_to_bytes(counter, 4)
|
| 186 |
+
hobj = hash_gen.new()
|
| 187 |
+
hobj.update(mgfSeed + c)
|
| 188 |
+
T = T + hobj.digest()
|
| 189 |
+
assert(len(T) >= maskLen)
|
| 190 |
+
return T[:maskLen]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen):
|
| 194 |
+
r"""
|
| 195 |
+
Implement the ``EMSA-PSS-ENCODE`` function, as defined
|
| 196 |
+
in PKCS#1 v2.1 (RFC3447, 9.1.1).
|
| 197 |
+
|
| 198 |
+
The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M``
|
| 199 |
+
as input, and hash it internally. Here, we expect that the message
|
| 200 |
+
has already been hashed instead.
|
| 201 |
+
|
| 202 |
+
:Parameters:
|
| 203 |
+
mhash : hash object
|
| 204 |
+
The hash object that holds the digest of the message being signed.
|
| 205 |
+
emBits : int
|
| 206 |
+
Maximum length of the final encoding, in bits.
|
| 207 |
+
randFunc : callable
|
| 208 |
+
An RNG function that accepts as only parameter an int, and returns
|
| 209 |
+
a string of random bytes, to be used as salt.
|
| 210 |
+
mgf : callable
|
| 211 |
+
A mask generation function that accepts two parameters: a string to
|
| 212 |
+
use as seed, and the lenth of the mask to generate, in bytes.
|
| 213 |
+
sLen : int
|
| 214 |
+
Length of the salt, in bytes.
|
| 215 |
+
|
| 216 |
+
:Return: An ``emLen`` byte long string that encodes the hash
|
| 217 |
+
(with ``emLen = \ceil(emBits/8)``).
|
| 218 |
+
|
| 219 |
+
:Raise ValueError:
|
| 220 |
+
When digest or salt length are too big.
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
emLen = ceil_div(emBits, 8)
|
| 224 |
+
|
| 225 |
+
# Bitmask of digits that fill up
|
| 226 |
+
lmask = 0
|
| 227 |
+
for i in iter_range(8*emLen-emBits):
|
| 228 |
+
lmask = lmask >> 1 | 0x80
|
| 229 |
+
|
| 230 |
+
# Step 1 and 2 have been already done
|
| 231 |
+
# Step 3
|
| 232 |
+
if emLen < mhash.digest_size+sLen+2:
|
| 233 |
+
raise ValueError("Digest or salt length are too long"
|
| 234 |
+
" for given key size.")
|
| 235 |
+
# Step 4
|
| 236 |
+
salt = randFunc(sLen)
|
| 237 |
+
# Step 5
|
| 238 |
+
m_prime = bchr(0)*8 + mhash.digest() + salt
|
| 239 |
+
# Step 6
|
| 240 |
+
h = mhash.new()
|
| 241 |
+
h.update(m_prime)
|
| 242 |
+
# Step 7
|
| 243 |
+
ps = bchr(0)*(emLen-sLen-mhash.digest_size-2)
|
| 244 |
+
# Step 8
|
| 245 |
+
db = ps + bchr(1) + salt
|
| 246 |
+
# Step 9
|
| 247 |
+
dbMask = mgf(h.digest(), emLen-mhash.digest_size-1)
|
| 248 |
+
# Step 10
|
| 249 |
+
maskedDB = strxor(db, dbMask)
|
| 250 |
+
# Step 11
|
| 251 |
+
maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:]
|
| 252 |
+
# Step 12
|
| 253 |
+
em = maskedDB + h.digest() + bchr(0xBC)
|
| 254 |
+
return em
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):
|
| 258 |
+
"""
|
| 259 |
+
Implement the ``EMSA-PSS-VERIFY`` function, as defined
|
| 260 |
+
in PKCS#1 v2.1 (RFC3447, 9.1.2).
|
| 261 |
+
|
| 262 |
+
``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
|
| 263 |
+
and hash it internally. Here, we expect that the message has already
|
| 264 |
+
been hashed instead.
|
| 265 |
+
|
| 266 |
+
:Parameters:
|
| 267 |
+
mhash : hash object
|
| 268 |
+
The hash object that holds the digest of the message to be verified.
|
| 269 |
+
em : string
|
| 270 |
+
The signature to verify, therefore proving that the sender really
|
| 271 |
+
signed the message that was received.
|
| 272 |
+
emBits : int
|
| 273 |
+
Length of the final encoding (em), in bits.
|
| 274 |
+
mgf : callable
|
| 275 |
+
A mask generation function that accepts two parameters: a string to
|
| 276 |
+
use as seed, and the lenth of the mask to generate, in bytes.
|
| 277 |
+
sLen : int
|
| 278 |
+
Length of the salt, in bytes.
|
| 279 |
+
|
| 280 |
+
:Raise ValueError:
|
| 281 |
+
When the encoding is inconsistent, or the digest or salt lengths
|
| 282 |
+
are too big.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
emLen = ceil_div(emBits, 8)
|
| 286 |
+
|
| 287 |
+
# Bitmask of digits that fill up
|
| 288 |
+
lmask = 0
|
| 289 |
+
for i in iter_range(8*emLen-emBits):
|
| 290 |
+
lmask = lmask >> 1 | 0x80
|
| 291 |
+
|
| 292 |
+
# Step 1 and 2 have been already done
|
| 293 |
+
# Step 3
|
| 294 |
+
if emLen < mhash.digest_size+sLen+2:
|
| 295 |
+
raise ValueError("Incorrect signature")
|
| 296 |
+
# Step 4
|
| 297 |
+
if ord(em[-1:]) != 0xBC:
|
| 298 |
+
raise ValueError("Incorrect signature")
|
| 299 |
+
# Step 5
|
| 300 |
+
maskedDB = em[:emLen-mhash.digest_size-1]
|
| 301 |
+
h = em[emLen-mhash.digest_size-1:-1]
|
| 302 |
+
# Step 6
|
| 303 |
+
if lmask & bord(em[0]):
|
| 304 |
+
raise ValueError("Incorrect signature")
|
| 305 |
+
# Step 7
|
| 306 |
+
dbMask = mgf(h, emLen-mhash.digest_size-1)
|
| 307 |
+
# Step 8
|
| 308 |
+
db = strxor(maskedDB, dbMask)
|
| 309 |
+
# Step 9
|
| 310 |
+
db = bchr(bord(db[0]) & ~lmask) + db[1:]
|
| 311 |
+
# Step 10
|
| 312 |
+
if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)):
|
| 313 |
+
raise ValueError("Incorrect signature")
|
| 314 |
+
# Step 11
|
| 315 |
+
if sLen > 0:
|
| 316 |
+
salt = db[-sLen:]
|
| 317 |
+
else:
|
| 318 |
+
salt = b""
|
| 319 |
+
# Step 12
|
| 320 |
+
m_prime = bchr(0)*8 + mhash.digest() + salt
|
| 321 |
+
# Step 13
|
| 322 |
+
hobj = mhash.new()
|
| 323 |
+
hobj.update(m_prime)
|
| 324 |
+
hp = hobj.digest()
|
| 325 |
+
# Step 14
|
| 326 |
+
if h != hp:
|
| 327 |
+
raise ValueError("Incorrect signature")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def new(rsa_key, **kwargs):
|
| 331 |
+
"""Create an object for making or verifying PKCS#1 PSS signatures.
|
| 332 |
+
|
| 333 |
+
:parameter rsa_key:
|
| 334 |
+
The RSA key to use for signing or verifying the message.
|
| 335 |
+
This is a :class:`Crypto.PublicKey.RSA` object.
|
| 336 |
+
Signing is only possible when ``rsa_key`` is a **private** RSA key.
|
| 337 |
+
:type rsa_key: RSA object
|
| 338 |
+
|
| 339 |
+
:Keyword Arguments:
|
| 340 |
+
|
| 341 |
+
* *mask_func* (``callable``) --
|
| 342 |
+
A function that returns the mask (as `bytes`).
|
| 343 |
+
It must accept two parameters: a seed (as `bytes`)
|
| 344 |
+
and the length of the data to return.
|
| 345 |
+
|
| 346 |
+
If not specified, it will be the function :func:`MGF1` defined in
|
| 347 |
+
`RFC8017 <https://tools.ietf.org/html/rfc8017#page-67>`_ and
|
| 348 |
+
combined with the same hash algorithm applied to the
|
| 349 |
+
message to sign or verify.
|
| 350 |
+
|
| 351 |
+
If you want to use a different function, for instance still :func:`MGF1`
|
| 352 |
+
but together with another hash, you can do::
|
| 353 |
+
|
| 354 |
+
from Crypto.Hash import SHA256
|
| 355 |
+
from Crypto.Signature.pss import MGF1
|
| 356 |
+
mgf = lambda x, y: MGF1(x, y, SHA256)
|
| 357 |
+
|
| 358 |
+
* *salt_bytes* (``integer``) --
|
| 359 |
+
Length of the salt, in bytes.
|
| 360 |
+
It is a value between 0 and ``emLen - hLen - 2``, where ``emLen``
|
| 361 |
+
is the size of the RSA modulus and ``hLen`` is the size of the digest
|
| 362 |
+
applied to the message to sign or verify.
|
| 363 |
+
|
| 364 |
+
The salt is generated internally, you don't need to provide it.
|
| 365 |
+
|
| 366 |
+
If not specified, the salt length will be ``hLen``.
|
| 367 |
+
If it is zero, the signature scheme becomes deterministic.
|
| 368 |
+
|
| 369 |
+
Note that in some implementations such as OpenSSL the default
|
| 370 |
+
salt length is ``emLen - hLen - 2`` (even though it is not more
|
| 371 |
+
secure than ``hLen``).
|
| 372 |
+
|
| 373 |
+
* *rand_func* (``callable``) --
|
| 374 |
+
A function that returns random ``bytes``, of the desired length.
|
| 375 |
+
The default is :func:`Crypto.Random.get_random_bytes`.
|
| 376 |
+
|
| 377 |
+
:return: a :class:`PSS_SigScheme` signature object
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
mask_func = kwargs.pop("mask_func", None)
|
| 381 |
+
salt_len = kwargs.pop("salt_bytes", None)
|
| 382 |
+
rand_func = kwargs.pop("rand_func", None)
|
| 383 |
+
if rand_func is None:
|
| 384 |
+
rand_func = Random.get_random_bytes
|
| 385 |
+
if kwargs:
|
| 386 |
+
raise ValueError("Unknown keywords: " + str(kwargs.keys()))
|
| 387 |
+
return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)
|
wemm/lib/python3.10/site-packages/_yaml/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a stub package designed to roughly emulate the _yaml
|
| 2 |
+
# extension module, which previously existed as a standalone module
|
| 3 |
+
# and has been moved into the `yaml` package namespace.
|
| 4 |
+
# It does not perfectly mimic its old counterpart, but should get
|
| 5 |
+
# close enough for anyone who's relying on it even when they shouldn't.
|
| 6 |
+
import yaml
|
| 7 |
+
|
| 8 |
+
# in some circumstances, the yaml module we imoprted may be from a different version, so we need
|
| 9 |
+
# to tread carefully when poking at it here (it may not have the attributes we expect)
|
| 10 |
+
if not getattr(yaml, '__with_libyaml__', False):
|
| 11 |
+
from sys import version_info
|
| 12 |
+
|
| 13 |
+
exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError
|
| 14 |
+
raise exc("No module named '_yaml'")
|
| 15 |
+
else:
|
| 16 |
+
from yaml._yaml import *
|
| 17 |
+
import warnings
|
| 18 |
+
warnings.warn(
|
| 19 |
+
'The _yaml extension module is now located at yaml._yaml'
|
| 20 |
+
' and its location is subject to change. To use the'
|
| 21 |
+
' LibYAML-based parser and emitter, import from `yaml`:'
|
| 22 |
+
' `from yaml import CLoader as Loader, CDumper as Dumper`.',
|
| 23 |
+
DeprecationWarning
|
| 24 |
+
)
|
| 25 |
+
del warnings
|
| 26 |
+
# Don't `del yaml` here because yaml is actually an existing
|
| 27 |
+
# namespace member of _yaml.
|
| 28 |
+
|
| 29 |
+
__name__ = '_yaml'
|
| 30 |
+
# If the module is top-level (i.e. not a part of any specific package)
|
| 31 |
+
# then the attribute should be set to ''.
|
| 32 |
+
# https://docs.python.org/3.8/library/types.html
|
| 33 |
+
__package__ = ''
|
wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: attrs
|
| 3 |
+
Version: 24.3.0
|
| 4 |
+
Summary: Classes Without Boilerplate
|
| 5 |
+
Project-URL: Documentation, https://www.attrs.org/
|
| 6 |
+
Project-URL: Changelog, https://www.attrs.org/en/stable/changelog.html
|
| 7 |
+
Project-URL: GitHub, https://github.com/python-attrs/attrs
|
| 8 |
+
Project-URL: Funding, https://github.com/sponsors/hynek
|
| 9 |
+
Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-attrs?utm_source=pypi-attrs&utm_medium=pypi
|
| 10 |
+
Author-email: Hynek Schlawack <hs@ox.cx>
|
| 11 |
+
License-Expression: MIT
|
| 12 |
+
License-File: LICENSE
|
| 13 |
+
Keywords: attribute,boilerplate,class
|
| 14 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 21 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 22 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 23 |
+
Classifier: Typing :: Typed
|
| 24 |
+
Requires-Python: >=3.8
|
| 25 |
+
Provides-Extra: benchmark
|
| 26 |
+
Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'benchmark'
|
| 27 |
+
Requires-Dist: hypothesis; extra == 'benchmark'
|
| 28 |
+
Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'benchmark'
|
| 29 |
+
Requires-Dist: pympler; extra == 'benchmark'
|
| 30 |
+
Requires-Dist: pytest-codspeed; extra == 'benchmark'
|
| 31 |
+
Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'benchmark'
|
| 32 |
+
Requires-Dist: pytest-xdist[psutil]; extra == 'benchmark'
|
| 33 |
+
Requires-Dist: pytest>=4.3.0; extra == 'benchmark'
|
| 34 |
+
Provides-Extra: cov
|
| 35 |
+
Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'cov'
|
| 36 |
+
Requires-Dist: coverage[toml]>=5.3; extra == 'cov'
|
| 37 |
+
Requires-Dist: hypothesis; extra == 'cov'
|
| 38 |
+
Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'cov'
|
| 39 |
+
Requires-Dist: pympler; extra == 'cov'
|
| 40 |
+
Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'cov'
|
| 41 |
+
Requires-Dist: pytest-xdist[psutil]; extra == 'cov'
|
| 42 |
+
Requires-Dist: pytest>=4.3.0; extra == 'cov'
|
| 43 |
+
Provides-Extra: dev
|
| 44 |
+
Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'dev'
|
| 45 |
+
Requires-Dist: hypothesis; extra == 'dev'
|
| 46 |
+
Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'dev'
|
| 47 |
+
Requires-Dist: pre-commit-uv; extra == 'dev'
|
| 48 |
+
Requires-Dist: pympler; extra == 'dev'
|
| 49 |
+
Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'dev'
|
| 50 |
+
Requires-Dist: pytest-xdist[psutil]; extra == 'dev'
|
| 51 |
+
Requires-Dist: pytest>=4.3.0; extra == 'dev'
|
| 52 |
+
Provides-Extra: docs
|
| 53 |
+
Requires-Dist: cogapp; extra == 'docs'
|
| 54 |
+
Requires-Dist: furo; extra == 'docs'
|
| 55 |
+
Requires-Dist: myst-parser; extra == 'docs'
|
| 56 |
+
Requires-Dist: sphinx; extra == 'docs'
|
| 57 |
+
Requires-Dist: sphinx-notfound-page; extra == 'docs'
|
| 58 |
+
Requires-Dist: sphinxcontrib-towncrier; extra == 'docs'
|
| 59 |
+
Requires-Dist: towncrier<24.7; extra == 'docs'
|
| 60 |
+
Provides-Extra: tests
|
| 61 |
+
Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'tests'
|
| 62 |
+
Requires-Dist: hypothesis; extra == 'tests'
|
| 63 |
+
Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests'
|
| 64 |
+
Requires-Dist: pympler; extra == 'tests'
|
| 65 |
+
Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests'
|
| 66 |
+
Requires-Dist: pytest-xdist[psutil]; extra == 'tests'
|
| 67 |
+
Requires-Dist: pytest>=4.3.0; extra == 'tests'
|
| 68 |
+
Provides-Extra: tests-mypy
|
| 69 |
+
Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests-mypy'
|
| 70 |
+
Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests-mypy'
|
| 71 |
+
Description-Content-Type: text/markdown
|
| 72 |
+
|
| 73 |
+
<p align="center">
|
| 74 |
+
<a href="https://www.attrs.org/">
|
| 75 |
+
<img src="https://raw.githubusercontent.com/python-attrs/attrs/main/docs/_static/attrs_logo.svg" width="35%" alt="attrs" />
|
| 76 |
+
</a>
|
| 77 |
+
</p>
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
*attrs* is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka [dunder methods](https://www.attrs.org/en/latest/glossary.html#term-dunder-methods)).
|
| 81 |
+
[Trusted by NASA](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/personalizing-your-profile#list-of-qualifying-repositories-for-mars-2020-helicopter-contributor-achievement) for Mars missions since 2020!
|
| 82 |
+
|
| 83 |
+
Its main goal is to help you to write **concise** and **correct** software without slowing down your code.
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
## Sponsors
|
| 87 |
+
|
| 88 |
+
*attrs* would not be possible without our [amazing sponsors](https://github.com/sponsors/hynek).
|
| 89 |
+
Especially those generously supporting us at the *The Organization* tier and higher:
|
| 90 |
+
|
| 91 |
+
<!-- sponsor-break-begin -->
|
| 92 |
+
|
| 93 |
+
<p align="center">
|
| 94 |
+
|
| 95 |
+
<!-- [[[cog
|
| 96 |
+
import pathlib, tomllib
|
| 97 |
+
|
| 98 |
+
for sponsor in tomllib.loads(pathlib.Path("pyproject.toml").read_text())["tool"]["sponcon"]["sponsors"]:
|
| 99 |
+
print(f'<a href="{sponsor["url"]}"><img title="{sponsor["title"]}" src="https://www.attrs.org/en/24.3.0/_static/sponsors/{sponsor["img"]}" width="190" /></a>')
|
| 100 |
+
]]] -->
|
| 101 |
+
<a href="https://www.variomedia.de/"><img title="Variomedia AG" src="https://www.attrs.org/en/24.3.0/_static/sponsors/Variomedia.svg" width="190" /></a>
|
| 102 |
+
<a href="https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek"><img title="Tidelift" src="https://www.attrs.org/en/24.3.0/_static/sponsors/Tidelift.svg" width="190" /></a>
|
| 103 |
+
<a href="https://klaviyo.com/"><img title="Klaviyo" src="https://www.attrs.org/en/24.3.0/_static/sponsors/Klaviyo.svg" width="190" /></a>
|
| 104 |
+
<a href="https://www.emsys-renewables.com/"><img title="emsys renewables" src="https://www.attrs.org/en/24.3.0/_static/sponsors/emsys-renewables.svg" width="190" /></a>
|
| 105 |
+
<a href="https://filepreviews.io/"><img title="FilePreviews" src="https://www.attrs.org/en/24.3.0/_static/sponsors/FilePreviews.svg" width="190" /></a>
|
| 106 |
+
<a href="https://polar.sh/"><img title="Polar" src="https://www.attrs.org/en/24.3.0/_static/sponsors/Polar.svg" width="190" /></a>
|
| 107 |
+
<!-- [[[end]]] -->
|
| 108 |
+
|
| 109 |
+
</p>
|
| 110 |
+
|
| 111 |
+
<!-- sponsor-break-end -->
|
| 112 |
+
|
| 113 |
+
<p align="center">
|
| 114 |
+
<strong>Please consider <a href="https://github.com/sponsors/hynek">joining them</a> to help make <em>attrs</em>’s maintenance more sustainable!</strong>
|
| 115 |
+
</p>
|
| 116 |
+
|
| 117 |
+
<!-- teaser-end -->
|
| 118 |
+
|
| 119 |
+
## Example
|
| 120 |
+
|
| 121 |
+
*attrs* gives you a class decorator and a way to declaratively define the attributes on that class:
|
| 122 |
+
|
| 123 |
+
<!-- code-begin -->
|
| 124 |
+
|
| 125 |
+
```pycon
|
| 126 |
+
>>> from attrs import asdict, define, make_class, Factory
|
| 127 |
+
|
| 128 |
+
>>> @define
|
| 129 |
+
... class SomeClass:
|
| 130 |
+
... a_number: int = 42
|
| 131 |
+
... list_of_numbers: list[int] = Factory(list)
|
| 132 |
+
...
|
| 133 |
+
... def hard_math(self, another_number):
|
| 134 |
+
... return self.a_number + sum(self.list_of_numbers) * another_number
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
>>> sc = SomeClass(1, [1, 2, 3])
|
| 138 |
+
>>> sc
|
| 139 |
+
SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
|
| 140 |
+
|
| 141 |
+
>>> sc.hard_math(3)
|
| 142 |
+
19
|
| 143 |
+
>>> sc == SomeClass(1, [1, 2, 3])
|
| 144 |
+
True
|
| 145 |
+
>>> sc != SomeClass(2, [3, 2, 1])
|
| 146 |
+
True
|
| 147 |
+
|
| 148 |
+
>>> asdict(sc)
|
| 149 |
+
{'a_number': 1, 'list_of_numbers': [1, 2, 3]}
|
| 150 |
+
|
| 151 |
+
>>> SomeClass()
|
| 152 |
+
SomeClass(a_number=42, list_of_numbers=[])
|
| 153 |
+
|
| 154 |
+
>>> C = make_class("C", ["a", "b"])
|
| 155 |
+
>>> C("foo", "bar")
|
| 156 |
+
C(a='foo', b='bar')
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
After *declaring* your attributes, *attrs* gives you:
|
| 160 |
+
|
| 161 |
+
- a concise and explicit overview of the class's attributes,
|
| 162 |
+
- a nice human-readable `__repr__`,
|
| 163 |
+
- equality-checking methods,
|
| 164 |
+
- an initializer,
|
| 165 |
+
- and much more,
|
| 166 |
+
|
| 167 |
+
*without* writing dull boilerplate code again and again and *without* runtime performance penalties.
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
This example uses *attrs*'s modern APIs that have been introduced in version 20.1.0, and the *attrs* package import name that has been added in version 21.3.0.
|
| 172 |
+
The classic APIs (`@attr.s`, `attr.ib`, plus their serious-business aliases) and the `attr` package import name will remain **indefinitely**.
|
| 173 |
+
|
| 174 |
+
Check out [*On The Core API Names*](https://www.attrs.org/en/latest/names.html) for an in-depth explanation!
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
### Hate Type Annotations!?
|
| 178 |
+
|
| 179 |
+
No problem!
|
| 180 |
+
Types are entirely **optional** with *attrs*.
|
| 181 |
+
Simply assign `attrs.field()` to the attributes instead of annotating them with types:
|
| 182 |
+
|
| 183 |
+
```python
|
| 184 |
+
from attrs import define, field
|
| 185 |
+
|
| 186 |
+
@define
|
| 187 |
+
class SomeClass:
|
| 188 |
+
a_number = field(default=42)
|
| 189 |
+
list_of_numbers = field(factory=list)
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
## Data Classes
|
| 194 |
+
|
| 195 |
+
On the tin, *attrs* might remind you of `dataclasses` (and indeed, `dataclasses` [are a descendant](https://hynek.me/articles/import-attrs/) of *attrs*).
|
| 196 |
+
In practice it does a lot more and is more flexible.
|
| 197 |
+
For instance, it allows you to define [special handling of NumPy arrays for equality checks](https://www.attrs.org/en/stable/comparison.html#customization), allows more ways to [plug into the initialization process](https://www.attrs.org/en/stable/init.html#hooking-yourself-into-initialization), has a replacement for `__init_subclass__`, and allows for stepping through the generated methods using a debugger.
|
| 198 |
+
|
| 199 |
+
For more details, please refer to our [comparison page](https://www.attrs.org/en/stable/why.html#data-classes), but generally speaking, we are more likely to commit crimes against nature to make things work that one would expect to work, but that are quite complicated in practice.
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
## Project Information
|
| 203 |
+
|
| 204 |
+
- [**Changelog**](https://www.attrs.org/en/stable/changelog.html)
|
| 205 |
+
- [**Documentation**](https://www.attrs.org/)
|
| 206 |
+
- [**PyPI**](https://pypi.org/project/attrs/)
|
| 207 |
+
- [**Source Code**](https://github.com/python-attrs/attrs)
|
| 208 |
+
- [**Contributing**](https://github.com/python-attrs/attrs/blob/main/.github/CONTRIBUTING.md)
|
| 209 |
+
- [**Third-party Extensions**](https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs)
|
| 210 |
+
- **Get Help**: use the `python-attrs` tag on [Stack Overflow](https://stackoverflow.com/questions/tagged/python-attrs)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
### *attrs* for Enterprise
|
| 214 |
+
|
| 215 |
+
Available as part of the [Tidelift Subscription](https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek).
|
| 216 |
+
|
| 217 |
+
The maintainers of *attrs* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications.
|
| 218 |
+
Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use.
|
| 219 |
+
|
| 220 |
+
## Release Information
|
| 221 |
+
|
| 222 |
+
### Backwards-incompatible Changes
|
| 223 |
+
|
| 224 |
+
- Python 3.7 has been dropped.
|
| 225 |
+
[#1340](https://github.com/python-attrs/attrs/issues/1340)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
### Changes
|
| 229 |
+
|
| 230 |
+
- Introduce `attrs.NothingType`, for annotating types consistent with `attrs.NOTHING`.
|
| 231 |
+
[#1358](https://github.com/python-attrs/attrs/issues/1358)
|
| 232 |
+
- Allow mutating `__suppress_context__` and `__notes__` on frozen exceptions.
|
| 233 |
+
[#1365](https://github.com/python-attrs/attrs/issues/1365)
|
| 234 |
+
- `attrs.converters.optional()` works again when taking `attrs.converters.pipe()` or another Converter as its argument.
|
| 235 |
+
[#1372](https://github.com/python-attrs/attrs/issues/1372)
|
| 236 |
+
- *attrs* instances now support [`copy.replace()`](https://docs.python.org/3/library/copy.html#copy.replace).
|
| 237 |
+
[#1383](https://github.com/python-attrs/attrs/issues/1383)
|
| 238 |
+
- `attrs.validators.instance_of()`'s type hints now allow for union types.
|
| 239 |
+
For example: `instance_of(str | int)`
|
| 240 |
+
[#1385](https://github.com/python-attrs/attrs/issues/1385)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
---
|
| 245 |
+
|
| 246 |
+
[Full changelog →](https://www.attrs.org/en/stable/changelog.html)
|
wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
attr/__init__.py,sha256=fOYIvt1eGSqQre4uCS3sJWKZ0mwAuC8UD6qba5OS9_U,2057
|
| 2 |
+
attr/__init__.pyi,sha256=QIXnnHPoucmDWkbpNsWTP-cgJ1bn8le7DjyRa_wYdew,11281
|
| 3 |
+
attr/__pycache__/__init__.cpython-310.pyc,,
|
| 4 |
+
attr/__pycache__/_cmp.cpython-310.pyc,,
|
| 5 |
+
attr/__pycache__/_compat.cpython-310.pyc,,
|
| 6 |
+
attr/__pycache__/_config.cpython-310.pyc,,
|
| 7 |
+
attr/__pycache__/_funcs.cpython-310.pyc,,
|
| 8 |
+
attr/__pycache__/_make.cpython-310.pyc,,
|
| 9 |
+
attr/__pycache__/_next_gen.cpython-310.pyc,,
|
| 10 |
+
attr/__pycache__/_version_info.cpython-310.pyc,,
|
| 11 |
+
attr/__pycache__/converters.cpython-310.pyc,,
|
| 12 |
+
attr/__pycache__/exceptions.cpython-310.pyc,,
|
| 13 |
+
attr/__pycache__/filters.cpython-310.pyc,,
|
| 14 |
+
attr/__pycache__/setters.cpython-310.pyc,,
|
| 15 |
+
attr/__pycache__/validators.cpython-310.pyc,,
|
| 16 |
+
attr/_cmp.py,sha256=3umHiBtgsEYtvNP_8XrQwTCdFoZIX4DEur76N-2a3X8,4123
|
| 17 |
+
attr/_cmp.pyi,sha256=U-_RU_UZOyPUEQzXE6RMYQQcjkZRY25wTH99sN0s7MM,368
|
| 18 |
+
attr/_compat.py,sha256=4hlXbWhdDjQCDK6FKF1EgnZ3POiHgtpp54qE0nxaGHg,2704
|
| 19 |
+
attr/_config.py,sha256=dGq3xR6fgZEF6UBt_L0T-eUHIB4i43kRmH0P28sJVw8,843
|
| 20 |
+
attr/_funcs.py,sha256=5-tUKJtp3h5El55EcDl6GWXFp68fT8D8U7uCRN6497I,15854
|
| 21 |
+
attr/_make.py,sha256=orKSf6C-B1eZfpat4lbAtxvmSyE_yxlG8zY9115ufWk,94157
|
| 22 |
+
attr/_next_gen.py,sha256=7FRkbtl_N017SuBhf_Vw3mw2c2pGZhtCGOzadgz7tp4,24395
|
| 23 |
+
attr/_typing_compat.pyi,sha256=XDP54TUn-ZKhD62TOQebmzrwFyomhUCoGRpclb6alRA,469
|
| 24 |
+
attr/_version_info.py,sha256=exSqb3b5E-fMSsgZAlEw9XcLpEgobPORCZpcaEglAM4,2121
|
| 25 |
+
attr/_version_info.pyi,sha256=x_M3L3WuB7r_ULXAWjx959udKQ4HLB8l-hsc1FDGNvk,209
|
| 26 |
+
attr/converters.py,sha256=GlDeOzPeTFgeBBLbj9G57Ez5lAk68uhSALRYJ_exe84,3861
|
| 27 |
+
attr/converters.pyi,sha256=orU2bff-VjQa2kMDyvnMQV73oJT2WRyQuw4ZR1ym1bE,643
|
| 28 |
+
attr/exceptions.py,sha256=HRFq4iybmv7-DcZwyjl6M1euM2YeJVK_hFxuaBGAngI,1977
|
| 29 |
+
attr/exceptions.pyi,sha256=zZq8bCUnKAy9mDtBEw42ZhPhAUIHoTKedDQInJD883M,539
|
| 30 |
+
attr/filters.py,sha256=ZBiKWLp3R0LfCZsq7X11pn9WX8NslS2wXM4jsnLOGc8,1795
|
| 31 |
+
attr/filters.pyi,sha256=3J5BG-dTxltBk1_-RuNRUHrv2qu1v8v4aDNAQ7_mifA,208
|
| 32 |
+
attr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 33 |
+
attr/setters.py,sha256=5-dcT63GQK35ONEzSgfXCkbB7pPkaR-qv15mm4PVSzQ,1617
|
| 34 |
+
attr/setters.pyi,sha256=NnVkaFU1BB4JB8E4JuXyrzTUgvtMpj8p3wBdJY7uix4,584
|
| 35 |
+
attr/validators.py,sha256=WaB1HLAHHqRHWsrv_K9H-sJ7ESil3H3Cmv2d8TtVZx4,20046
|
| 36 |
+
attr/validators.pyi,sha256=s2WhKPqskxbsckJfKk8zOuuB088GfgpyxcCYSNFLqNU,2603
|
| 37 |
+
attrs-24.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 38 |
+
attrs-24.3.0.dist-info/METADATA,sha256=f9hhECeAUyS7iewHPRuMLDy1tpJ6vyy8R_TKUnCmiA8,11654
|
| 39 |
+
attrs-24.3.0.dist-info/RECORD,,
|
| 40 |
+
attrs-24.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 41 |
+
attrs-24.3.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
| 42 |
+
attrs-24.3.0.dist-info/licenses/LICENSE,sha256=iCEVyV38KvHutnFPjsbVy8q_Znyv-HKfQkINpj9xTp8,1109
|
| 43 |
+
attrs/__init__.py,sha256=qeQJZ4O08yczSn840v9bYOaZyRE81WsVi-QCrY3krCU,1107
|
| 44 |
+
attrs/__init__.pyi,sha256=nZmInocjM7tHV4AQw0vxO_fo6oJjL_PonlV9zKKW8DY,7931
|
| 45 |
+
attrs/__pycache__/__init__.cpython-310.pyc,,
|
| 46 |
+
attrs/__pycache__/converters.cpython-310.pyc,,
|
| 47 |
+
attrs/__pycache__/exceptions.cpython-310.pyc,,
|
| 48 |
+
attrs/__pycache__/filters.cpython-310.pyc,,
|
| 49 |
+
attrs/__pycache__/setters.cpython-310.pyc,,
|
| 50 |
+
attrs/__pycache__/validators.cpython-310.pyc,,
|
| 51 |
+
attrs/converters.py,sha256=8kQljrVwfSTRu8INwEk8SI0eGrzmWftsT7rM0EqyohM,76
|
| 52 |
+
attrs/exceptions.py,sha256=ACCCmg19-vDFaDPY9vFl199SPXCQMN_bENs4DALjzms,76
|
| 53 |
+
attrs/filters.py,sha256=VOUMZug9uEU6dUuA0dF1jInUK0PL3fLgP0VBS5d-CDE,73
|
| 54 |
+
attrs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 55 |
+
attrs/setters.py,sha256=eL1YidYQV3T2h9_SYIZSZR1FAcHGb1TuCTy0E0Lv2SU,73
|
| 56 |
+
attrs/validators.py,sha256=xcy6wD5TtTkdCG1f4XWbocPSO0faBjk5IfVJfP6SUj0,76
|
wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/REQUESTED
ADDED
|
File without changes
|
wemm/lib/python3.10/site-packages/attrs-24.3.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.27.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
wemm/lib/python3.10/site-packages/botocore/data/amplifybackend/2020-08-11/endpoint-rule-set-1.json.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04e4c036ecdc99a04e567759ee2285cf996031c056457964a93e9ffd7a587ec4
|
| 3 |
+
size 1127
|
wemm/lib/python3.10/site-packages/botocore/data/location/2020-11-19/endpoint-rule-set-1.json.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:18f9e9138b3b2af3d284231b1664bf9d8a7f3a40a34760ce3e7ca9354197aca0
|
| 3 |
+
size 1287
|
wemm/lib/python3.10/site-packages/tokenizers/__init__.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
from typing import List, Tuple, Union
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
Offsets = Tuple[int, int]
|
| 6 |
+
|
| 7 |
+
TextInputSequence = str
|
| 8 |
+
"""A :obj:`str` that represents an input sequence """
|
| 9 |
+
|
| 10 |
+
PreTokenizedInputSequence = Union[List[str], Tuple[str]]
|
| 11 |
+
"""A pre-tokenized input sequence. Can be one of:
|
| 12 |
+
|
| 13 |
+
- A :obj:`List` of :obj:`str`
|
| 14 |
+
- A :obj:`Tuple` of :obj:`str`
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
TextEncodeInput = Union[
|
| 18 |
+
TextInputSequence,
|
| 19 |
+
Tuple[TextInputSequence, TextInputSequence],
|
| 20 |
+
List[TextInputSequence],
|
| 21 |
+
]
|
| 22 |
+
"""Represents a textual input for encoding. Can be either:
|
| 23 |
+
|
| 24 |
+
- A single sequence: :data:`~tokenizers.TextInputSequence`
|
| 25 |
+
- A pair of sequences:
|
| 26 |
+
|
| 27 |
+
- A :obj:`Tuple` of :data:`~tokenizers.TextInputSequence`
|
| 28 |
+
- Or a :obj:`List` of :data:`~tokenizers.TextInputSequence` of size 2
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
PreTokenizedEncodeInput = Union[
|
| 32 |
+
PreTokenizedInputSequence,
|
| 33 |
+
Tuple[PreTokenizedInputSequence, PreTokenizedInputSequence],
|
| 34 |
+
List[PreTokenizedInputSequence],
|
| 35 |
+
]
|
| 36 |
+
"""Represents a pre-tokenized input for encoding. Can be either:
|
| 37 |
+
|
| 38 |
+
- A single sequence: :data:`~tokenizers.PreTokenizedInputSequence`
|
| 39 |
+
- A pair of sequences:
|
| 40 |
+
|
| 41 |
+
- A :obj:`Tuple` of :data:`~tokenizers.PreTokenizedInputSequence`
|
| 42 |
+
- Or a :obj:`List` of :data:`~tokenizers.PreTokenizedInputSequence` of size 2
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
InputSequence = Union[TextInputSequence, PreTokenizedInputSequence]
|
| 46 |
+
"""Represents all the possible types of input sequences for encoding. Can be:
|
| 47 |
+
|
| 48 |
+
- When ``is_pretokenized=False``: :data:`~TextInputSequence`
|
| 49 |
+
- When ``is_pretokenized=True``: :data:`~PreTokenizedInputSequence`
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
EncodeInput = Union[TextEncodeInput, PreTokenizedEncodeInput]
|
| 53 |
+
"""Represents all the possible types of input for encoding. Can be:
|
| 54 |
+
|
| 55 |
+
- When ``is_pretokenized=False``: :data:`~TextEncodeInput`
|
| 56 |
+
- When ``is_pretokenized=True``: :data:`~PreTokenizedEncodeInput`
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class OffsetReferential(Enum):
|
| 61 |
+
ORIGINAL = "original"
|
| 62 |
+
NORMALIZED = "normalized"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class OffsetType(Enum):
|
| 66 |
+
BYTE = "byte"
|
| 67 |
+
CHAR = "char"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class SplitDelimiterBehavior(Enum):
|
| 71 |
+
REMOVED = "removed"
|
| 72 |
+
ISOLATED = "isolated"
|
| 73 |
+
MERGED_WITH_PREVIOUS = "merged_with_previous"
|
| 74 |
+
MERGED_WITH_NEXT = "merged_with_next"
|
| 75 |
+
CONTIGUOUS = "contiguous"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
from .tokenizers import (
|
| 79 |
+
AddedToken,
|
| 80 |
+
Encoding,
|
| 81 |
+
NormalizedString,
|
| 82 |
+
PreTokenizedString,
|
| 83 |
+
Regex,
|
| 84 |
+
Token,
|
| 85 |
+
Tokenizer,
|
| 86 |
+
decoders,
|
| 87 |
+
models,
|
| 88 |
+
normalizers,
|
| 89 |
+
pre_tokenizers,
|
| 90 |
+
processors,
|
| 91 |
+
trainers,
|
| 92 |
+
__version__,
|
| 93 |
+
)
|
| 94 |
+
from .implementations import (
|
| 95 |
+
BertWordPieceTokenizer,
|
| 96 |
+
ByteLevelBPETokenizer,
|
| 97 |
+
CharBPETokenizer,
|
| 98 |
+
SentencePieceBPETokenizer,
|
| 99 |
+
SentencePieceUnigramTokenizer,
|
| 100 |
+
)
|
wemm/lib/python3.10/site-packages/tokenizers/decoders/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .. import decoders
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
Decoder = decoders.Decoder
|
| 5 |
+
ByteLevel = decoders.ByteLevel
|
| 6 |
+
Replace = decoders.Replace
|
| 7 |
+
WordPiece = decoders.WordPiece
|
| 8 |
+
ByteFallback = decoders.ByteFallback
|
| 9 |
+
Fuse = decoders.Fuse
|
| 10 |
+
Strip = decoders.Strip
|
| 11 |
+
Metaspace = decoders.Metaspace
|
| 12 |
+
BPEDecoder = decoders.BPEDecoder
|
| 13 |
+
CTC = decoders.CTC
|
| 14 |
+
Sequence = decoders.Sequence
|
wemm/lib/python3.10/site-packages/tokenizers/implementations/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base_tokenizer import BaseTokenizer
|
| 2 |
+
from .bert_wordpiece import BertWordPieceTokenizer
|
| 3 |
+
from .byte_level_bpe import ByteLevelBPETokenizer
|
| 4 |
+
from .char_level_bpe import CharBPETokenizer
|
| 5 |
+
from .sentencepiece_bpe import SentencePieceBPETokenizer
|
| 6 |
+
from .sentencepiece_unigram import SentencePieceUnigramTokenizer
|
wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (546 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/bert_wordpiece.cpython-310.pyc
ADDED
|
Binary file (3.85 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/sentencepiece_bpe.cpython-310.pyc
ADDED
|
Binary file (3.25 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/tokenizers/implementations/__pycache__/sentencepiece_unigram.cpython-310.pyc
ADDED
|
Binary file (6.47 kB). View file
|
|
|