Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- minigpt2/lib/python3.10/site-packages/Crypto/IO/PEM.py +189 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/PEM.pyi +10 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/PKCS8.py +226 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/PKCS8.pyi +17 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/_PBES.py +546 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/_PBES.pyi +26 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/__init__.py +31 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/PEM.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/PKCS8.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/_PBES.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/DH.py +192 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/KDF.py +639 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/KDF.pyi +42 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/SecretSharing.py +278 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__init__.py +31 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__init__.pyi +1 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/DH.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/KDF.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/SecretSharing.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Protocol/_scrypt.abi3.so +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Random/__init__.py +57 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Random/__init__.pyi +19 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Random/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Random/__pycache__/random.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Random/random.py +138 -0
- minigpt2/lib/python3.10/site-packages/Crypto/Random/random.pyi +22 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/IO/__init__.py +47 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/IO/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/IO/__pycache__/test_PKCS8.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__init__.py +51 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_Numbers.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_Primality.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_modexp.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_modmult.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_Numbers.py +838 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_Primality.py +118 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_modexp.py +201 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_modmult.py +120 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__init__.py +45 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/__init__.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_KDF.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_SecretSharing.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_ecdh.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_rfc1751.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/test_KDF.py +809 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/test_SecretSharing.py +267 -0
- minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/test_ecdh.py +619 -0
minigpt2/lib/python3.10/site-packages/Crypto/IO/PEM.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Util/PEM.py : Privacy Enhanced Mail utilities
|
| 3 |
+
#
|
| 4 |
+
# ===================================================================
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
|
| 7 |
+
# All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Redistribution and use in source and binary forms, with or without
|
| 10 |
+
# modification, are permitted provided that the following conditions
|
| 11 |
+
# are met:
|
| 12 |
+
#
|
| 13 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 14 |
+
# notice, this list of conditions and the following disclaimer.
|
| 15 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 16 |
+
# notice, this list of conditions and the following disclaimer in
|
| 17 |
+
# the documentation and/or other materials provided with the
|
| 18 |
+
# distribution.
|
| 19 |
+
#
|
| 20 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 21 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 22 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
|
| 23 |
+
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
|
| 24 |
+
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 25 |
+
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
| 26 |
+
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 27 |
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 28 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 29 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
| 30 |
+
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 31 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
| 32 |
+
# ===================================================================
|
| 33 |
+
|
| 34 |
+
__all__ = ['encode', 'decode']
|
| 35 |
+
|
| 36 |
+
import re
|
| 37 |
+
from binascii import a2b_base64, b2a_base64, hexlify, unhexlify
|
| 38 |
+
|
| 39 |
+
from Crypto.Hash import MD5
|
| 40 |
+
from Crypto.Util.Padding import pad, unpad
|
| 41 |
+
from Crypto.Cipher import DES, DES3, AES
|
| 42 |
+
from Crypto.Protocol.KDF import PBKDF1
|
| 43 |
+
from Crypto.Random import get_random_bytes
|
| 44 |
+
from Crypto.Util.py3compat import tobytes, tostr
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def encode(data, marker, passphrase=None, randfunc=None):
|
| 48 |
+
"""Encode a piece of binary data into PEM format.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
data (byte string):
|
| 52 |
+
The piece of binary data to encode.
|
| 53 |
+
marker (string):
|
| 54 |
+
The marker for the PEM block (e.g. "PUBLIC KEY").
|
| 55 |
+
Note that there is no official master list for all allowed markers.
|
| 56 |
+
Still, you can refer to the OpenSSL_ source code.
|
| 57 |
+
passphrase (byte string):
|
| 58 |
+
If given, the PEM block will be encrypted. The key is derived from
|
| 59 |
+
the passphrase.
|
| 60 |
+
randfunc (callable):
|
| 61 |
+
Random number generation function; it accepts an integer N and returns
|
| 62 |
+
a byte string of random data, N bytes long. If not given, a new one is
|
| 63 |
+
instantiated.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
The PEM block, as a string.
|
| 67 |
+
|
| 68 |
+
.. _OpenSSL: https://github.com/openssl/openssl/blob/master/include/openssl/pem.h
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
if randfunc is None:
|
| 72 |
+
randfunc = get_random_bytes
|
| 73 |
+
|
| 74 |
+
out = "-----BEGIN %s-----\n" % marker
|
| 75 |
+
if passphrase:
|
| 76 |
+
# We only support 3DES for encryption
|
| 77 |
+
salt = randfunc(8)
|
| 78 |
+
key = PBKDF1(passphrase, salt, 16, 1, MD5)
|
| 79 |
+
key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
|
| 80 |
+
objenc = DES3.new(key, DES3.MODE_CBC, salt)
|
| 81 |
+
out += "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,%s\n\n" %\
|
| 82 |
+
tostr(hexlify(salt).upper())
|
| 83 |
+
# Encrypt with PKCS#7 padding
|
| 84 |
+
data = objenc.encrypt(pad(data, objenc.block_size))
|
| 85 |
+
elif passphrase is not None:
|
| 86 |
+
raise ValueError("Empty password")
|
| 87 |
+
|
| 88 |
+
# Each BASE64 line can take up to 64 characters (=48 bytes of data)
|
| 89 |
+
# b2a_base64 adds a new line character!
|
| 90 |
+
chunks = [tostr(b2a_base64(data[i:i + 48]))
|
| 91 |
+
for i in range(0, len(data), 48)]
|
| 92 |
+
out += "".join(chunks)
|
| 93 |
+
out += "-----END %s-----" % marker
|
| 94 |
+
return out
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _EVP_BytesToKey(data, salt, key_len):
|
| 98 |
+
d = [ b'' ]
|
| 99 |
+
m = (key_len + 15 ) // 16
|
| 100 |
+
for _ in range(m):
|
| 101 |
+
nd = MD5.new(d[-1] + data + salt).digest()
|
| 102 |
+
d.append(nd)
|
| 103 |
+
return b"".join(d)[:key_len]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def decode(pem_data, passphrase=None):
|
| 107 |
+
"""Decode a PEM block into binary.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
pem_data (string):
|
| 111 |
+
The PEM block.
|
| 112 |
+
passphrase (byte string):
|
| 113 |
+
If given and the PEM block is encrypted,
|
| 114 |
+
the key will be derived from the passphrase.
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
A tuple with the binary data, the marker string, and a boolean to
|
| 118 |
+
indicate if decryption was performed.
|
| 119 |
+
|
| 120 |
+
Raises:
|
| 121 |
+
ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has
|
| 122 |
+
been provided or if the passphrase is incorrect.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
# Verify Pre-Encapsulation Boundary
|
| 126 |
+
r = re.compile(r"\s*-----BEGIN (.*)-----\s+")
|
| 127 |
+
m = r.match(pem_data)
|
| 128 |
+
if not m:
|
| 129 |
+
raise ValueError("Not a valid PEM pre boundary")
|
| 130 |
+
marker = m.group(1)
|
| 131 |
+
|
| 132 |
+
# Verify Post-Encapsulation Boundary
|
| 133 |
+
r = re.compile(r"-----END (.*)-----\s*$")
|
| 134 |
+
m = r.search(pem_data)
|
| 135 |
+
if not m or m.group(1) != marker:
|
| 136 |
+
raise ValueError("Not a valid PEM post boundary")
|
| 137 |
+
|
| 138 |
+
# Removes spaces and slit on lines
|
| 139 |
+
lines = pem_data.replace(" ", '').split()
|
| 140 |
+
|
| 141 |
+
# Decrypts, if necessary
|
| 142 |
+
if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
|
| 143 |
+
if not passphrase:
|
| 144 |
+
raise ValueError("PEM is encrypted, but no passphrase available")
|
| 145 |
+
DEK = lines[2].split(':')
|
| 146 |
+
if len(DEK) != 2 or DEK[0] != 'DEK-Info':
|
| 147 |
+
raise ValueError("PEM encryption format not supported.")
|
| 148 |
+
algo, salt = DEK[1].split(',')
|
| 149 |
+
salt = unhexlify(tobytes(salt))
|
| 150 |
+
|
| 151 |
+
padding = True
|
| 152 |
+
|
| 153 |
+
if algo == "DES-CBC":
|
| 154 |
+
key = _EVP_BytesToKey(passphrase, salt, 8)
|
| 155 |
+
objdec = DES.new(key, DES.MODE_CBC, salt)
|
| 156 |
+
elif algo == "DES-EDE3-CBC":
|
| 157 |
+
key = _EVP_BytesToKey(passphrase, salt, 24)
|
| 158 |
+
objdec = DES3.new(key, DES3.MODE_CBC, salt)
|
| 159 |
+
elif algo == "AES-128-CBC":
|
| 160 |
+
key = _EVP_BytesToKey(passphrase, salt[:8], 16)
|
| 161 |
+
objdec = AES.new(key, AES.MODE_CBC, salt)
|
| 162 |
+
elif algo == "AES-192-CBC":
|
| 163 |
+
key = _EVP_BytesToKey(passphrase, salt[:8], 24)
|
| 164 |
+
objdec = AES.new(key, AES.MODE_CBC, salt)
|
| 165 |
+
elif algo == "AES-256-CBC":
|
| 166 |
+
key = _EVP_BytesToKey(passphrase, salt[:8], 32)
|
| 167 |
+
objdec = AES.new(key, AES.MODE_CBC, salt)
|
| 168 |
+
elif algo.lower() == "id-aes256-gcm":
|
| 169 |
+
key = _EVP_BytesToKey(passphrase, salt[:8], 32)
|
| 170 |
+
objdec = AES.new(key, AES.MODE_GCM, nonce=salt)
|
| 171 |
+
padding = False
|
| 172 |
+
else:
|
| 173 |
+
raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo)
|
| 174 |
+
lines = lines[2:]
|
| 175 |
+
else:
|
| 176 |
+
objdec = None
|
| 177 |
+
|
| 178 |
+
# Decode body
|
| 179 |
+
data = a2b_base64(''.join(lines[1:-1]))
|
| 180 |
+
enc_flag = False
|
| 181 |
+
if objdec:
|
| 182 |
+
if padding:
|
| 183 |
+
data = unpad(objdec.decrypt(data), objdec.block_size)
|
| 184 |
+
else:
|
| 185 |
+
# There is no tag, so we don't use decrypt_and_verify
|
| 186 |
+
data = objdec.decrypt(data)
|
| 187 |
+
enc_flag = True
|
| 188 |
+
|
| 189 |
+
return (data, marker, enc_flag)
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/PEM.pyi
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple, Optional, Callable
|
| 2 |
+
|
| 3 |
+
def encode(data: bytes,
|
| 4 |
+
marke: str,
|
| 5 |
+
passphrase: Optional[bytes] = ...,
|
| 6 |
+
randfunc: Optional[Callable[[int],bytes]] = ...) -> str: ...
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def decode(pem_data: str,
|
| 10 |
+
passphrase: Optional[bytes] = ...) -> Tuple[bytes, str, bool]: ...
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/PKCS8.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/PKCS8.pyi
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple, Optional, Union, Callable
|
| 2 |
+
from typing_extensions import NotRequired
|
| 3 |
+
|
| 4 |
+
from Crypto.Util.asn1 import DerObject
|
| 5 |
+
from Crypto.IO._PBES import ProtParams
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def wrap(private_key: bytes,
|
| 9 |
+
key_oid: str,
|
| 10 |
+
passphrase: Union[bytes, str] = ...,
|
| 11 |
+
protection: str = ...,
|
| 12 |
+
prot_params: Optional[ProtParams] = ...,
|
| 13 |
+
key_params: Optional[DerObject] = ...,
|
| 14 |
+
randfunc: Optional[Callable[[int], str]] = ...) -> bytes: ...
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def unwrap(p8_private_key: bytes, passphrase: Optional[Union[bytes, str]] = ...) -> Tuple[str, bytes, Optional[bytes]]: ...
|
minigpt2/l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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# PublicKey/_PBES.py : Password-Based Encryption 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 |
+
import re
|
| 35 |
+
|
| 36 |
+
from Crypto import Hash
|
| 37 |
+
from Crypto import Random
|
| 38 |
+
from Crypto.Util.asn1 import (
|
| 39 |
+
DerSequence, DerOctetString,
|
| 40 |
+
DerObjectId, DerInteger,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
from Crypto.Cipher import AES
|
| 44 |
+
from Crypto.Util.Padding import pad, unpad
|
| 45 |
+
from Crypto.Protocol.KDF import PBKDF1, PBKDF2, scrypt
|
| 46 |
+
|
| 47 |
+
_OID_PBE_WITH_MD5_AND_DES_CBC = "1.2.840.113549.1.5.3"
|
| 48 |
+
_OID_PBE_WITH_MD5_AND_RC2_CBC = "1.2.840.113549.1.5.6"
|
| 49 |
+
_OID_PBE_WITH_SHA1_AND_DES_CBC = "1.2.840.113549.1.5.10"
|
| 50 |
+
_OID_PBE_WITH_SHA1_AND_RC2_CBC = "1.2.840.113549.1.5.11"
|
| 51 |
+
|
| 52 |
+
_OID_PBES2 = "1.2.840.113549.1.5.13"
|
| 53 |
+
|
| 54 |
+
_OID_PBKDF2 = "1.2.840.113549.1.5.12"
|
| 55 |
+
_OID_SCRYPT = "1.3.6.1.4.1.11591.4.11"
|
| 56 |
+
|
| 57 |
+
_OID_HMAC_SHA1 = "1.2.840.113549.2.7"
|
| 58 |
+
|
| 59 |
+
_OID_DES_EDE3_CBC = "1.2.840.113549.3.7"
|
| 60 |
+
_OID_AES128_CBC = "2.16.840.1.101.3.4.1.2"
|
| 61 |
+
_OID_AES192_CBC = "2.16.840.1.101.3.4.1.22"
|
| 62 |
+
_OID_AES256_CBC = "2.16.840.1.101.3.4.1.42"
|
| 63 |
+
_OID_AES128_GCM = "2.16.840.1.101.3.4.1.6"
|
| 64 |
+
_OID_AES192_GCM = "2.16.840.1.101.3.4.1.26"
|
| 65 |
+
_OID_AES256_GCM = "2.16.840.1.101.3.4.1.46"
|
| 66 |
+
|
| 67 |
+
class PbesError(ValueError):
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
# These are the ASN.1 definitions used by the PBES1/2 logic:
|
| 71 |
+
#
|
| 72 |
+
# EncryptedPrivateKeyInfo ::= SEQUENCE {
|
| 73 |
+
# encryptionAlgorithm EncryptionAlgorithmIdentifier,
|
| 74 |
+
# encryptedData EncryptedData
|
| 75 |
+
# }
|
| 76 |
+
#
|
| 77 |
+
# EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
|
| 78 |
+
#
|
| 79 |
+
# EncryptedData ::= OCTET STRING
|
| 80 |
+
#
|
| 81 |
+
# AlgorithmIdentifier ::= SEQUENCE {
|
| 82 |
+
# algorithm OBJECT IDENTIFIER,
|
| 83 |
+
# parameters ANY DEFINED BY algorithm OPTIONAL
|
| 84 |
+
# }
|
| 85 |
+
#
|
| 86 |
+
# PBEParameter ::= SEQUENCE {
|
| 87 |
+
# salt OCTET STRING (SIZE(8)),
|
| 88 |
+
# iterationCount INTEGER
|
| 89 |
+
# }
|
| 90 |
+
#
|
| 91 |
+
# PBES2-params ::= SEQUENCE {
|
| 92 |
+
# keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
|
| 93 |
+
# encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
|
| 94 |
+
# }
|
| 95 |
+
#
|
| 96 |
+
# PBKDF2-params ::= SEQUENCE {
|
| 97 |
+
# salt CHOICE {
|
| 98 |
+
# specified OCTET STRING,
|
| 99 |
+
# otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
|
| 100 |
+
# },
|
| 101 |
+
# iterationCount INTEGER (1..MAX),
|
| 102 |
+
# keyLength INTEGER (1..MAX) OPTIONAL,
|
| 103 |
+
# prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
|
| 104 |
+
# }
|
| 105 |
+
#
|
| 106 |
+
# PBKDF2-PRFs ALGORITHM-IDENTIFIER ::= {
|
| 107 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA1},
|
| 108 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA224},
|
| 109 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA256},
|
| 110 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA384},
|
| 111 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA512},
|
| 112 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA512-224},
|
| 113 |
+
# {NULL IDENTIFIED BY id-hmacWithSHA512-256},
|
| 114 |
+
# ...
|
| 115 |
+
# }
|
| 116 |
+
# scrypt-params ::= SEQUENCE {
|
| 117 |
+
# salt OCTET STRING,
|
| 118 |
+
# costParameter INTEGER (1..MAX),
|
| 119 |
+
# blockSize INTEGER (1..MAX),
|
| 120 |
+
# parallelizationParameter INTEGER (1..MAX),
|
| 121 |
+
# keyLength INTEGER (1..MAX) OPTIONAL
|
| 122 |
+
# }
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class PBES1(object):
|
| 126 |
+
"""Deprecated encryption scheme with password-based key derivation
|
| 127 |
+
(originally defined in PKCS#5 v1.5, but still present in `v2.0`__).
|
| 128 |
+
|
| 129 |
+
.. __: http://www.ietf.org/rfc/rfc2898.txt
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
@staticmethod
|
| 133 |
+
def decrypt(data, passphrase):
|
| 134 |
+
"""Decrypt a piece of data using a passphrase and *PBES1*.
|
| 135 |
+
|
| 136 |
+
The algorithm to use is automatically detected.
|
| 137 |
+
|
| 138 |
+
:Parameters:
|
| 139 |
+
data : byte string
|
| 140 |
+
The piece of data to decrypt.
|
| 141 |
+
passphrase : byte string
|
| 142 |
+
The passphrase to use for decrypting the data.
|
| 143 |
+
:Returns:
|
| 144 |
+
The decrypted data, as a binary string.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
enc_private_key_info = DerSequence().decode(data)
|
| 148 |
+
encrypted_algorithm = DerSequence().decode(enc_private_key_info[0])
|
| 149 |
+
encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload
|
| 150 |
+
|
| 151 |
+
pbe_oid = DerObjectId().decode(encrypted_algorithm[0]).value
|
| 152 |
+
cipher_params = {}
|
| 153 |
+
if pbe_oid == _OID_PBE_WITH_MD5_AND_DES_CBC:
|
| 154 |
+
# PBE_MD5_DES_CBC
|
| 155 |
+
from Crypto.Hash import MD5
|
| 156 |
+
from Crypto.Cipher import DES
|
| 157 |
+
hashmod = MD5
|
| 158 |
+
module = DES
|
| 159 |
+
elif pbe_oid == _OID_PBE_WITH_MD5_AND_RC2_CBC:
|
| 160 |
+
# PBE_MD5_RC2_CBC
|
| 161 |
+
from Crypto.Hash import MD5
|
| 162 |
+
from Crypto.Cipher import ARC2
|
| 163 |
+
hashmod = MD5
|
| 164 |
+
module = ARC2
|
| 165 |
+
cipher_params['effective_keylen'] = 64
|
| 166 |
+
elif pbe_oid == _OID_PBE_WITH_SHA1_AND_DES_CBC:
|
| 167 |
+
# PBE_SHA1_DES_CBC
|
| 168 |
+
from Crypto.Hash import SHA1
|
| 169 |
+
from Crypto.Cipher import DES
|
| 170 |
+
hashmod = SHA1
|
| 171 |
+
module = DES
|
| 172 |
+
elif pbe_oid == _OID_PBE_WITH_SHA1_AND_RC2_CBC:
|
| 173 |
+
# PBE_SHA1_RC2_CBC
|
| 174 |
+
from Crypto.Hash import SHA1
|
| 175 |
+
from Crypto.Cipher import ARC2
|
| 176 |
+
hashmod = SHA1
|
| 177 |
+
module = ARC2
|
| 178 |
+
cipher_params['effective_keylen'] = 64
|
| 179 |
+
else:
|
| 180 |
+
raise PbesError("Unknown OID for PBES1")
|
| 181 |
+
|
| 182 |
+
pbe_params = DerSequence().decode(encrypted_algorithm[1], nr_elements=2)
|
| 183 |
+
salt = DerOctetString().decode(pbe_params[0]).payload
|
| 184 |
+
iterations = pbe_params[1]
|
| 185 |
+
|
| 186 |
+
key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod)
|
| 187 |
+
key, iv = key_iv[:8], key_iv[8:]
|
| 188 |
+
|
| 189 |
+
cipher = module.new(key, module.MODE_CBC, iv, **cipher_params)
|
| 190 |
+
pt = cipher.decrypt(encrypted_data)
|
| 191 |
+
return unpad(pt, cipher.block_size)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class PBES2(object):
|
| 195 |
+
"""Encryption scheme with password-based key derivation
|
| 196 |
+
(defined in `PKCS#5 v2.0`__).
|
| 197 |
+
|
| 198 |
+
.. __: http://www.ietf.org/rfc/rfc2898.txt."""
|
| 199 |
+
|
| 200 |
+
@staticmethod
|
| 201 |
+
def encrypt(data, passphrase, protection, prot_params=None, randfunc=None):
|
| 202 |
+
"""Encrypt a piece of data using a passphrase and *PBES2*.
|
| 203 |
+
|
| 204 |
+
:Parameters:
|
| 205 |
+
data : byte string
|
| 206 |
+
The piece of data to encrypt.
|
| 207 |
+
passphrase : byte string
|
| 208 |
+
The passphrase to use for encrypting the data.
|
| 209 |
+
protection : string
|
| 210 |
+
The identifier of the encryption algorithm to use.
|
| 211 |
+
The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
|
| 212 |
+
prot_params : dictionary
|
| 213 |
+
Parameters of the protection algorithm.
|
| 214 |
+
|
| 215 |
+
+------------------+-----------------------------------------------+
|
| 216 |
+
| Key | Description |
|
| 217 |
+
+==================+===============================================+
|
| 218 |
+
| iteration_count | The KDF algorithm is repeated several times to|
|
| 219 |
+
| | slow down brute force attacks on passwords |
|
| 220 |
+
| | (called *N* or CPU/memory cost in scrypt). |
|
| 221 |
+
| | |
|
| 222 |
+
| | The default value for PBKDF2 is 1 000. |
|
| 223 |
+
| | The default value for scrypt is 16 384. |
|
| 224 |
+
+------------------+-----------------------------------------------+
|
| 225 |
+
| salt_size | Salt is used to thwart dictionary and rainbow |
|
| 226 |
+
| | attacks on passwords. The default value is 8 |
|
| 227 |
+
| | bytes. |
|
| 228 |
+
+------------------+-----------------------------------------------+
|
| 229 |
+
| block_size | *(scrypt only)* Memory-cost (r). The default |
|
| 230 |
+
| | value is 8. |
|
| 231 |
+
+------------------+-----------------------------------------------+
|
| 232 |
+
| parallelization | *(scrypt only)* CPU-cost (p). The default |
|
| 233 |
+
| | value is 1. |
|
| 234 |
+
+------------------+-----------------------------------------------+
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
randfunc : callable
|
| 238 |
+
Random number generation function; it should accept
|
| 239 |
+
a single integer N and return a string of random data,
|
| 240 |
+
N bytes long. If not specified, a new RNG will be
|
| 241 |
+
instantiated from ``Crypto.Random``.
|
| 242 |
+
|
| 243 |
+
:Returns:
|
| 244 |
+
The encrypted data, as a binary string.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
if prot_params is None:
|
| 248 |
+
prot_params = {}
|
| 249 |
+
|
| 250 |
+
if randfunc is None:
|
| 251 |
+
randfunc = Random.new().read
|
| 252 |
+
|
| 253 |
+
pattern = re.compile(r'^(PBKDF2WithHMAC-([0-9A-Z-]+)|scrypt)And([0-9A-Z-]+)$')
|
| 254 |
+
res = pattern.match(protection)
|
| 255 |
+
if res is None:
|
| 256 |
+
raise ValueError("Unknown protection %s" % protection)
|
| 257 |
+
|
| 258 |
+
if protection.startswith("PBKDF"):
|
| 259 |
+
pbkdf = "pbkdf2"
|
| 260 |
+
pbkdf2_hmac_algo = res.group(2)
|
| 261 |
+
enc_algo = res.group(3)
|
| 262 |
+
else:
|
| 263 |
+
pbkdf = "scrypt"
|
| 264 |
+
enc_algo = res.group(3)
|
| 265 |
+
|
| 266 |
+
aead = False
|
| 267 |
+
if enc_algo == 'DES-EDE3-CBC':
|
| 268 |
+
from Crypto.Cipher import DES3
|
| 269 |
+
key_size = 24
|
| 270 |
+
module = DES3
|
| 271 |
+
cipher_mode = DES3.MODE_CBC
|
| 272 |
+
enc_oid = _OID_DES_EDE3_CBC
|
| 273 |
+
enc_param = {'iv': randfunc(8)}
|
| 274 |
+
elif enc_algo == 'AES128-CBC':
|
| 275 |
+
key_size = 16
|
| 276 |
+
module = AES
|
| 277 |
+
cipher_mode = AES.MODE_CBC
|
| 278 |
+
enc_oid = _OID_AES128_CBC
|
| 279 |
+
enc_param = {'iv': randfunc(16)}
|
| 280 |
+
elif enc_algo == 'AES192-CBC':
|
| 281 |
+
key_size = 24
|
| 282 |
+
module = AES
|
| 283 |
+
cipher_mode = AES.MODE_CBC
|
| 284 |
+
enc_oid = _OID_AES192_CBC
|
| 285 |
+
enc_param = {'iv': randfunc(16)}
|
| 286 |
+
elif enc_algo == 'AES256-CBC':
|
| 287 |
+
key_size = 32
|
| 288 |
+
module = AES
|
| 289 |
+
cipher_mode = AES.MODE_CBC
|
| 290 |
+
enc_oid = _OID_AES256_CBC
|
| 291 |
+
enc_param = {'iv': randfunc(16)}
|
| 292 |
+
elif enc_algo == 'AES128-GCM':
|
| 293 |
+
key_size = 16
|
| 294 |
+
module = AES
|
| 295 |
+
cipher_mode = AES.MODE_GCM
|
| 296 |
+
enc_oid = _OID_AES128_GCM
|
| 297 |
+
enc_param = {'nonce': randfunc(12)}
|
| 298 |
+
aead = True
|
| 299 |
+
elif enc_algo == 'AES192-GCM':
|
| 300 |
+
key_size = 24
|
| 301 |
+
module = AES
|
| 302 |
+
cipher_mode = AES.MODE_GCM
|
| 303 |
+
enc_oid = _OID_AES192_GCM
|
| 304 |
+
enc_param = {'nonce': randfunc(12)}
|
| 305 |
+
aead = True
|
| 306 |
+
elif enc_algo == 'AES256-GCM':
|
| 307 |
+
key_size = 32
|
| 308 |
+
module = AES
|
| 309 |
+
cipher_mode = AES.MODE_GCM
|
| 310 |
+
enc_oid = _OID_AES256_GCM
|
| 311 |
+
enc_param = {'nonce': randfunc(12)}
|
| 312 |
+
aead = True
|
| 313 |
+
else:
|
| 314 |
+
raise ValueError("Unknown encryption mode '%s'" % enc_algo)
|
| 315 |
+
|
| 316 |
+
iv_nonce = list(enc_param.values())[0]
|
| 317 |
+
salt = randfunc(prot_params.get("salt_size", 8))
|
| 318 |
+
|
| 319 |
+
# Derive key from password
|
| 320 |
+
if pbkdf == 'pbkdf2':
|
| 321 |
+
|
| 322 |
+
count = prot_params.get("iteration_count", 1000)
|
| 323 |
+
digestmod = Hash.new(pbkdf2_hmac_algo)
|
| 324 |
+
|
| 325 |
+
key = PBKDF2(passphrase,
|
| 326 |
+
salt,
|
| 327 |
+
key_size,
|
| 328 |
+
count,
|
| 329 |
+
hmac_hash_module=digestmod)
|
| 330 |
+
|
| 331 |
+
pbkdf2_params = DerSequence([
|
| 332 |
+
DerOctetString(salt),
|
| 333 |
+
DerInteger(count)
|
| 334 |
+
])
|
| 335 |
+
|
| 336 |
+
if pbkdf2_hmac_algo != 'SHA1':
|
| 337 |
+
try:
|
| 338 |
+
hmac_oid = Hash.HMAC.new(b'', digestmod=digestmod).oid
|
| 339 |
+
except KeyError:
|
| 340 |
+
raise ValueError("No OID for HMAC hash algorithm")
|
| 341 |
+
pbkdf2_params.append(DerSequence([DerObjectId(hmac_oid)]))
|
| 342 |
+
|
| 343 |
+
kdf_info = DerSequence([
|
| 344 |
+
DerObjectId(_OID_PBKDF2), # PBKDF2
|
| 345 |
+
pbkdf2_params
|
| 346 |
+
])
|
| 347 |
+
|
| 348 |
+
elif pbkdf == 'scrypt':
|
| 349 |
+
|
| 350 |
+
count = prot_params.get("iteration_count", 16384)
|
| 351 |
+
scrypt_r = prot_params.get('block_size', 8)
|
| 352 |
+
scrypt_p = prot_params.get('parallelization', 1)
|
| 353 |
+
key = scrypt(passphrase, salt, key_size,
|
| 354 |
+
count, scrypt_r, scrypt_p)
|
| 355 |
+
kdf_info = DerSequence([
|
| 356 |
+
DerObjectId(_OID_SCRYPT), # scrypt
|
| 357 |
+
DerSequence([
|
| 358 |
+
DerOctetString(salt),
|
| 359 |
+
DerInteger(count),
|
| 360 |
+
DerInteger(scrypt_r),
|
| 361 |
+
DerInteger(scrypt_p)
|
| 362 |
+
])
|
| 363 |
+
])
|
| 364 |
+
|
| 365 |
+
else:
|
| 366 |
+
raise ValueError("Unknown KDF " + res.group(1))
|
| 367 |
+
|
| 368 |
+
# Create cipher and use it
|
| 369 |
+
cipher = module.new(key, cipher_mode, **enc_param)
|
| 370 |
+
if aead:
|
| 371 |
+
ct, tag = cipher.encrypt_and_digest(data)
|
| 372 |
+
encrypted_data = ct + tag
|
| 373 |
+
else:
|
| 374 |
+
encrypted_data = cipher.encrypt(pad(data, cipher.block_size))
|
| 375 |
+
enc_info = DerSequence([
|
| 376 |
+
DerObjectId(enc_oid),
|
| 377 |
+
DerOctetString(iv_nonce)
|
| 378 |
+
])
|
| 379 |
+
|
| 380 |
+
# Result
|
| 381 |
+
enc_private_key_info = DerSequence([
|
| 382 |
+
# encryptionAlgorithm
|
| 383 |
+
DerSequence([
|
| 384 |
+
DerObjectId(_OID_PBES2),
|
| 385 |
+
DerSequence([
|
| 386 |
+
kdf_info,
|
| 387 |
+
enc_info
|
| 388 |
+
]),
|
| 389 |
+
]),
|
| 390 |
+
DerOctetString(encrypted_data)
|
| 391 |
+
])
|
| 392 |
+
return enc_private_key_info.encode()
|
| 393 |
+
|
| 394 |
+
@staticmethod
|
| 395 |
+
def decrypt(data, passphrase):
|
| 396 |
+
"""Decrypt a piece of data using a passphrase and *PBES2*.
|
| 397 |
+
|
| 398 |
+
The algorithm to use is automatically detected.
|
| 399 |
+
|
| 400 |
+
:Parameters:
|
| 401 |
+
data : byte string
|
| 402 |
+
The piece of data to decrypt.
|
| 403 |
+
passphrase : byte string
|
| 404 |
+
The passphrase to use for decrypting the data.
|
| 405 |
+
:Returns:
|
| 406 |
+
The decrypted data, as a binary string.
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
enc_private_key_info = DerSequence().decode(data, nr_elements=2)
|
| 410 |
+
enc_algo = DerSequence().decode(enc_private_key_info[0])
|
| 411 |
+
encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload
|
| 412 |
+
|
| 413 |
+
pbe_oid = DerObjectId().decode(enc_algo[0]).value
|
| 414 |
+
if pbe_oid != _OID_PBES2:
|
| 415 |
+
raise PbesError("Not a PBES2 object")
|
| 416 |
+
|
| 417 |
+
pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2)
|
| 418 |
+
|
| 419 |
+
# Key Derivation Function selection
|
| 420 |
+
kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2)
|
| 421 |
+
kdf_oid = DerObjectId().decode(kdf_info[0]).value
|
| 422 |
+
|
| 423 |
+
kdf_key_length = None
|
| 424 |
+
|
| 425 |
+
# We only support PBKDF2 or scrypt
|
| 426 |
+
if kdf_oid == _OID_PBKDF2:
|
| 427 |
+
|
| 428 |
+
pbkdf2_params = DerSequence().decode(kdf_info[1], nr_elements=(2, 3, 4))
|
| 429 |
+
salt = DerOctetString().decode(pbkdf2_params[0]).payload
|
| 430 |
+
iteration_count = pbkdf2_params[1]
|
| 431 |
+
|
| 432 |
+
left = len(pbkdf2_params) - 2
|
| 433 |
+
idx = 2
|
| 434 |
+
|
| 435 |
+
if left > 0:
|
| 436 |
+
try:
|
| 437 |
+
# Check if it's an INTEGER
|
| 438 |
+
kdf_key_length = pbkdf2_params[idx] - 0
|
| 439 |
+
left -= 1
|
| 440 |
+
idx += 1
|
| 441 |
+
except TypeError:
|
| 442 |
+
# keyLength is not present
|
| 443 |
+
pass
|
| 444 |
+
|
| 445 |
+
# Default is HMAC-SHA1
|
| 446 |
+
pbkdf2_prf_oid = _OID_HMAC_SHA1
|
| 447 |
+
if left > 0:
|
| 448 |
+
pbkdf2_prf_algo_id = DerSequence().decode(pbkdf2_params[idx])
|
| 449 |
+
pbkdf2_prf_oid = DerObjectId().decode(pbkdf2_prf_algo_id[0]).value
|
| 450 |
+
|
| 451 |
+
elif kdf_oid == _OID_SCRYPT:
|
| 452 |
+
|
| 453 |
+
scrypt_params = DerSequence().decode(kdf_info[1], nr_elements=(4, 5))
|
| 454 |
+
salt = DerOctetString().decode(scrypt_params[0]).payload
|
| 455 |
+
iteration_count, scrypt_r, scrypt_p = [scrypt_params[x]
|
| 456 |
+
for x in (1, 2, 3)]
|
| 457 |
+
if len(scrypt_params) > 4:
|
| 458 |
+
kdf_key_length = scrypt_params[4]
|
| 459 |
+
else:
|
| 460 |
+
kdf_key_length = None
|
| 461 |
+
else:
|
| 462 |
+
raise PbesError("Unsupported PBES2 KDF")
|
| 463 |
+
|
| 464 |
+
# Cipher selection
|
| 465 |
+
enc_info = DerSequence().decode(pbes2_params[1])
|
| 466 |
+
enc_oid = DerObjectId().decode(enc_info[0]).value
|
| 467 |
+
|
| 468 |
+
aead = False
|
| 469 |
+
if enc_oid == _OID_DES_EDE3_CBC:
|
| 470 |
+
# DES_EDE3_CBC
|
| 471 |
+
from Crypto.Cipher import DES3
|
| 472 |
+
module = DES3
|
| 473 |
+
cipher_mode = DES3.MODE_CBC
|
| 474 |
+
key_size = 24
|
| 475 |
+
cipher_param = 'iv'
|
| 476 |
+
elif enc_oid == _OID_AES128_CBC:
|
| 477 |
+
module = AES
|
| 478 |
+
cipher_mode = AES.MODE_CBC
|
| 479 |
+
key_size = 16
|
| 480 |
+
cipher_param = 'iv'
|
| 481 |
+
elif enc_oid == _OID_AES192_CBC:
|
| 482 |
+
module = AES
|
| 483 |
+
cipher_mode = AES.MODE_CBC
|
| 484 |
+
key_size = 24
|
| 485 |
+
cipher_param = 'iv'
|
| 486 |
+
elif enc_oid == _OID_AES256_CBC:
|
| 487 |
+
module = AES
|
| 488 |
+
cipher_mode = AES.MODE_CBC
|
| 489 |
+
key_size = 32
|
| 490 |
+
cipher_param = 'iv'
|
| 491 |
+
elif enc_oid == _OID_AES128_GCM:
|
| 492 |
+
module = AES
|
| 493 |
+
cipher_mode = AES.MODE_GCM
|
| 494 |
+
key_size = 16
|
| 495 |
+
cipher_param = 'nonce'
|
| 496 |
+
aead = True
|
| 497 |
+
elif enc_oid == _OID_AES192_GCM:
|
| 498 |
+
module = AES
|
| 499 |
+
cipher_mode = AES.MODE_GCM
|
| 500 |
+
key_size = 24
|
| 501 |
+
cipher_param = 'nonce'
|
| 502 |
+
aead = True
|
| 503 |
+
elif enc_oid == _OID_AES256_GCM:
|
| 504 |
+
module = AES
|
| 505 |
+
cipher_mode = AES.MODE_GCM
|
| 506 |
+
key_size = 32
|
| 507 |
+
cipher_param = 'nonce'
|
| 508 |
+
aead = True
|
| 509 |
+
else:
|
| 510 |
+
raise PbesError("Unsupported PBES2 cipher " + enc_algo)
|
| 511 |
+
|
| 512 |
+
if kdf_key_length and kdf_key_length != key_size:
|
| 513 |
+
raise PbesError("Mismatch between PBES2 KDF parameters"
|
| 514 |
+
" and selected cipher")
|
| 515 |
+
|
| 516 |
+
iv_nonce = DerOctetString().decode(enc_info[1]).payload
|
| 517 |
+
|
| 518 |
+
# Create cipher
|
| 519 |
+
if kdf_oid == _OID_PBKDF2:
|
| 520 |
+
|
| 521 |
+
try:
|
| 522 |
+
hmac_hash_module_oid = Hash.HMAC._hmac2hash_oid[pbkdf2_prf_oid]
|
| 523 |
+
except KeyError:
|
| 524 |
+
raise PbesError("Unsupported HMAC %s" % pbkdf2_prf_oid)
|
| 525 |
+
hmac_hash_module = Hash.new(hmac_hash_module_oid)
|
| 526 |
+
|
| 527 |
+
key = PBKDF2(passphrase, salt, key_size, iteration_count,
|
| 528 |
+
hmac_hash_module=hmac_hash_module)
|
| 529 |
+
else:
|
| 530 |
+
key = scrypt(passphrase, salt, key_size, iteration_count,
|
| 531 |
+
scrypt_r, scrypt_p)
|
| 532 |
+
cipher = module.new(key, cipher_mode, **{cipher_param:iv_nonce})
|
| 533 |
+
|
| 534 |
+
# Decrypt data
|
| 535 |
+
if len(encrypted_data) < cipher.block_size:
|
| 536 |
+
raise ValueError("Too little data to decrypt")
|
| 537 |
+
|
| 538 |
+
if aead:
|
| 539 |
+
tag_len = cipher.block_size
|
| 540 |
+
pt = cipher.decrypt_and_verify(encrypted_data[:-tag_len],
|
| 541 |
+
encrypted_data[-tag_len:])
|
| 542 |
+
else:
|
| 543 |
+
pt_padded = cipher.decrypt(encrypted_data)
|
| 544 |
+
pt = unpad(pt_padded, cipher.block_size)
|
| 545 |
+
|
| 546 |
+
return pt
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/_PBES.pyi
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Callable, TypedDict
|
| 2 |
+
from typing_extensions import NotRequired
|
| 3 |
+
|
| 4 |
+
class PbesError(ValueError):
|
| 5 |
+
...
|
| 6 |
+
|
| 7 |
+
class PBES1(object):
|
| 8 |
+
@staticmethod
|
| 9 |
+
def decrypt(data: bytes, passphrase: bytes) -> bytes: ...
|
| 10 |
+
|
| 11 |
+
class ProtParams(TypedDict):
|
| 12 |
+
iteration_count: NotRequired[int]
|
| 13 |
+
salt_size: NotRequired[int]
|
| 14 |
+
block_size: NotRequired[int]
|
| 15 |
+
parallelization: NotRequired[int]
|
| 16 |
+
|
| 17 |
+
class PBES2(object):
|
| 18 |
+
@staticmethod
|
| 19 |
+
def encrypt(data: bytes,
|
| 20 |
+
passphrase: bytes,
|
| 21 |
+
protection: str,
|
| 22 |
+
prot_params: Optional[ProtParams] = ...,
|
| 23 |
+
randfunc: Optional[Callable[[int],bytes]] = ...) -> bytes: ...
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def decrypt(data:bytes, passphrase: bytes) -> bytes: ...
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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__ = ['PEM', 'PKCS8']
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/PEM.cpython-310.pyc
ADDED
|
Binary file (4.55 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/PKCS8.cpython-310.pyc
ADDED
|
Binary file (4.21 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/_PBES.cpython-310.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/IO/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (189 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/DH.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
|
| 7 |
+
|
| 8 |
+
def _compute_ecdh(key_priv, key_pub):
|
| 9 |
+
pointP = key_pub.pointQ * key_priv.d
|
| 10 |
+
if pointP.is_point_at_infinity():
|
| 11 |
+
raise ValueError("Invalid ECDH point")
|
| 12 |
+
|
| 13 |
+
if key_priv.curve == "Curve25519":
|
| 14 |
+
z = bytearray(pointP.x.to_bytes(32, byteorder='little'))
|
| 15 |
+
elif key_priv.curve == "Curve448":
|
| 16 |
+
z = bytearray(pointP.x.to_bytes(56, byteorder='little'))
|
| 17 |
+
else:
|
| 18 |
+
# See Section 5.7.1.2 in NIST SP 800-56Ar3
|
| 19 |
+
z = long_to_bytes(pointP.x, pointP.size_in_bytes())
|
| 20 |
+
return z
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def import_x25519_public_key(encoded):
|
| 24 |
+
"""Create a new X25519 public key object,
|
| 25 |
+
starting from the key encoded as raw ``bytes``,
|
| 26 |
+
in the format described in RFC7748.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
encoded (bytes):
|
| 30 |
+
The x25519 public key to import.
|
| 31 |
+
It must be 32 bytes.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
:class:`Crypto.PublicKey.EccKey` : a new ECC key object.
|
| 35 |
+
|
| 36 |
+
Raises:
|
| 37 |
+
ValueError: when the given key cannot be parsed.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
x = _import_curve25519_public_key(encoded)
|
| 41 |
+
return construct(curve='Curve25519', point_x=x)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def import_x25519_private_key(encoded):
|
| 45 |
+
"""Create a new X25519 private key object,
|
| 46 |
+
starting from the key encoded as raw ``bytes``,
|
| 47 |
+
in the format described in RFC7748.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
encoded (bytes):
|
| 51 |
+
The X25519 private key to import.
|
| 52 |
+
It must be 32 bytes.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
:class:`Crypto.PublicKey.EccKey` : a new ECC key object.
|
| 56 |
+
|
| 57 |
+
Raises:
|
| 58 |
+
ValueError: when the given key cannot be parsed.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
return construct(seed=encoded, curve="Curve25519")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def import_x448_public_key(encoded):
|
| 65 |
+
"""Create a new X448 public key object,
|
| 66 |
+
starting from the key encoded as raw ``bytes``,
|
| 67 |
+
in the format described in RFC7748.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
encoded (bytes):
|
| 71 |
+
The x448 public key to import.
|
| 72 |
+
It must be 56 bytes.
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
:class:`Crypto.PublicKey.EccKey` : a new ECC key object.
|
| 76 |
+
|
| 77 |
+
Raises:
|
| 78 |
+
ValueError: when the given key cannot be parsed.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
x = _import_curve448_public_key(encoded)
|
| 82 |
+
return construct(curve='Curve448', point_x=x)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def import_x448_private_key(encoded):
|
| 86 |
+
"""Create a new X448 private key object,
|
| 87 |
+
starting from the key encoded as raw ``bytes``,
|
| 88 |
+
in the format described in RFC7748.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
encoded (bytes):
|
| 92 |
+
The X448 private key to import.
|
| 93 |
+
It must be 56 bytes.
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
:class:`Crypto.PublicKey.EccKey` : a new ECC key object.
|
| 97 |
+
|
| 98 |
+
Raises:
|
| 99 |
+
ValueError: when the given key cannot be parsed.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
return construct(seed=encoded, curve="Curve448")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def key_agreement(**kwargs):
|
| 106 |
+
"""Perform a Diffie-Hellman key agreement.
|
| 107 |
+
|
| 108 |
+
Keywords:
|
| 109 |
+
kdf (callable):
|
| 110 |
+
A key derivation function that accepts ``bytes`` as input and returns
|
| 111 |
+
``bytes``.
|
| 112 |
+
static_priv (EccKey):
|
| 113 |
+
The local static private key. Optional.
|
| 114 |
+
static_pub (EccKey):
|
| 115 |
+
The static public key that belongs to the peer. Optional.
|
| 116 |
+
eph_priv (EccKey):
|
| 117 |
+
The local ephemeral private key, generated for this session. Optional.
|
| 118 |
+
eph_pub (EccKey):
|
| 119 |
+
The ephemeral public key, received from the peer for this session. Optional.
|
| 120 |
+
|
| 121 |
+
At least two keys must be passed, of which one is a private key and one
|
| 122 |
+
a public key.
|
| 123 |
+
|
| 124 |
+
Returns (bytes):
|
| 125 |
+
The derived secret key material.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
static_priv = kwargs.get('static_priv', None)
|
| 129 |
+
static_pub = kwargs.get('static_pub', None)
|
| 130 |
+
eph_priv = kwargs.get('eph_priv', None)
|
| 131 |
+
eph_pub = kwargs.get('eph_pub', None)
|
| 132 |
+
kdf = kwargs.get('kdf', None)
|
| 133 |
+
|
| 134 |
+
if kdf is None:
|
| 135 |
+
raise ValueError("'kdf' is mandatory")
|
| 136 |
+
|
| 137 |
+
count_priv = 0
|
| 138 |
+
count_pub = 0
|
| 139 |
+
curve = None
|
| 140 |
+
|
| 141 |
+
def check_curve(curve, key, name, private):
|
| 142 |
+
if not isinstance(key, EccKey):
|
| 143 |
+
raise TypeError("'%s' must be an ECC key" % name)
|
| 144 |
+
if private and not key.has_private():
|
| 145 |
+
raise TypeError("'%s' must be a private ECC key" % name)
|
| 146 |
+
if curve is None:
|
| 147 |
+
curve = key.curve
|
| 148 |
+
elif curve != key.curve:
|
| 149 |
+
raise TypeError("'%s' is defined on an incompatible curve" % name)
|
| 150 |
+
return curve
|
| 151 |
+
|
| 152 |
+
if static_priv is not None:
|
| 153 |
+
curve = check_curve(curve, static_priv, 'static_priv', True)
|
| 154 |
+
count_priv += 1
|
| 155 |
+
|
| 156 |
+
if static_pub is not None:
|
| 157 |
+
curve = check_curve(curve, static_pub, 'static_pub', False)
|
| 158 |
+
count_pub += 1
|
| 159 |
+
|
| 160 |
+
if eph_priv is not None:
|
| 161 |
+
curve = check_curve(curve, eph_priv, 'eph_priv', True)
|
| 162 |
+
count_priv += 1
|
| 163 |
+
|
| 164 |
+
if eph_pub is not None:
|
| 165 |
+
curve = check_curve(curve, eph_pub, 'eph_pub', False)
|
| 166 |
+
count_pub += 1
|
| 167 |
+
|
| 168 |
+
if (count_priv + count_pub) < 2 or count_priv == 0 or count_pub == 0:
|
| 169 |
+
raise ValueError("Too few keys for the ECDH key agreement")
|
| 170 |
+
|
| 171 |
+
Zs = b''
|
| 172 |
+
Ze = b''
|
| 173 |
+
|
| 174 |
+
if static_priv and static_pub:
|
| 175 |
+
# C(*, 2s)
|
| 176 |
+
Zs = _compute_ecdh(static_priv, static_pub)
|
| 177 |
+
|
| 178 |
+
if eph_priv and eph_pub:
|
| 179 |
+
# C(2e, 0s) or C(2e, 2s)
|
| 180 |
+
if bool(static_priv) != bool(static_pub):
|
| 181 |
+
raise ValueError("DH mode C(2e, 1s) is not supported")
|
| 182 |
+
Ze = _compute_ecdh(eph_priv, eph_pub)
|
| 183 |
+
elif eph_priv and static_pub:
|
| 184 |
+
# C(1e, 2s) or C(1e, 1s)
|
| 185 |
+
Ze = _compute_ecdh(eph_priv, static_pub)
|
| 186 |
+
elif eph_pub and static_priv:
|
| 187 |
+
# C(1e, 2s) or C(1e, 1s)
|
| 188 |
+
Ze = _compute_ecdh(static_priv, eph_pub)
|
| 189 |
+
|
| 190 |
+
Z = Ze + Zs
|
| 191 |
+
|
| 192 |
+
return kdf(Z)
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/KDF.py
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
#
|
| 3 |
+
# KDF.py : a collection of Key Derivation Functions
|
| 4 |
+
#
|
| 5 |
+
# Part of the Python Cryptography Toolkit
|
| 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 |
+
import re
|
| 26 |
+
import struct
|
| 27 |
+
from functools import reduce
|
| 28 |
+
|
| 29 |
+
from Crypto.Util.py3compat import (tobytes, bord, _copy_bytes, iter_range,
|
| 30 |
+
tostr, bchr, bstr)
|
| 31 |
+
|
| 32 |
+
from Crypto.Hash import SHA1, SHA256, HMAC, CMAC, BLAKE2s
|
| 33 |
+
from Crypto.Util.strxor import strxor
|
| 34 |
+
from Crypto.Random import get_random_bytes
|
| 35 |
+
from Crypto.Util.number import size as bit_size, long_to_bytes, bytes_to_long
|
| 36 |
+
|
| 37 |
+
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
|
| 38 |
+
create_string_buffer,
|
| 39 |
+
get_raw_buffer, c_size_t)
|
| 40 |
+
|
| 41 |
+
_raw_salsa20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._Salsa20",
|
| 42 |
+
"""
|
| 43 |
+
int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
|
| 44 |
+
uint8_t *out);
|
| 45 |
+
""")
|
| 46 |
+
|
| 47 |
+
_raw_scrypt_lib = load_pycryptodome_raw_lib("Crypto.Protocol._scrypt",
|
| 48 |
+
"""
|
| 49 |
+
typedef int (core_t)(const uint8_t [64], const uint8_t [64], uint8_t [64]);
|
| 50 |
+
int scryptROMix(const uint8_t *data_in, uint8_t *data_out,
|
| 51 |
+
size_t data_len, unsigned N, core_t *core);
|
| 52 |
+
""")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
|
| 56 |
+
"""Derive one key from a password (or passphrase).
|
| 57 |
+
|
| 58 |
+
This function performs key derivation according to an old version of
|
| 59 |
+
the PKCS#5 standard (v1.5) or `RFC2898
|
| 60 |
+
<https://www.ietf.org/rfc/rfc2898.txt>`_.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
password (string):
|
| 64 |
+
The secret password to generate the key from.
|
| 65 |
+
salt (byte string):
|
| 66 |
+
An 8 byte string to use for better protection from dictionary attacks.
|
| 67 |
+
This value does not need to be kept secret, but it should be randomly
|
| 68 |
+
chosen for each derivation.
|
| 69 |
+
dkLen (integer):
|
| 70 |
+
The length of the desired key. The default is 16 bytes, suitable for
|
| 71 |
+
instance for :mod:`Crypto.Cipher.AES`.
|
| 72 |
+
count (integer):
|
| 73 |
+
The number of iterations to carry out. The recommendation is 1000 or
|
| 74 |
+
more.
|
| 75 |
+
hashAlgo (module):
|
| 76 |
+
The hash algorithm to use, as a module or an object from the :mod:`Crypto.Hash` package.
|
| 77 |
+
The digest length must be no shorter than ``dkLen``.
|
| 78 |
+
The default algorithm is :mod:`Crypto.Hash.SHA1`.
|
| 79 |
+
|
| 80 |
+
Return:
|
| 81 |
+
A byte string of length ``dkLen`` that can be used as key.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
if not hashAlgo:
|
| 85 |
+
hashAlgo = SHA1
|
| 86 |
+
password = tobytes(password)
|
| 87 |
+
pHash = hashAlgo.new(password+salt)
|
| 88 |
+
digest = pHash.digest_size
|
| 89 |
+
if dkLen > digest:
|
| 90 |
+
raise TypeError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
|
| 91 |
+
if len(salt) != 8:
|
| 92 |
+
raise ValueError("Salt is not 8 bytes long (%d bytes instead)." % len(salt))
|
| 93 |
+
for i in iter_range(count-1):
|
| 94 |
+
pHash = pHash.new(pHash.digest())
|
| 95 |
+
return pHash.digest()[:dkLen]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def PBKDF2(password, salt, dkLen=16, count=1000, prf=None, hmac_hash_module=None):
|
| 99 |
+
"""Derive one or more keys from a password (or passphrase).
|
| 100 |
+
|
| 101 |
+
This function performs key derivation according to the PKCS#5 standard (v2.0).
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
password (string or byte string):
|
| 105 |
+
The secret password to generate the key from.
|
| 106 |
+
|
| 107 |
+
Strings will be encoded as ISO 8859-1 (also known as Latin-1),
|
| 108 |
+
which does not allow any characters with codepoints > 255.
|
| 109 |
+
salt (string or byte string):
|
| 110 |
+
A (byte) string to use for better protection from dictionary attacks.
|
| 111 |
+
This value does not need to be kept secret, but it should be randomly
|
| 112 |
+
chosen for each derivation. It is recommended to use at least 16 bytes.
|
| 113 |
+
|
| 114 |
+
Strings will be encoded as ISO 8859-1 (also known as Latin-1),
|
| 115 |
+
which does not allow any characters with codepoints > 255.
|
| 116 |
+
dkLen (integer):
|
| 117 |
+
The cumulative length of the keys to produce.
|
| 118 |
+
|
| 119 |
+
Due to a flaw in the PBKDF2 design, you should not request more bytes
|
| 120 |
+
than the ``prf`` can output. For instance, ``dkLen`` should not exceed
|
| 121 |
+
20 bytes in combination with ``HMAC-SHA1``.
|
| 122 |
+
count (integer):
|
| 123 |
+
The number of iterations to carry out. The higher the value, the slower
|
| 124 |
+
and the more secure the function becomes.
|
| 125 |
+
|
| 126 |
+
You should find the maximum number of iterations that keeps the
|
| 127 |
+
key derivation still acceptable on the slowest hardware you must support.
|
| 128 |
+
|
| 129 |
+
Although the default value is 1000, **it is recommended to use at least
|
| 130 |
+
1000000 (1 million) iterations**.
|
| 131 |
+
prf (callable):
|
| 132 |
+
A pseudorandom function. It must be a function that returns a
|
| 133 |
+
pseudorandom byte string from two parameters: a secret and a salt.
|
| 134 |
+
The slower the algorithm, the more secure the derivation function.
|
| 135 |
+
If not specified, **HMAC-SHA1** is used.
|
| 136 |
+
hmac_hash_module (module):
|
| 137 |
+
A module from ``Crypto.Hash`` implementing a Merkle-Damgard cryptographic
|
| 138 |
+
hash, which PBKDF2 must use in combination with HMAC.
|
| 139 |
+
This parameter is mutually exclusive with ``prf``.
|
| 140 |
+
|
| 141 |
+
Return:
|
| 142 |
+
A byte string of length ``dkLen`` that can be used as key material.
|
| 143 |
+
If you want multiple keys, just break up this string into segments of the desired length.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
password = tobytes(password)
|
| 147 |
+
salt = tobytes(salt)
|
| 148 |
+
|
| 149 |
+
if prf and hmac_hash_module:
|
| 150 |
+
raise ValueError("'prf' and 'hmac_hash_module' are mutually exlusive")
|
| 151 |
+
|
| 152 |
+
if prf is None and hmac_hash_module is None:
|
| 153 |
+
hmac_hash_module = SHA1
|
| 154 |
+
|
| 155 |
+
if prf or not hasattr(hmac_hash_module, "_pbkdf2_hmac_assist"):
|
| 156 |
+
# Generic (and slow) implementation
|
| 157 |
+
|
| 158 |
+
if prf is None:
|
| 159 |
+
prf = lambda p,s: HMAC.new(p, s, hmac_hash_module).digest()
|
| 160 |
+
|
| 161 |
+
def link(s):
|
| 162 |
+
s[0], s[1] = s[1], prf(password, s[1])
|
| 163 |
+
return s[0]
|
| 164 |
+
|
| 165 |
+
key = b''
|
| 166 |
+
i = 1
|
| 167 |
+
while len(key) < dkLen:
|
| 168 |
+
s = [ prf(password, salt + struct.pack(">I", i)) ] * 2
|
| 169 |
+
key += reduce(strxor, (link(s) for j in range(count)) )
|
| 170 |
+
i += 1
|
| 171 |
+
|
| 172 |
+
else:
|
| 173 |
+
# Optimized implementation
|
| 174 |
+
key = b''
|
| 175 |
+
i = 1
|
| 176 |
+
while len(key)<dkLen:
|
| 177 |
+
base = HMAC.new(password, b"", hmac_hash_module)
|
| 178 |
+
first_digest = base.copy().update(salt + struct.pack(">I", i)).digest()
|
| 179 |
+
key += base._pbkdf2_hmac_assist(first_digest, count)
|
| 180 |
+
i += 1
|
| 181 |
+
|
| 182 |
+
return key[:dkLen]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class _S2V(object):
|
| 186 |
+
"""String-to-vector PRF as defined in `RFC5297`_.
|
| 187 |
+
|
| 188 |
+
This class implements a pseudorandom function family
|
| 189 |
+
based on CMAC that takes as input a vector of strings.
|
| 190 |
+
|
| 191 |
+
.. _RFC5297: http://tools.ietf.org/html/rfc5297
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def __init__(self, key, ciphermod, cipher_params=None):
|
| 195 |
+
"""Initialize the S2V PRF.
|
| 196 |
+
|
| 197 |
+
:Parameters:
|
| 198 |
+
key : byte string
|
| 199 |
+
A secret that can be used as key for CMACs
|
| 200 |
+
based on ciphers from ``ciphermod``.
|
| 201 |
+
ciphermod : module
|
| 202 |
+
A block cipher module from `Crypto.Cipher`.
|
| 203 |
+
cipher_params : dictionary
|
| 204 |
+
A set of extra parameters to use to create a cipher instance.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
self._key = _copy_bytes(None, None, key)
|
| 208 |
+
self._ciphermod = ciphermod
|
| 209 |
+
self._last_string = self._cache = b'\x00' * ciphermod.block_size
|
| 210 |
+
|
| 211 |
+
# Max number of update() call we can process
|
| 212 |
+
self._n_updates = ciphermod.block_size * 8 - 1
|
| 213 |
+
|
| 214 |
+
if cipher_params is None:
|
| 215 |
+
self._cipher_params = {}
|
| 216 |
+
else:
|
| 217 |
+
self._cipher_params = dict(cipher_params)
|
| 218 |
+
|
| 219 |
+
@staticmethod
|
| 220 |
+
def new(key, ciphermod):
|
| 221 |
+
"""Create a new S2V PRF.
|
| 222 |
+
|
| 223 |
+
:Parameters:
|
| 224 |
+
key : byte string
|
| 225 |
+
A secret that can be used as key for CMACs
|
| 226 |
+
based on ciphers from ``ciphermod``.
|
| 227 |
+
ciphermod : module
|
| 228 |
+
A block cipher module from `Crypto.Cipher`.
|
| 229 |
+
"""
|
| 230 |
+
return _S2V(key, ciphermod)
|
| 231 |
+
|
| 232 |
+
def _double(self, bs):
|
| 233 |
+
doubled = bytes_to_long(bs)<<1
|
| 234 |
+
if bord(bs[0]) & 0x80:
|
| 235 |
+
doubled ^= 0x87
|
| 236 |
+
return long_to_bytes(doubled, len(bs))[-len(bs):]
|
| 237 |
+
|
| 238 |
+
def update(self, item):
|
| 239 |
+
"""Pass the next component of the vector.
|
| 240 |
+
|
| 241 |
+
The maximum number of components you can pass is equal to the block
|
| 242 |
+
length of the cipher (in bits) minus 1.
|
| 243 |
+
|
| 244 |
+
:Parameters:
|
| 245 |
+
item : byte string
|
| 246 |
+
The next component of the vector.
|
| 247 |
+
:Raise TypeError: when the limit on the number of components has been reached.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
if self._n_updates == 0:
|
| 251 |
+
raise TypeError("Too many components passed to S2V")
|
| 252 |
+
self._n_updates -= 1
|
| 253 |
+
|
| 254 |
+
mac = CMAC.new(self._key,
|
| 255 |
+
msg=self._last_string,
|
| 256 |
+
ciphermod=self._ciphermod,
|
| 257 |
+
cipher_params=self._cipher_params)
|
| 258 |
+
self._cache = strxor(self._double(self._cache), mac.digest())
|
| 259 |
+
self._last_string = _copy_bytes(None, None, item)
|
| 260 |
+
|
| 261 |
+
def derive(self):
|
| 262 |
+
""""Derive a secret from the vector of components.
|
| 263 |
+
|
| 264 |
+
:Return: a byte string, as long as the block length of the cipher.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
if len(self._last_string) >= 16:
|
| 268 |
+
# xorend
|
| 269 |
+
final = self._last_string[:-16] + strxor(self._last_string[-16:], self._cache)
|
| 270 |
+
else:
|
| 271 |
+
# zero-pad & xor
|
| 272 |
+
padded = (self._last_string + b'\x80' + b'\x00' * 15)[:16]
|
| 273 |
+
final = strxor(padded, self._double(self._cache))
|
| 274 |
+
mac = CMAC.new(self._key,
|
| 275 |
+
msg=final,
|
| 276 |
+
ciphermod=self._ciphermod,
|
| 277 |
+
cipher_params=self._cipher_params)
|
| 278 |
+
return mac.digest()
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def HKDF(master, key_len, salt, hashmod, num_keys=1, context=None):
|
| 282 |
+
"""Derive one or more keys from a master secret using
|
| 283 |
+
the HMAC-based KDF defined in RFC5869_.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
master (byte string):
|
| 287 |
+
The unguessable value used by the KDF to generate the other keys.
|
| 288 |
+
It must be a high-entropy secret, though not necessarily uniform.
|
| 289 |
+
It must not be a password.
|
| 290 |
+
key_len (integer):
|
| 291 |
+
The length in bytes of every derived key.
|
| 292 |
+
salt (byte string):
|
| 293 |
+
A non-secret, reusable value that strengthens the randomness
|
| 294 |
+
extraction step.
|
| 295 |
+
Ideally, it is as long as the digest size of the chosen hash.
|
| 296 |
+
If empty, a string of zeroes in used.
|
| 297 |
+
hashmod (module):
|
| 298 |
+
A cryptographic hash algorithm from :mod:`Crypto.Hash`.
|
| 299 |
+
:mod:`Crypto.Hash.SHA512` is a good choice.
|
| 300 |
+
num_keys (integer):
|
| 301 |
+
The number of keys to derive. Every key is :data:`key_len` bytes long.
|
| 302 |
+
The maximum cumulative length of all keys is
|
| 303 |
+
255 times the digest size.
|
| 304 |
+
context (byte string):
|
| 305 |
+
Optional identifier describing what the keys are used for.
|
| 306 |
+
|
| 307 |
+
Return:
|
| 308 |
+
A byte string or a tuple of byte strings.
|
| 309 |
+
|
| 310 |
+
.. _RFC5869: http://tools.ietf.org/html/rfc5869
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
output_len = key_len * num_keys
|
| 314 |
+
if output_len > (255 * hashmod.digest_size):
|
| 315 |
+
raise ValueError("Too much secret data to derive")
|
| 316 |
+
if not salt:
|
| 317 |
+
salt = b'\x00' * hashmod.digest_size
|
| 318 |
+
if context is None:
|
| 319 |
+
context = b""
|
| 320 |
+
|
| 321 |
+
# Step 1: extract
|
| 322 |
+
hmac = HMAC.new(salt, master, digestmod=hashmod)
|
| 323 |
+
prk = hmac.digest()
|
| 324 |
+
|
| 325 |
+
# Step 2: expand
|
| 326 |
+
t = [ b"" ]
|
| 327 |
+
n = 1
|
| 328 |
+
tlen = 0
|
| 329 |
+
while tlen < output_len:
|
| 330 |
+
hmac = HMAC.new(prk, t[-1] + context + struct.pack('B', n), digestmod=hashmod)
|
| 331 |
+
t.append(hmac.digest())
|
| 332 |
+
tlen += hashmod.digest_size
|
| 333 |
+
n += 1
|
| 334 |
+
derived_output = b"".join(t)
|
| 335 |
+
if num_keys == 1:
|
| 336 |
+
return derived_output[:key_len]
|
| 337 |
+
kol = [derived_output[idx:idx + key_len]
|
| 338 |
+
for idx in iter_range(0, output_len, key_len)]
|
| 339 |
+
return list(kol[:num_keys])
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def scrypt(password, salt, key_len, N, r, p, num_keys=1):
|
| 344 |
+
"""Derive one or more keys from a passphrase.
|
| 345 |
+
|
| 346 |
+
Args:
|
| 347 |
+
password (string):
|
| 348 |
+
The secret pass phrase to generate the keys from.
|
| 349 |
+
salt (string):
|
| 350 |
+
A string to use for better protection from dictionary attacks.
|
| 351 |
+
This value does not need to be kept secret,
|
| 352 |
+
but it should be randomly chosen for each derivation.
|
| 353 |
+
It is recommended to be at least 16 bytes long.
|
| 354 |
+
key_len (integer):
|
| 355 |
+
The length in bytes of each derived key.
|
| 356 |
+
N (integer):
|
| 357 |
+
CPU/Memory cost parameter. It must be a power of 2 and less
|
| 358 |
+
than :math:`2^{32}`.
|
| 359 |
+
r (integer):
|
| 360 |
+
Block size parameter.
|
| 361 |
+
p (integer):
|
| 362 |
+
Parallelization parameter.
|
| 363 |
+
It must be no greater than :math:`(2^{32}-1)/(4r)`.
|
| 364 |
+
num_keys (integer):
|
| 365 |
+
The number of keys to derive. Every key is :data:`key_len` bytes long.
|
| 366 |
+
By default, only 1 key is generated.
|
| 367 |
+
The maximum cumulative length of all keys is :math:`(2^{32}-1)*32`
|
| 368 |
+
(that is, 128TB).
|
| 369 |
+
|
| 370 |
+
A good choice of parameters *(N, r , p)* was suggested
|
| 371 |
+
by Colin Percival in his `presentation in 2009`__:
|
| 372 |
+
|
| 373 |
+
- *( 2¹⁴, 8, 1 )* for interactive logins (≤100ms)
|
| 374 |
+
- *( 2²⁰, 8, 1 )* for file encryption (≤5s)
|
| 375 |
+
|
| 376 |
+
Return:
|
| 377 |
+
A byte string or a tuple of byte strings.
|
| 378 |
+
|
| 379 |
+
.. __: http://www.tarsnap.com/scrypt/scrypt-slides.pdf
|
| 380 |
+
"""
|
| 381 |
+
|
| 382 |
+
if 2 ** (bit_size(N) - 1) != N:
|
| 383 |
+
raise ValueError("N must be a power of 2")
|
| 384 |
+
if N >= 2 ** 32:
|
| 385 |
+
raise ValueError("N is too big")
|
| 386 |
+
if p > ((2 ** 32 - 1) * 32) // (128 * r):
|
| 387 |
+
raise ValueError("p or r are too big")
|
| 388 |
+
|
| 389 |
+
prf_hmac_sha256 = lambda p, s: HMAC.new(p, s, SHA256).digest()
|
| 390 |
+
|
| 391 |
+
stage_1 = PBKDF2(password, salt, p * 128 * r, 1, prf=prf_hmac_sha256)
|
| 392 |
+
|
| 393 |
+
scryptROMix = _raw_scrypt_lib.scryptROMix
|
| 394 |
+
core = _raw_salsa20_lib.Salsa20_8_core
|
| 395 |
+
|
| 396 |
+
# Parallelize into p flows
|
| 397 |
+
data_out = []
|
| 398 |
+
for flow in iter_range(p):
|
| 399 |
+
idx = flow * 128 * r
|
| 400 |
+
buffer_out = create_string_buffer(128 * r)
|
| 401 |
+
result = scryptROMix(stage_1[idx : idx + 128 * r],
|
| 402 |
+
buffer_out,
|
| 403 |
+
c_size_t(128 * r),
|
| 404 |
+
N,
|
| 405 |
+
core)
|
| 406 |
+
if result:
|
| 407 |
+
raise ValueError("Error %X while running scrypt" % result)
|
| 408 |
+
data_out += [ get_raw_buffer(buffer_out) ]
|
| 409 |
+
|
| 410 |
+
dk = PBKDF2(password,
|
| 411 |
+
b"".join(data_out),
|
| 412 |
+
key_len * num_keys, 1,
|
| 413 |
+
prf=prf_hmac_sha256)
|
| 414 |
+
|
| 415 |
+
if num_keys == 1:
|
| 416 |
+
return dk
|
| 417 |
+
|
| 418 |
+
kol = [dk[idx:idx + key_len]
|
| 419 |
+
for idx in iter_range(0, key_len * num_keys, key_len)]
|
| 420 |
+
return kol
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _bcrypt_encode(data):
|
| 424 |
+
s = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
| 425 |
+
|
| 426 |
+
bits = []
|
| 427 |
+
for c in data:
|
| 428 |
+
bits_c = bin(bord(c))[2:].zfill(8)
|
| 429 |
+
bits.append(bstr(bits_c))
|
| 430 |
+
bits = b"".join(bits)
|
| 431 |
+
|
| 432 |
+
bits6 = [ bits[idx:idx+6] for idx in range(0, len(bits), 6) ]
|
| 433 |
+
|
| 434 |
+
result = []
|
| 435 |
+
for g in bits6[:-1]:
|
| 436 |
+
idx = int(g, 2)
|
| 437 |
+
result.append(s[idx])
|
| 438 |
+
|
| 439 |
+
g = bits6[-1]
|
| 440 |
+
idx = int(g, 2) << (6 - len(g))
|
| 441 |
+
result.append(s[idx])
|
| 442 |
+
result = "".join(result)
|
| 443 |
+
|
| 444 |
+
return tobytes(result)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _bcrypt_decode(data):
|
| 448 |
+
s = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
| 449 |
+
|
| 450 |
+
bits = []
|
| 451 |
+
for c in tostr(data):
|
| 452 |
+
idx = s.find(c)
|
| 453 |
+
bits6 = bin(idx)[2:].zfill(6)
|
| 454 |
+
bits.append(bits6)
|
| 455 |
+
bits = "".join(bits)
|
| 456 |
+
|
| 457 |
+
modulo4 = len(data) % 4
|
| 458 |
+
if modulo4 == 1:
|
| 459 |
+
raise ValueError("Incorrect length")
|
| 460 |
+
elif modulo4 == 2:
|
| 461 |
+
bits = bits[:-4]
|
| 462 |
+
elif modulo4 == 3:
|
| 463 |
+
bits = bits[:-2]
|
| 464 |
+
|
| 465 |
+
bits8 = [ bits[idx:idx+8] for idx in range(0, len(bits), 8) ]
|
| 466 |
+
|
| 467 |
+
result = []
|
| 468 |
+
for g in bits8:
|
| 469 |
+
result.append(bchr(int(g, 2)))
|
| 470 |
+
result = b"".join(result)
|
| 471 |
+
|
| 472 |
+
return result
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _bcrypt_hash(password, cost, salt, constant, invert):
|
| 476 |
+
from Crypto.Cipher import _EKSBlowfish
|
| 477 |
+
|
| 478 |
+
if len(password) > 72:
|
| 479 |
+
raise ValueError("The password is too long. It must be 72 bytes at most.")
|
| 480 |
+
|
| 481 |
+
if not (4 <= cost <= 31):
|
| 482 |
+
raise ValueError("bcrypt cost factor must be in the range 4..31")
|
| 483 |
+
|
| 484 |
+
cipher = _EKSBlowfish.new(password, _EKSBlowfish.MODE_ECB, salt, cost, invert)
|
| 485 |
+
ctext = constant
|
| 486 |
+
for _ in range(64):
|
| 487 |
+
ctext = cipher.encrypt(ctext)
|
| 488 |
+
return ctext
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def bcrypt(password, cost, salt=None):
|
| 492 |
+
"""Hash a password into a key, using the OpenBSD bcrypt protocol.
|
| 493 |
+
|
| 494 |
+
Args:
|
| 495 |
+
password (byte string or string):
|
| 496 |
+
The secret password or pass phrase.
|
| 497 |
+
It must be at most 72 bytes long.
|
| 498 |
+
It must not contain the zero byte.
|
| 499 |
+
Unicode strings will be encoded as UTF-8.
|
| 500 |
+
cost (integer):
|
| 501 |
+
The exponential factor that makes it slower to compute the hash.
|
| 502 |
+
It must be in the range 4 to 31.
|
| 503 |
+
A value of at least 12 is recommended.
|
| 504 |
+
salt (byte string):
|
| 505 |
+
Optional. Random byte string to thwarts dictionary and rainbow table
|
| 506 |
+
attacks. It must be 16 bytes long.
|
| 507 |
+
If not passed, a random value is generated.
|
| 508 |
+
|
| 509 |
+
Return (byte string):
|
| 510 |
+
The bcrypt hash
|
| 511 |
+
|
| 512 |
+
Raises:
|
| 513 |
+
ValueError: if password is longer than 72 bytes or if it contains the zero byte
|
| 514 |
+
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
password = tobytes(password, "utf-8")
|
| 518 |
+
|
| 519 |
+
if password.find(bchr(0)[0]) != -1:
|
| 520 |
+
raise ValueError("The password contains the zero byte")
|
| 521 |
+
|
| 522 |
+
if len(password) < 72:
|
| 523 |
+
password += b"\x00"
|
| 524 |
+
|
| 525 |
+
if salt is None:
|
| 526 |
+
salt = get_random_bytes(16)
|
| 527 |
+
if len(salt) != 16:
|
| 528 |
+
raise ValueError("bcrypt salt must be 16 bytes long")
|
| 529 |
+
|
| 530 |
+
ctext = _bcrypt_hash(password, cost, salt, b"OrpheanBeholderScryDoubt", True)
|
| 531 |
+
|
| 532 |
+
cost_enc = b"$" + bstr(str(cost).zfill(2))
|
| 533 |
+
salt_enc = b"$" + _bcrypt_encode(salt)
|
| 534 |
+
hash_enc = _bcrypt_encode(ctext[:-1]) # only use 23 bytes, not 24
|
| 535 |
+
return b"$2a" + cost_enc + salt_enc + hash_enc
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def bcrypt_check(password, bcrypt_hash):
|
| 539 |
+
"""Verify if the provided password matches the given bcrypt hash.
|
| 540 |
+
|
| 541 |
+
Args:
|
| 542 |
+
password (byte string or string):
|
| 543 |
+
The secret password or pass phrase to test.
|
| 544 |
+
It must be at most 72 bytes long.
|
| 545 |
+
It must not contain the zero byte.
|
| 546 |
+
Unicode strings will be encoded as UTF-8.
|
| 547 |
+
bcrypt_hash (byte string, bytearray):
|
| 548 |
+
The reference bcrypt hash the password needs to be checked against.
|
| 549 |
+
|
| 550 |
+
Raises:
|
| 551 |
+
ValueError: if the password does not match
|
| 552 |
+
"""
|
| 553 |
+
|
| 554 |
+
bcrypt_hash = tobytes(bcrypt_hash)
|
| 555 |
+
|
| 556 |
+
if len(bcrypt_hash) != 60:
|
| 557 |
+
raise ValueError("Incorrect length of the bcrypt hash: %d bytes instead of 60" % len(bcrypt_hash))
|
| 558 |
+
|
| 559 |
+
if bcrypt_hash[:4] != b'$2a$':
|
| 560 |
+
raise ValueError("Unsupported prefix")
|
| 561 |
+
|
| 562 |
+
p = re.compile(br'\$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})')
|
| 563 |
+
r = p.match(bcrypt_hash)
|
| 564 |
+
if not r:
|
| 565 |
+
raise ValueError("Incorrect bcrypt hash format")
|
| 566 |
+
|
| 567 |
+
cost = int(r.group(1))
|
| 568 |
+
if not (4 <= cost <= 31):
|
| 569 |
+
raise ValueError("Incorrect cost")
|
| 570 |
+
|
| 571 |
+
salt = _bcrypt_decode(r.group(2))
|
| 572 |
+
|
| 573 |
+
bcrypt_hash2 = bcrypt(password, cost, salt)
|
| 574 |
+
|
| 575 |
+
secret = get_random_bytes(16)
|
| 576 |
+
|
| 577 |
+
mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash).digest()
|
| 578 |
+
mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash2).digest()
|
| 579 |
+
if mac1 != mac2:
|
| 580 |
+
raise ValueError("Incorrect bcrypt hash")
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def SP800_108_Counter(master, key_len, prf, num_keys=None, label=b'', context=b''):
|
| 584 |
+
"""Derive one or more keys from a master secret using
|
| 585 |
+
a pseudorandom function in Counter Mode, as specified in
|
| 586 |
+
`NIST SP 800-108r1 <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-108r1.pdf>`_.
|
| 587 |
+
|
| 588 |
+
Args:
|
| 589 |
+
master (byte string):
|
| 590 |
+
The secret value used by the KDF to derive the other keys.
|
| 591 |
+
It must not be a password.
|
| 592 |
+
The length on the secret must be consistent with the input expected by
|
| 593 |
+
the :data:`prf` function.
|
| 594 |
+
key_len (integer):
|
| 595 |
+
The length in bytes of each derived key.
|
| 596 |
+
prf (function):
|
| 597 |
+
A pseudorandom function that takes two byte strings as parameters:
|
| 598 |
+
the secret and an input. It returns another byte string.
|
| 599 |
+
num_keys (integer):
|
| 600 |
+
The number of keys to derive. Every key is :data:`key_len` bytes long.
|
| 601 |
+
By default, only 1 key is derived.
|
| 602 |
+
label (byte string):
|
| 603 |
+
Optional description of the purpose of the derived keys.
|
| 604 |
+
It must not contain zero bytes.
|
| 605 |
+
context (byte string):
|
| 606 |
+
Optional information pertaining to
|
| 607 |
+
the protocol that uses the keys, such as the identity of the
|
| 608 |
+
participants, nonces, session IDs, etc.
|
| 609 |
+
It must not contain zero bytes.
|
| 610 |
+
|
| 611 |
+
Return:
|
| 612 |
+
- a byte string (if ``num_keys`` is not specified), or
|
| 613 |
+
- a tuple of byte strings (if ``num_key`` is specified).
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
if num_keys is None:
|
| 617 |
+
num_keys = 1
|
| 618 |
+
|
| 619 |
+
if context.find(b'\x00') != -1:
|
| 620 |
+
raise ValueError("Null byte found in context")
|
| 621 |
+
|
| 622 |
+
key_len_enc = long_to_bytes(key_len * num_keys * 8, 4)
|
| 623 |
+
output_len = key_len * num_keys
|
| 624 |
+
|
| 625 |
+
i = 1
|
| 626 |
+
dk = b""
|
| 627 |
+
while len(dk) < output_len:
|
| 628 |
+
info = long_to_bytes(i, 4) + label + b'\x00' + context + key_len_enc
|
| 629 |
+
dk += prf(master, info)
|
| 630 |
+
i += 1
|
| 631 |
+
if i > 0xFFFFFFFF:
|
| 632 |
+
raise ValueError("Overflow in SP800 108 counter")
|
| 633 |
+
|
| 634 |
+
if num_keys == 1:
|
| 635 |
+
return dk[:key_len]
|
| 636 |
+
else:
|
| 637 |
+
kol = [dk[idx:idx + key_len]
|
| 638 |
+
for idx in iter_range(0, output_len, key_len)]
|
| 639 |
+
return kol
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/KDF.pyi
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import ModuleType
|
| 2 |
+
from typing import Optional, Callable, Tuple, Union, Dict, Any, overload
|
| 3 |
+
from typing_extensions import Literal
|
| 4 |
+
|
| 5 |
+
Buffer=bytes|bytearray|memoryview
|
| 6 |
+
|
| 7 |
+
RNG = Callable[[int], bytes]
|
| 8 |
+
PRF = Callable[[bytes, bytes], bytes]
|
| 9 |
+
|
| 10 |
+
def PBKDF1(password: str, salt: bytes, dkLen: int, count: Optional[int]=1000, hashAlgo: Optional[ModuleType]=None) -> bytes: ...
|
| 11 |
+
def PBKDF2(password: str, salt: bytes, dkLen: Optional[int]=16, count: Optional[int]=1000, prf: Optional[RNG]=None, hmac_hash_module: Optional[ModuleType]=None) -> bytes: ...
|
| 12 |
+
|
| 13 |
+
class _S2V(object):
|
| 14 |
+
def __init__(self, key: bytes, ciphermod: ModuleType, cipher_params: Optional[Dict[Any, Any]]=None) -> None: ...
|
| 15 |
+
|
| 16 |
+
@staticmethod
|
| 17 |
+
def new(key: bytes, ciphermod: ModuleType) -> None: ...
|
| 18 |
+
def update(self, item: bytes) -> None: ...
|
| 19 |
+
def derive(self) -> bytes: ...
|
| 20 |
+
|
| 21 |
+
def HKDF(master: bytes, key_len: int, salt: bytes, hashmod: ModuleType, num_keys: Optional[int]=1, context: Optional[bytes]=None) -> Union[bytes, Tuple[bytes, ...]]: ...
|
| 22 |
+
|
| 23 |
+
def scrypt(password: str, salt: str, key_len: int, N: int, r: int, p: int, num_keys: Optional[int]=1) -> Union[bytes, Tuple[bytes, ...]]: ...
|
| 24 |
+
|
| 25 |
+
def _bcrypt_decode(data: bytes) -> bytes: ...
|
| 26 |
+
def _bcrypt_hash(password:bytes , cost: int, salt: bytes, constant:bytes, invert:bool) -> bytes: ...
|
| 27 |
+
def bcrypt(password: Union[bytes, str], cost: int, salt: Optional[bytes]=None) -> bytes: ...
|
| 28 |
+
def bcrypt_check(password: Union[bytes, str], bcrypt_hash: Union[bytes, bytearray, str]) -> None: ...
|
| 29 |
+
|
| 30 |
+
@overload
|
| 31 |
+
def SP800_108_Counter(master: Buffer,
|
| 32 |
+
key_len: int,
|
| 33 |
+
prf: PRF,
|
| 34 |
+
num_keys: Literal[None] = None,
|
| 35 |
+
label: Buffer = b'', context: Buffer = b'') -> bytes: ...
|
| 36 |
+
|
| 37 |
+
@overload
|
| 38 |
+
def SP800_108_Counter(master: Buffer,
|
| 39 |
+
key_len: int,
|
| 40 |
+
prf: PRF,
|
| 41 |
+
num_keys: int,
|
| 42 |
+
label: Buffer = b'', context: Buffer = b'') -> Tuple[bytes]: ...
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/SecretSharing.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SecretSharing.py : distribute a secret amongst a group of participants
|
| 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.py3compat import is_native_int
|
| 35 |
+
from Crypto.Util import number
|
| 36 |
+
from Crypto.Util.number import long_to_bytes, bytes_to_long
|
| 37 |
+
from Crypto.Random import get_random_bytes as rng
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _mult_gf2(f1, f2):
|
| 41 |
+
"""Multiply two polynomials in GF(2)"""
|
| 42 |
+
|
| 43 |
+
# Ensure f2 is the smallest
|
| 44 |
+
if f2 > f1:
|
| 45 |
+
f1, f2 = f2, f1
|
| 46 |
+
z = 0
|
| 47 |
+
while f2:
|
| 48 |
+
if f2 & 1:
|
| 49 |
+
z ^= f1
|
| 50 |
+
f1 <<= 1
|
| 51 |
+
f2 >>= 1
|
| 52 |
+
return z
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _div_gf2(a, b):
|
| 56 |
+
"""
|
| 57 |
+
Compute division of polynomials over GF(2).
|
| 58 |
+
Given a and b, it finds two polynomials q and r such that:
|
| 59 |
+
|
| 60 |
+
a = b*q + r with deg(r)<deg(b)
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
if (a < b):
|
| 64 |
+
return 0, a
|
| 65 |
+
|
| 66 |
+
deg = number.size
|
| 67 |
+
q = 0
|
| 68 |
+
r = a
|
| 69 |
+
d = deg(b)
|
| 70 |
+
while deg(r) >= d:
|
| 71 |
+
s = 1 << (deg(r) - d)
|
| 72 |
+
q ^= s
|
| 73 |
+
r ^= _mult_gf2(b, s)
|
| 74 |
+
return (q, r)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class _Element(object):
|
| 78 |
+
"""Element of GF(2^128) field"""
|
| 79 |
+
|
| 80 |
+
# The irreducible polynomial defining this field is 1+x+x^2+x^7+x^128
|
| 81 |
+
irr_poly = 1 + 2 + 4 + 128 + 2 ** 128
|
| 82 |
+
|
| 83 |
+
def __init__(self, encoded_value):
|
| 84 |
+
"""Initialize the element to a certain value.
|
| 85 |
+
|
| 86 |
+
The value passed as parameter is internally encoded as
|
| 87 |
+
a 128-bit integer, where each bit represents a polynomial
|
| 88 |
+
coefficient. The LSB is the constant coefficient.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
if is_native_int(encoded_value):
|
| 92 |
+
self._value = encoded_value
|
| 93 |
+
elif len(encoded_value) == 16:
|
| 94 |
+
self._value = bytes_to_long(encoded_value)
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError("The encoded value must be an integer or a 16 byte string")
|
| 97 |
+
|
| 98 |
+
def __eq__(self, other):
|
| 99 |
+
return self._value == other._value
|
| 100 |
+
|
| 101 |
+
def __int__(self):
|
| 102 |
+
"""Return the field element, encoded as a 128-bit integer."""
|
| 103 |
+
return self._value
|
| 104 |
+
|
| 105 |
+
def encode(self):
|
| 106 |
+
"""Return the field element, encoded as a 16 byte string."""
|
| 107 |
+
return long_to_bytes(self._value, 16)
|
| 108 |
+
|
| 109 |
+
def __mul__(self, factor):
|
| 110 |
+
|
| 111 |
+
f1 = self._value
|
| 112 |
+
f2 = factor._value
|
| 113 |
+
|
| 114 |
+
# Make sure that f2 is the smallest, to speed up the loop
|
| 115 |
+
if f2 > f1:
|
| 116 |
+
f1, f2 = f2, f1
|
| 117 |
+
|
| 118 |
+
if self.irr_poly in (f1, f2):
|
| 119 |
+
return _Element(0)
|
| 120 |
+
|
| 121 |
+
mask1 = 2 ** 128
|
| 122 |
+
v, z = f1, 0
|
| 123 |
+
while f2:
|
| 124 |
+
# if f2 ^ 1: z ^= v
|
| 125 |
+
mask2 = int(bin(f2 & 1)[2:] * 128, base=2)
|
| 126 |
+
z = (mask2 & (z ^ v)) | ((mask1 - mask2 - 1) & z)
|
| 127 |
+
v <<= 1
|
| 128 |
+
# if v & mask1: v ^= self.irr_poly
|
| 129 |
+
mask3 = int(bin((v >> 128) & 1)[2:] * 128, base=2)
|
| 130 |
+
v = (mask3 & (v ^ self.irr_poly)) | ((mask1 - mask3 - 1) & v)
|
| 131 |
+
f2 >>= 1
|
| 132 |
+
return _Element(z)
|
| 133 |
+
|
| 134 |
+
def __add__(self, term):
|
| 135 |
+
return _Element(self._value ^ term._value)
|
| 136 |
+
|
| 137 |
+
def inverse(self):
|
| 138 |
+
"""Return the inverse of this element in GF(2^128)."""
|
| 139 |
+
|
| 140 |
+
# We use the Extended GCD algorithm
|
| 141 |
+
# http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor
|
| 142 |
+
|
| 143 |
+
if self._value == 0:
|
| 144 |
+
raise ValueError("Inversion of zero")
|
| 145 |
+
|
| 146 |
+
r0, r1 = self._value, self.irr_poly
|
| 147 |
+
s0, s1 = 1, 0
|
| 148 |
+
while r1 > 0:
|
| 149 |
+
q = _div_gf2(r0, r1)[0]
|
| 150 |
+
r0, r1 = r1, r0 ^ _mult_gf2(q, r1)
|
| 151 |
+
s0, s1 = s1, s0 ^ _mult_gf2(q, s1)
|
| 152 |
+
return _Element(s0)
|
| 153 |
+
|
| 154 |
+
def __pow__(self, exponent):
|
| 155 |
+
result = _Element(self._value)
|
| 156 |
+
for _ in range(exponent - 1):
|
| 157 |
+
result = result * self
|
| 158 |
+
return result
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class Shamir(object):
|
| 162 |
+
"""Shamir's secret sharing scheme.
|
| 163 |
+
|
| 164 |
+
A secret is split into ``n`` shares, and it is sufficient to collect
|
| 165 |
+
``k`` of them to reconstruct the secret.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def split(k, n, secret, ssss=False):
|
| 170 |
+
"""Split a secret into ``n`` shares.
|
| 171 |
+
|
| 172 |
+
The secret can be reconstructed later using just ``k`` shares
|
| 173 |
+
out of the original ``n``.
|
| 174 |
+
Each share must be kept confidential to the person it was
|
| 175 |
+
assigned to.
|
| 176 |
+
|
| 177 |
+
Each share is associated to an index (starting from 1).
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
k (integer):
|
| 181 |
+
The sufficient number of shares to reconstruct the secret (``k < n``).
|
| 182 |
+
n (integer):
|
| 183 |
+
The number of shares that this method will create.
|
| 184 |
+
secret (byte string):
|
| 185 |
+
A byte string of 16 bytes (e.g. the AES 128 key).
|
| 186 |
+
ssss (bool):
|
| 187 |
+
If ``True``, the shares can be used with the ``ssss`` utility.
|
| 188 |
+
Default: ``False``.
|
| 189 |
+
|
| 190 |
+
Return (tuples):
|
| 191 |
+
``n`` tuples. A tuple is meant for each participant and it contains two items:
|
| 192 |
+
|
| 193 |
+
1. the unique index (an integer)
|
| 194 |
+
2. the share (a byte string, 16 bytes)
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
#
|
| 198 |
+
# We create a polynomial with random coefficients in GF(2^128):
|
| 199 |
+
#
|
| 200 |
+
# p(x) = \sum_{i=0}^{k-1} c_i * x^i
|
| 201 |
+
#
|
| 202 |
+
# c_0 is the encoded secret
|
| 203 |
+
#
|
| 204 |
+
|
| 205 |
+
coeffs = [_Element(rng(16)) for i in range(k - 1)]
|
| 206 |
+
coeffs.append(_Element(secret))
|
| 207 |
+
|
| 208 |
+
# Each share is y_i = p(x_i) where x_i is the public index
|
| 209 |
+
# associated to each of the n users.
|
| 210 |
+
|
| 211 |
+
def make_share(user, coeffs, ssss):
|
| 212 |
+
idx = _Element(user)
|
| 213 |
+
share = _Element(0)
|
| 214 |
+
for coeff in coeffs:
|
| 215 |
+
share = idx * share + coeff
|
| 216 |
+
if ssss:
|
| 217 |
+
share += _Element(user) ** len(coeffs)
|
| 218 |
+
return share.encode()
|
| 219 |
+
|
| 220 |
+
return [(i, make_share(i, coeffs, ssss)) for i in range(1, n + 1)]
|
| 221 |
+
|
| 222 |
+
@staticmethod
|
| 223 |
+
def combine(shares, ssss=False):
|
| 224 |
+
"""Recombine a secret, if enough shares are presented.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
shares (tuples):
|
| 228 |
+
The *k* tuples, each containin the index (an integer) and
|
| 229 |
+
the share (a byte string, 16 bytes long) that were assigned to
|
| 230 |
+
a participant.
|
| 231 |
+
ssss (bool):
|
| 232 |
+
If ``True``, the shares were produced by the ``ssss`` utility.
|
| 233 |
+
Default: ``False``.
|
| 234 |
+
|
| 235 |
+
Return:
|
| 236 |
+
The original secret, as a byte string (16 bytes long).
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
#
|
| 240 |
+
# Given k points (x,y), the interpolation polynomial of degree k-1 is:
|
| 241 |
+
#
|
| 242 |
+
# L(x) = \sum_{j=0}^{k-1} y_i * l_j(x)
|
| 243 |
+
#
|
| 244 |
+
# where:
|
| 245 |
+
#
|
| 246 |
+
# l_j(x) = \prod_{ \overset{0 \le m \le k-1}{m \ne j} }
|
| 247 |
+
# \frac{x - x_m}{x_j - x_m}
|
| 248 |
+
#
|
| 249 |
+
# However, in this case we are purely interested in the constant
|
| 250 |
+
# coefficient of L(x).
|
| 251 |
+
#
|
| 252 |
+
|
| 253 |
+
k = len(shares)
|
| 254 |
+
|
| 255 |
+
gf_shares = []
|
| 256 |
+
for x in shares:
|
| 257 |
+
idx = _Element(x[0])
|
| 258 |
+
value = _Element(x[1])
|
| 259 |
+
if any(y[0] == idx for y in gf_shares):
|
| 260 |
+
raise ValueError("Duplicate share")
|
| 261 |
+
if ssss:
|
| 262 |
+
value += idx ** k
|
| 263 |
+
gf_shares.append((idx, value))
|
| 264 |
+
|
| 265 |
+
result = _Element(0)
|
| 266 |
+
for j in range(k):
|
| 267 |
+
x_j, y_j = gf_shares[j]
|
| 268 |
+
|
| 269 |
+
numerator = _Element(1)
|
| 270 |
+
denominator = _Element(1)
|
| 271 |
+
|
| 272 |
+
for m in range(k):
|
| 273 |
+
x_m = gf_shares[m][0]
|
| 274 |
+
if m != j:
|
| 275 |
+
numerator *= x_m
|
| 276 |
+
denominator *= x_j + x_m
|
| 277 |
+
result += y_j * numerator * denominator.inverse()
|
| 278 |
+
return result.encode()
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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__ = ['KDF', 'SecretSharing', 'DH']
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__init__.pyi
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__all__ = ['KDF.pyi', 'SecretSharing.pyi']
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/DH.cpython-310.pyc
ADDED
|
Binary file (4.85 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/KDF.cpython-310.pyc
ADDED
|
Binary file (20.4 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/SecretSharing.cpython-310.pyc
ADDED
|
Binary file (6.76 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (209 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Protocol/_scrypt.abi3.so
ADDED
|
Binary file (26.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Random/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# Random/__init__.py : PyCrypto random number generation
|
| 4 |
+
#
|
| 5 |
+
# ===================================================================
|
| 6 |
+
# The contents of this file are dedicated to the public domain. To
|
| 7 |
+
# the extent that dedication to the public domain is not available,
|
| 8 |
+
# everyone is granted a worldwide, perpetual, royalty-free,
|
| 9 |
+
# non-exclusive license to exercise all rights associated with the
|
| 10 |
+
# contents of this file for any purpose whatsoever.
|
| 11 |
+
# No rights are reserved.
|
| 12 |
+
#
|
| 13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 14 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 15 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 16 |
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
| 17 |
+
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
| 18 |
+
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 19 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
# SOFTWARE.
|
| 21 |
+
# ===================================================================
|
| 22 |
+
|
| 23 |
+
__all__ = ['new', 'get_random_bytes']
|
| 24 |
+
|
| 25 |
+
from os import urandom
|
| 26 |
+
|
| 27 |
+
class _UrandomRNG(object):
|
| 28 |
+
|
| 29 |
+
def read(self, n):
|
| 30 |
+
"""Return a random byte string of the desired size."""
|
| 31 |
+
return urandom(n)
|
| 32 |
+
|
| 33 |
+
def flush(self):
|
| 34 |
+
"""Method provided for backward compatibility only."""
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
def reinit(self):
|
| 38 |
+
"""Method provided for backward compatibility only."""
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
def close(self):
|
| 42 |
+
"""Method provided for backward compatibility only."""
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def new(*args, **kwargs):
|
| 47 |
+
"""Return a file-like object that outputs cryptographically random bytes."""
|
| 48 |
+
return _UrandomRNG()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def atfork():
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
#: Function that returns a random byte string of the desired size.
|
| 56 |
+
get_random_bytes = urandom
|
| 57 |
+
|
minigpt2/lib/python3.10/site-packages/Crypto/Random/__init__.pyi
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
__all__ = ['new', 'get_random_bytes']
|
| 4 |
+
|
| 5 |
+
from os import urandom
|
| 6 |
+
|
| 7 |
+
class _UrandomRNG(object):
|
| 8 |
+
|
| 9 |
+
def read(self, n: int) -> bytes:...
|
| 10 |
+
def flush(self) -> None: ...
|
| 11 |
+
def reinit(self) -> None: ...
|
| 12 |
+
def close(self) -> None: ...
|
| 13 |
+
|
| 14 |
+
def new(*args: Any, **kwargs: Any) -> _UrandomRNG: ...
|
| 15 |
+
|
| 16 |
+
def atfork() -> None: ...
|
| 17 |
+
|
| 18 |
+
get_random_bytes = urandom
|
| 19 |
+
|
minigpt2/lib/python3.10/site-packages/Crypto/Random/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.26 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Random/__pycache__/random.cpython-310.pyc
ADDED
|
Binary file (3.4 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/Random/random.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# Random/random.py : Strong alternative for the standard 'random' module
|
| 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 |
+
__all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample']
|
| 26 |
+
|
| 27 |
+
from Crypto import Random
|
| 28 |
+
|
| 29 |
+
from Crypto.Util.py3compat import is_native_int
|
| 30 |
+
|
| 31 |
+
class StrongRandom(object):
|
| 32 |
+
def __init__(self, rng=None, randfunc=None):
|
| 33 |
+
if randfunc is None and rng is None:
|
| 34 |
+
self._randfunc = None
|
| 35 |
+
elif randfunc is not None and rng is None:
|
| 36 |
+
self._randfunc = randfunc
|
| 37 |
+
elif randfunc is None and rng is not None:
|
| 38 |
+
self._randfunc = rng.read
|
| 39 |
+
else:
|
| 40 |
+
raise ValueError("Cannot specify both 'rng' and 'randfunc'")
|
| 41 |
+
|
| 42 |
+
def getrandbits(self, k):
|
| 43 |
+
"""Return an integer with k random bits."""
|
| 44 |
+
|
| 45 |
+
if self._randfunc is None:
|
| 46 |
+
self._randfunc = Random.new().read
|
| 47 |
+
mask = (1 << k) - 1
|
| 48 |
+
return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
|
| 49 |
+
|
| 50 |
+
def randrange(self, *args):
|
| 51 |
+
"""randrange([start,] stop[, step]):
|
| 52 |
+
Return a randomly-selected element from range(start, stop, step)."""
|
| 53 |
+
if len(args) == 3:
|
| 54 |
+
(start, stop, step) = args
|
| 55 |
+
elif len(args) == 2:
|
| 56 |
+
(start, stop) = args
|
| 57 |
+
step = 1
|
| 58 |
+
elif len(args) == 1:
|
| 59 |
+
(stop,) = args
|
| 60 |
+
start = 0
|
| 61 |
+
step = 1
|
| 62 |
+
else:
|
| 63 |
+
raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),))
|
| 64 |
+
if (not is_native_int(start) or not is_native_int(stop) or not
|
| 65 |
+
is_native_int(step)):
|
| 66 |
+
raise TypeError("randrange requires integer arguments")
|
| 67 |
+
if step == 0:
|
| 68 |
+
raise ValueError("randrange step argument must not be zero")
|
| 69 |
+
|
| 70 |
+
num_choices = ceil_div(stop - start, step)
|
| 71 |
+
if num_choices < 0:
|
| 72 |
+
num_choices = 0
|
| 73 |
+
if num_choices < 1:
|
| 74 |
+
raise ValueError("empty range for randrange(%r, %r, %r)" % (start, stop, step))
|
| 75 |
+
|
| 76 |
+
# Pick a random number in the range of possible numbers
|
| 77 |
+
r = num_choices
|
| 78 |
+
while r >= num_choices:
|
| 79 |
+
r = self.getrandbits(size(num_choices))
|
| 80 |
+
|
| 81 |
+
return start + (step * r)
|
| 82 |
+
|
| 83 |
+
def randint(self, a, b):
|
| 84 |
+
"""Return a random integer N such that a <= N <= b."""
|
| 85 |
+
if not is_native_int(a) or not is_native_int(b):
|
| 86 |
+
raise TypeError("randint requires integer arguments")
|
| 87 |
+
N = self.randrange(a, b+1)
|
| 88 |
+
assert a <= N <= b
|
| 89 |
+
return N
|
| 90 |
+
|
| 91 |
+
def choice(self, seq):
|
| 92 |
+
"""Return a random element from a (non-empty) sequence.
|
| 93 |
+
|
| 94 |
+
If the seqence is empty, raises IndexError.
|
| 95 |
+
"""
|
| 96 |
+
if len(seq) == 0:
|
| 97 |
+
raise IndexError("empty sequence")
|
| 98 |
+
return seq[self.randrange(len(seq))]
|
| 99 |
+
|
| 100 |
+
def shuffle(self, x):
|
| 101 |
+
"""Shuffle the sequence in place."""
|
| 102 |
+
# Fisher-Yates shuffle. O(n)
|
| 103 |
+
# See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
|
| 104 |
+
# Working backwards from the end of the array, we choose a random item
|
| 105 |
+
# from the remaining items until all items have been chosen.
|
| 106 |
+
for i in range(len(x)-1, 0, -1): # iterate from len(x)-1 downto 1
|
| 107 |
+
j = self.randrange(0, i+1) # choose random j such that 0 <= j <= i
|
| 108 |
+
x[i], x[j] = x[j], x[i] # exchange x[i] and x[j]
|
| 109 |
+
|
| 110 |
+
def sample(self, population, k):
|
| 111 |
+
"""Return a k-length list of unique elements chosen from the population sequence."""
|
| 112 |
+
|
| 113 |
+
num_choices = len(population)
|
| 114 |
+
if k > num_choices:
|
| 115 |
+
raise ValueError("sample larger than population")
|
| 116 |
+
|
| 117 |
+
retval = []
|
| 118 |
+
selected = {} # we emulate a set using a dict here
|
| 119 |
+
for i in range(k):
|
| 120 |
+
r = None
|
| 121 |
+
while r is None or r in selected:
|
| 122 |
+
r = self.randrange(num_choices)
|
| 123 |
+
retval.append(population[r])
|
| 124 |
+
selected[r] = 1
|
| 125 |
+
return retval
|
| 126 |
+
|
| 127 |
+
_r = StrongRandom()
|
| 128 |
+
getrandbits = _r.getrandbits
|
| 129 |
+
randrange = _r.randrange
|
| 130 |
+
randint = _r.randint
|
| 131 |
+
choice = _r.choice
|
| 132 |
+
shuffle = _r.shuffle
|
| 133 |
+
sample = _r.sample
|
| 134 |
+
|
| 135 |
+
# These are at the bottom to avoid problems with recursive imports
|
| 136 |
+
from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes, size
|
| 137 |
+
|
| 138 |
+
# vim:set ts=4 sw=4 sts=4 expandtab:
|
minigpt2/lib/python3.10/site-packages/Crypto/Random/random.pyi
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Tuple, Union, Sequence, Any, Optional, TypeVar
|
| 2 |
+
|
| 3 |
+
__all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample']
|
| 4 |
+
|
| 5 |
+
T = TypeVar('T')
|
| 6 |
+
|
| 7 |
+
class StrongRandom(object):
|
| 8 |
+
def __init__(self, rng: Optional[Any]=None, randfunc: Optional[Callable]=None) -> None: ... # TODO What is rng?
|
| 9 |
+
def getrandbits(self, k: int) -> int: ...
|
| 10 |
+
def randrange(self, start: int, stop: int = ..., step: int = ...) -> int: ...
|
| 11 |
+
def randint(self, a: int, b: int) -> int: ...
|
| 12 |
+
def choice(self, seq: Sequence[T]) -> T: ...
|
| 13 |
+
def shuffle(self, x: Sequence) -> None: ...
|
| 14 |
+
def sample(self, population: Sequence, k: int) -> list: ...
|
| 15 |
+
|
| 16 |
+
_r = StrongRandom()
|
| 17 |
+
getrandbits = _r.getrandbits
|
| 18 |
+
randrange = _r.randrange
|
| 19 |
+
randint = _r.randint
|
| 20 |
+
choice = _r.choice
|
| 21 |
+
shuffle = _r.shuffle
|
| 22 |
+
sample = _r.sample
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/IO/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SelfTest/IO/__init__.py: Self-test for input/output module
|
| 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 |
+
"""Self-test for I/O"""
|
| 35 |
+
|
| 36 |
+
def get_tests(config={}):
|
| 37 |
+
tests = []
|
| 38 |
+
from Crypto.SelfTest.IO import test_PKCS8; tests += test_PKCS8.get_tests(config=config)
|
| 39 |
+
from Crypto.SelfTest.IO import test_PBES; tests += test_PBES.get_tests(config=config)
|
| 40 |
+
return tests
|
| 41 |
+
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
import unittest
|
| 44 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 45 |
+
unittest.main(defaultTest='suite')
|
| 46 |
+
|
| 47 |
+
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/IO/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (700 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/IO/__pycache__/test_PKCS8.cpython-310.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SelfTest/Math/__init__.py: Self-test for math module
|
| 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 |
+
"""Self-test for Math"""
|
| 35 |
+
|
| 36 |
+
def get_tests(config={}):
|
| 37 |
+
tests = []
|
| 38 |
+
from Crypto.SelfTest.Math import test_Numbers
|
| 39 |
+
from Crypto.SelfTest.Math import test_Primality
|
| 40 |
+
from Crypto.SelfTest.Math import test_modexp
|
| 41 |
+
from Crypto.SelfTest.Math import test_modmult
|
| 42 |
+
tests += test_Numbers.get_tests(config=config)
|
| 43 |
+
tests += test_Primality.get_tests(config=config)
|
| 44 |
+
tests += test_modexp.get_tests(config=config)
|
| 45 |
+
tests += test_modmult.get_tests(config=config)
|
| 46 |
+
return tests
|
| 47 |
+
|
| 48 |
+
if __name__ == '__main__':
|
| 49 |
+
import unittest
|
| 50 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 51 |
+
unittest.main(defaultTest='suite')
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (831 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_Numbers.cpython-310.pyc
ADDED
|
Binary file (28.6 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_Primality.cpython-310.pyc
ADDED
|
Binary file (3.6 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_modexp.cpython-310.pyc
ADDED
|
Binary file (5.87 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/__pycache__/test_modmult.cpython-310.pyc
ADDED
|
Binary file (3.24 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_Numbers.py
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SelfTest/Math/test_Numbers.py: Self-test for Numbers module
|
| 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 |
+
"""Self-test for Math.Numbers"""
|
| 35 |
+
|
| 36 |
+
import sys
|
| 37 |
+
import unittest
|
| 38 |
+
|
| 39 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 40 |
+
|
| 41 |
+
from Crypto.Util.py3compat import *
|
| 42 |
+
|
| 43 |
+
from Crypto.Math._IntegerNative import IntegerNative
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestIntegerBase(unittest.TestCase):
|
| 47 |
+
|
| 48 |
+
def setUp(self):
|
| 49 |
+
raise NotImplementedError("To be implemented")
|
| 50 |
+
|
| 51 |
+
def Integers(self, *arg):
|
| 52 |
+
return map(self.Integer, arg)
|
| 53 |
+
|
| 54 |
+
def test_init_and_equality(self):
|
| 55 |
+
Integer = self.Integer
|
| 56 |
+
|
| 57 |
+
v1 = Integer(23)
|
| 58 |
+
v2 = Integer(v1)
|
| 59 |
+
v3 = Integer(-9)
|
| 60 |
+
self.assertRaises(ValueError, Integer, 1.0)
|
| 61 |
+
|
| 62 |
+
v4 = Integer(10**10)
|
| 63 |
+
v5 = Integer(-10**10)
|
| 64 |
+
|
| 65 |
+
v6 = Integer(0xFFFF)
|
| 66 |
+
v7 = Integer(0xFFFFFFFF)
|
| 67 |
+
v8 = Integer(0xFFFFFFFFFFFFFFFF)
|
| 68 |
+
|
| 69 |
+
self.assertEqual(v1, v1)
|
| 70 |
+
self.assertEqual(v1, 23)
|
| 71 |
+
self.assertEqual(v1, v2)
|
| 72 |
+
self.assertEqual(v3, -9)
|
| 73 |
+
self.assertEqual(v4, 10 ** 10)
|
| 74 |
+
self.assertEqual(v5, -10 ** 10)
|
| 75 |
+
self.assertEqual(v6, 0xFFFF)
|
| 76 |
+
self.assertEqual(v7, 0xFFFFFFFF)
|
| 77 |
+
self.assertEqual(v8, 0xFFFFFFFFFFFFFFFF)
|
| 78 |
+
|
| 79 |
+
self.assertFalse(v1 == v4)
|
| 80 |
+
|
| 81 |
+
# Init and comparison between Integer's
|
| 82 |
+
v6 = Integer(v1)
|
| 83 |
+
self.assertEqual(v1, v6)
|
| 84 |
+
|
| 85 |
+
self.assertFalse(Integer(0) == None)
|
| 86 |
+
|
| 87 |
+
def test_conversion_to_int(self):
|
| 88 |
+
v1, v2 = self.Integers(-23, 2 ** 1000)
|
| 89 |
+
self.assertEqual(int(v1), -23)
|
| 90 |
+
self.assertEqual(int(v2), 2 ** 1000)
|
| 91 |
+
|
| 92 |
+
def test_equality_with_ints(self):
|
| 93 |
+
v1, v2, v3 = self.Integers(23, -89, 2 ** 1000)
|
| 94 |
+
self.assertTrue(v1 == 23)
|
| 95 |
+
self.assertTrue(v2 == -89)
|
| 96 |
+
self.assertFalse(v1 == 24)
|
| 97 |
+
self.assertTrue(v3 == 2 ** 1000)
|
| 98 |
+
|
| 99 |
+
def test_conversion_to_str(self):
|
| 100 |
+
v1, v2, v3, v4 = self.Integers(20, 0, -20, 2 ** 1000)
|
| 101 |
+
self.assertTrue(str(v1) == "20")
|
| 102 |
+
self.assertTrue(str(v2) == "0")
|
| 103 |
+
self.assertTrue(str(v3) == "-20")
|
| 104 |
+
self.assertTrue(str(v4) == "10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376")
|
| 105 |
+
|
| 106 |
+
def test_repr(self):
|
| 107 |
+
v1, v2 = self.Integers(-1, 2**80)
|
| 108 |
+
self.assertEqual(repr(v1), "Integer(-1)")
|
| 109 |
+
self.assertEqual(repr(v2), "Integer(1208925819614629174706176)")
|
| 110 |
+
|
| 111 |
+
def test_conversion_to_bytes(self):
|
| 112 |
+
Integer = self.Integer
|
| 113 |
+
|
| 114 |
+
v0 = Integer(0)
|
| 115 |
+
self.assertEqual(b"\x00", v0.to_bytes())
|
| 116 |
+
|
| 117 |
+
v1 = Integer(0x17)
|
| 118 |
+
self.assertEqual(b"\x17", v1.to_bytes())
|
| 119 |
+
|
| 120 |
+
v2 = Integer(0xFFFE)
|
| 121 |
+
self.assertEqual(b"\xFF\xFE", v2.to_bytes())
|
| 122 |
+
self.assertEqual(b"\x00\xFF\xFE", v2.to_bytes(3))
|
| 123 |
+
self.assertRaises(ValueError, v2.to_bytes, 1)
|
| 124 |
+
|
| 125 |
+
self.assertEqual(b"\xFE\xFF", v2.to_bytes(byteorder='little'))
|
| 126 |
+
self.assertEqual(b"\xFE\xFF\x00", v2.to_bytes(3, byteorder='little'))
|
| 127 |
+
|
| 128 |
+
v3 = Integer(0xFF00AABBCCDDEE1122)
|
| 129 |
+
self.assertEqual(b"\xFF\x00\xAA\xBB\xCC\xDD\xEE\x11\x22", v3.to_bytes())
|
| 130 |
+
self.assertEqual(b"\x22\x11\xEE\xDD\xCC\xBB\xAA\x00\xFF",
|
| 131 |
+
v3.to_bytes(byteorder='little'))
|
| 132 |
+
self.assertEqual(b"\x00\xFF\x00\xAA\xBB\xCC\xDD\xEE\x11\x22",
|
| 133 |
+
v3.to_bytes(10))
|
| 134 |
+
self.assertEqual(b"\x22\x11\xEE\xDD\xCC\xBB\xAA\x00\xFF\x00",
|
| 135 |
+
v3.to_bytes(10, byteorder='little'))
|
| 136 |
+
self.assertRaises(ValueError, v3.to_bytes, 8)
|
| 137 |
+
|
| 138 |
+
v4 = Integer(-90)
|
| 139 |
+
self.assertRaises(ValueError, v4.to_bytes)
|
| 140 |
+
self.assertRaises(ValueError, v4.to_bytes, byteorder='bittle')
|
| 141 |
+
|
| 142 |
+
def test_conversion_from_bytes(self):
|
| 143 |
+
Integer = self.Integer
|
| 144 |
+
|
| 145 |
+
v1 = Integer.from_bytes(b"\x00")
|
| 146 |
+
self.assertTrue(isinstance(v1, Integer))
|
| 147 |
+
self.assertEqual(0, v1)
|
| 148 |
+
|
| 149 |
+
v2 = Integer.from_bytes(b"\x00\x01")
|
| 150 |
+
self.assertEqual(1, v2)
|
| 151 |
+
|
| 152 |
+
v3 = Integer.from_bytes(b"\xFF\xFF")
|
| 153 |
+
self.assertEqual(0xFFFF, v3)
|
| 154 |
+
|
| 155 |
+
v4 = Integer.from_bytes(b"\x00\x01", 'big')
|
| 156 |
+
self.assertEqual(1, v4)
|
| 157 |
+
|
| 158 |
+
v5 = Integer.from_bytes(b"\x00\x01", byteorder='big')
|
| 159 |
+
self.assertEqual(1, v5)
|
| 160 |
+
|
| 161 |
+
v6 = Integer.from_bytes(b"\x00\x01", byteorder='little')
|
| 162 |
+
self.assertEqual(0x0100, v6)
|
| 163 |
+
|
| 164 |
+
self.assertRaises(ValueError, Integer.from_bytes, b'\x09', 'bittle')
|
| 165 |
+
|
| 166 |
+
def test_inequality(self):
|
| 167 |
+
# Test Integer!=Integer and Integer!=int
|
| 168 |
+
v1, v2, v3, v4 = self.Integers(89, 89, 90, -8)
|
| 169 |
+
self.assertTrue(v1 != v3)
|
| 170 |
+
self.assertTrue(v1 != 90)
|
| 171 |
+
self.assertFalse(v1 != v2)
|
| 172 |
+
self.assertFalse(v1 != 89)
|
| 173 |
+
self.assertTrue(v1 != v4)
|
| 174 |
+
self.assertTrue(v4 != v1)
|
| 175 |
+
self.assertTrue(self.Integer(0) != None)
|
| 176 |
+
|
| 177 |
+
def test_less_than(self):
|
| 178 |
+
# Test Integer<Integer and Integer<int
|
| 179 |
+
v1, v2, v3, v4, v5 = self.Integers(13, 13, 14, -8, 2 ** 10)
|
| 180 |
+
self.assertTrue(v1 < v3)
|
| 181 |
+
self.assertTrue(v1 < 14)
|
| 182 |
+
self.assertFalse(v1 < v2)
|
| 183 |
+
self.assertFalse(v1 < 13)
|
| 184 |
+
self.assertTrue(v4 < v1)
|
| 185 |
+
self.assertFalse(v1 < v4)
|
| 186 |
+
self.assertTrue(v1 < v5)
|
| 187 |
+
self.assertFalse(v5 < v1)
|
| 188 |
+
|
| 189 |
+
def test_less_than_or_equal(self):
|
| 190 |
+
# Test Integer<=Integer and Integer<=int
|
| 191 |
+
v1, v2, v3, v4, v5 = self.Integers(13, 13, 14, -4, 2 ** 10)
|
| 192 |
+
self.assertTrue(v1 <= v1)
|
| 193 |
+
self.assertTrue(v1 <= 13)
|
| 194 |
+
self.assertTrue(v1 <= v2)
|
| 195 |
+
self.assertTrue(v1 <= 14)
|
| 196 |
+
self.assertTrue(v1 <= v3)
|
| 197 |
+
self.assertFalse(v1 <= v4)
|
| 198 |
+
self.assertTrue(v1 <= v5)
|
| 199 |
+
self.assertFalse(v5 <= v1)
|
| 200 |
+
|
| 201 |
+
def test_more_than(self):
|
| 202 |
+
# Test Integer>Integer and Integer>int
|
| 203 |
+
v1, v2, v3, v4, v5 = self.Integers(13, 13, 14, -8, 2 ** 10)
|
| 204 |
+
self.assertTrue(v3 > v1)
|
| 205 |
+
self.assertTrue(v3 > 13)
|
| 206 |
+
self.assertFalse(v1 > v1)
|
| 207 |
+
self.assertFalse(v1 > v2)
|
| 208 |
+
self.assertFalse(v1 > 13)
|
| 209 |
+
self.assertTrue(v1 > v4)
|
| 210 |
+
self.assertFalse(v4 > v1)
|
| 211 |
+
self.assertTrue(v5 > v1)
|
| 212 |
+
self.assertFalse(v1 > v5)
|
| 213 |
+
|
| 214 |
+
def test_more_than_or_equal(self):
|
| 215 |
+
# Test Integer>=Integer and Integer>=int
|
| 216 |
+
v1, v2, v3, v4 = self.Integers(13, 13, 14, -4)
|
| 217 |
+
self.assertTrue(v3 >= v1)
|
| 218 |
+
self.assertTrue(v3 >= 13)
|
| 219 |
+
self.assertTrue(v1 >= v2)
|
| 220 |
+
self.assertTrue(v1 >= v1)
|
| 221 |
+
self.assertTrue(v1 >= 13)
|
| 222 |
+
self.assertFalse(v4 >= v1)
|
| 223 |
+
|
| 224 |
+
def test_bool(self):
|
| 225 |
+
v1, v2, v3, v4 = self.Integers(0, 10, -9, 2 ** 10)
|
| 226 |
+
self.assertFalse(v1)
|
| 227 |
+
self.assertFalse(bool(v1))
|
| 228 |
+
self.assertTrue(v2)
|
| 229 |
+
self.assertTrue(bool(v2))
|
| 230 |
+
self.assertTrue(v3)
|
| 231 |
+
self.assertTrue(v4)
|
| 232 |
+
|
| 233 |
+
def test_is_negative(self):
|
| 234 |
+
v1, v2, v3, v4, v5 = self.Integers(-3 ** 100, -3, 0, 3, 3**100)
|
| 235 |
+
self.assertTrue(v1.is_negative())
|
| 236 |
+
self.assertTrue(v2.is_negative())
|
| 237 |
+
self.assertFalse(v4.is_negative())
|
| 238 |
+
self.assertFalse(v5.is_negative())
|
| 239 |
+
|
| 240 |
+
def test_addition(self):
|
| 241 |
+
# Test Integer+Integer and Integer+int
|
| 242 |
+
v1, v2, v3 = self.Integers(7, 90, -7)
|
| 243 |
+
self.assertTrue(isinstance(v1 + v2, self.Integer))
|
| 244 |
+
self.assertEqual(v1 + v2, 97)
|
| 245 |
+
self.assertEqual(v1 + 90, 97)
|
| 246 |
+
self.assertEqual(v1 + v3, 0)
|
| 247 |
+
self.assertEqual(v1 + (-7), 0)
|
| 248 |
+
self.assertEqual(v1 + 2 ** 10, 2 ** 10 + 7)
|
| 249 |
+
|
| 250 |
+
def test_subtraction(self):
|
| 251 |
+
# Test Integer-Integer and Integer-int
|
| 252 |
+
v1, v2, v3 = self.Integers(7, 90, -7)
|
| 253 |
+
self.assertTrue(isinstance(v1 - v2, self.Integer))
|
| 254 |
+
self.assertEqual(v2 - v1, 83)
|
| 255 |
+
self.assertEqual(v2 - 7, 83)
|
| 256 |
+
self.assertEqual(v2 - v3, 97)
|
| 257 |
+
self.assertEqual(v1 - (-7), 14)
|
| 258 |
+
self.assertEqual(v1 - 2 ** 10, 7 - 2 ** 10)
|
| 259 |
+
|
| 260 |
+
def test_multiplication(self):
|
| 261 |
+
# Test Integer-Integer and Integer-int
|
| 262 |
+
v1, v2, v3, v4 = self.Integers(4, 5, -2, 2 ** 10)
|
| 263 |
+
self.assertTrue(isinstance(v1 * v2, self.Integer))
|
| 264 |
+
self.assertEqual(v1 * v2, 20)
|
| 265 |
+
self.assertEqual(v1 * 5, 20)
|
| 266 |
+
self.assertEqual(v1 * -2, -8)
|
| 267 |
+
self.assertEqual(v1 * 2 ** 10, 4 * (2 ** 10))
|
| 268 |
+
|
| 269 |
+
def test_floor_div(self):
|
| 270 |
+
v1, v2, v3 = self.Integers(3, 8, 2 ** 80)
|
| 271 |
+
self.assertTrue(isinstance(v1 // v2, self.Integer))
|
| 272 |
+
self.assertEqual(v2 // v1, 2)
|
| 273 |
+
self.assertEqual(v2 // 3, 2)
|
| 274 |
+
self.assertEqual(v2 // -3, -3)
|
| 275 |
+
self.assertEqual(v3 // 2 ** 79, 2)
|
| 276 |
+
self.assertRaises(ZeroDivisionError, lambda: v1 // 0)
|
| 277 |
+
|
| 278 |
+
def test_remainder(self):
|
| 279 |
+
# Test Integer%Integer and Integer%int
|
| 280 |
+
v1, v2, v3 = self.Integers(23, 5, -4)
|
| 281 |
+
self.assertTrue(isinstance(v1 % v2, self.Integer))
|
| 282 |
+
self.assertEqual(v1 % v2, 3)
|
| 283 |
+
self.assertEqual(v1 % 5, 3)
|
| 284 |
+
self.assertEqual(v3 % 5, 1)
|
| 285 |
+
self.assertEqual(v1 % 2 ** 10, 23)
|
| 286 |
+
self.assertRaises(ZeroDivisionError, lambda: v1 % 0)
|
| 287 |
+
self.assertRaises(ValueError, lambda: v1 % -6)
|
| 288 |
+
|
| 289 |
+
def test_simple_exponentiation(self):
|
| 290 |
+
v1, v2, v3 = self.Integers(4, 3, -2)
|
| 291 |
+
self.assertTrue(isinstance(v1 ** v2, self.Integer))
|
| 292 |
+
self.assertEqual(v1 ** v2, 64)
|
| 293 |
+
self.assertEqual(pow(v1, v2), 64)
|
| 294 |
+
self.assertEqual(v1 ** 3, 64)
|
| 295 |
+
self.assertEqual(pow(v1, 3), 64)
|
| 296 |
+
self.assertEqual(v3 ** 2, 4)
|
| 297 |
+
self.assertEqual(v3 ** 3, -8)
|
| 298 |
+
|
| 299 |
+
self.assertRaises(ValueError, pow, v1, -3)
|
| 300 |
+
|
| 301 |
+
def test_modular_exponentiation(self):
|
| 302 |
+
v1, v2, v3 = self.Integers(23, 5, 17)
|
| 303 |
+
|
| 304 |
+
self.assertTrue(isinstance(pow(v1, v2, v3), self.Integer))
|
| 305 |
+
self.assertEqual(pow(v1, v2, v3), 7)
|
| 306 |
+
self.assertEqual(pow(v1, 5, v3), 7)
|
| 307 |
+
self.assertEqual(pow(v1, v2, 17), 7)
|
| 308 |
+
self.assertEqual(pow(v1, 5, 17), 7)
|
| 309 |
+
self.assertEqual(pow(v1, 0, 17), 1)
|
| 310 |
+
self.assertEqual(pow(v1, 1, 2 ** 80), 23)
|
| 311 |
+
self.assertEqual(pow(v1, 2 ** 80, 89298), 17689)
|
| 312 |
+
|
| 313 |
+
self.assertRaises(ZeroDivisionError, pow, v1, 5, 0)
|
| 314 |
+
self.assertRaises(ValueError, pow, v1, 5, -4)
|
| 315 |
+
self.assertRaises(ValueError, pow, v1, -3, 8)
|
| 316 |
+
|
| 317 |
+
def test_inplace_exponentiation(self):
|
| 318 |
+
v1 = self.Integer(4)
|
| 319 |
+
v1.inplace_pow(2)
|
| 320 |
+
self.assertEqual(v1, 16)
|
| 321 |
+
|
| 322 |
+
v1 = self.Integer(4)
|
| 323 |
+
v1.inplace_pow(2, 15)
|
| 324 |
+
self.assertEqual(v1, 1)
|
| 325 |
+
|
| 326 |
+
def test_abs(self):
|
| 327 |
+
v1, v2, v3, v4, v5 = self.Integers(-2 ** 100, -2, 0, 2, 2 ** 100)
|
| 328 |
+
self.assertEqual(abs(v1), 2 ** 100)
|
| 329 |
+
self.assertEqual(abs(v2), 2)
|
| 330 |
+
self.assertEqual(abs(v3), 0)
|
| 331 |
+
self.assertEqual(abs(v4), 2)
|
| 332 |
+
self.assertEqual(abs(v5), 2 ** 100)
|
| 333 |
+
|
| 334 |
+
def test_sqrt(self):
|
| 335 |
+
v1, v2, v3, v4 = self.Integers(-2, 0, 49, 10**100)
|
| 336 |
+
|
| 337 |
+
self.assertRaises(ValueError, v1.sqrt)
|
| 338 |
+
self.assertEqual(v2.sqrt(), 0)
|
| 339 |
+
self.assertEqual(v3.sqrt(), 7)
|
| 340 |
+
self.assertEqual(v4.sqrt(), 10**50)
|
| 341 |
+
|
| 342 |
+
def test_sqrt_module(self):
|
| 343 |
+
|
| 344 |
+
# Invalid modulus (non positive)
|
| 345 |
+
self.assertRaises(ValueError, self.Integer(5).sqrt, 0)
|
| 346 |
+
self.assertRaises(ValueError, self.Integer(5).sqrt, -1)
|
| 347 |
+
|
| 348 |
+
# Simple cases
|
| 349 |
+
assert self.Integer(0).sqrt(5) == 0
|
| 350 |
+
assert self.Integer(1).sqrt(5) in (1, 4)
|
| 351 |
+
|
| 352 |
+
# Test with all quadratic residues in several fields
|
| 353 |
+
for p in (11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53):
|
| 354 |
+
for i in range(0, p):
|
| 355 |
+
square = i**2 % p
|
| 356 |
+
res = self.Integer(square).sqrt(p)
|
| 357 |
+
assert res in (i, p - i)
|
| 358 |
+
|
| 359 |
+
# 2 is a non-quadratic reside in Z_11
|
| 360 |
+
self.assertRaises(ValueError, self.Integer(2).sqrt, 11)
|
| 361 |
+
|
| 362 |
+
# 10 is not a prime
|
| 363 |
+
self.assertRaises(ValueError, self.Integer(4).sqrt, 10)
|
| 364 |
+
|
| 365 |
+
# 5 is square residue of 4 and 7
|
| 366 |
+
assert self.Integer(5 - 11).sqrt(11) in (4, 7)
|
| 367 |
+
assert self.Integer(5 + 11).sqrt(11) in (4, 7)
|
| 368 |
+
|
| 369 |
+
def test_in_place_add(self):
|
| 370 |
+
v1, v2 = self.Integers(10, 20)
|
| 371 |
+
|
| 372 |
+
v1 += v2
|
| 373 |
+
self.assertEqual(v1, 30)
|
| 374 |
+
v1 += 10
|
| 375 |
+
self.assertEqual(v1, 40)
|
| 376 |
+
v1 += -1
|
| 377 |
+
self.assertEqual(v1, 39)
|
| 378 |
+
v1 += 2 ** 1000
|
| 379 |
+
self.assertEqual(v1, 39 + 2 ** 1000)
|
| 380 |
+
|
| 381 |
+
def test_in_place_sub(self):
|
| 382 |
+
v1, v2 = self.Integers(10, 20)
|
| 383 |
+
|
| 384 |
+
v1 -= v2
|
| 385 |
+
self.assertEqual(v1, -10)
|
| 386 |
+
v1 -= -100
|
| 387 |
+
self.assertEqual(v1, 90)
|
| 388 |
+
v1 -= 90000
|
| 389 |
+
self.assertEqual(v1, -89910)
|
| 390 |
+
v1 -= -100000
|
| 391 |
+
self.assertEqual(v1, 10090)
|
| 392 |
+
|
| 393 |
+
def test_in_place_mul(self):
|
| 394 |
+
v1, v2 = self.Integers(3, 5)
|
| 395 |
+
|
| 396 |
+
v1 *= v2
|
| 397 |
+
self.assertEqual(v1, 15)
|
| 398 |
+
v1 *= 2
|
| 399 |
+
self.assertEqual(v1, 30)
|
| 400 |
+
v1 *= -2
|
| 401 |
+
self.assertEqual(v1, -60)
|
| 402 |
+
v1 *= 2 ** 1000
|
| 403 |
+
self.assertEqual(v1, -60 * (2 ** 1000))
|
| 404 |
+
|
| 405 |
+
def test_in_place_modulus(self):
|
| 406 |
+
v1, v2 = self.Integers(20, 7)
|
| 407 |
+
|
| 408 |
+
v1 %= v2
|
| 409 |
+
self.assertEqual(v1, 6)
|
| 410 |
+
v1 %= 2 ** 1000
|
| 411 |
+
self.assertEqual(v1, 6)
|
| 412 |
+
v1 %= 2
|
| 413 |
+
self.assertEqual(v1, 0)
|
| 414 |
+
def t():
|
| 415 |
+
v3 = self.Integer(9)
|
| 416 |
+
v3 %= 0
|
| 417 |
+
self.assertRaises(ZeroDivisionError, t)
|
| 418 |
+
|
| 419 |
+
def test_and(self):
|
| 420 |
+
v1, v2, v3 = self.Integers(0xF4, 0x31, -0xF)
|
| 421 |
+
self.assertTrue(isinstance(v1 & v2, self.Integer))
|
| 422 |
+
self.assertEqual(v1 & v2, 0x30)
|
| 423 |
+
self.assertEqual(v1 & 0x31, 0x30)
|
| 424 |
+
self.assertEqual(v1 & v3, 0xF0)
|
| 425 |
+
self.assertEqual(v1 & -0xF, 0xF0)
|
| 426 |
+
self.assertEqual(v3 & -0xF, -0xF)
|
| 427 |
+
self.assertEqual(v2 & (2 ** 1000 + 0x31), 0x31)
|
| 428 |
+
|
| 429 |
+
def test_or(self):
|
| 430 |
+
v1, v2, v3 = self.Integers(0x40, 0x82, -0xF)
|
| 431 |
+
self.assertTrue(isinstance(v1 | v2, self.Integer))
|
| 432 |
+
self.assertEqual(v1 | v2, 0xC2)
|
| 433 |
+
self.assertEqual(v1 | 0x82, 0xC2)
|
| 434 |
+
self.assertEqual(v2 | v3, -0xD)
|
| 435 |
+
self.assertEqual(v2 | 2 ** 1000, 2 ** 1000 + 0x82)
|
| 436 |
+
|
| 437 |
+
def test_right_shift(self):
|
| 438 |
+
v1, v2, v3 = self.Integers(0x10, 1, -0x10)
|
| 439 |
+
self.assertEqual(v1 >> 0, v1)
|
| 440 |
+
self.assertTrue(isinstance(v1 >> v2, self.Integer))
|
| 441 |
+
self.assertEqual(v1 >> v2, 0x08)
|
| 442 |
+
self.assertEqual(v1 >> 1, 0x08)
|
| 443 |
+
self.assertRaises(ValueError, lambda: v1 >> -1)
|
| 444 |
+
self.assertEqual(v1 >> (2 ** 1000), 0)
|
| 445 |
+
|
| 446 |
+
self.assertEqual(v3 >> 1, -0x08)
|
| 447 |
+
self.assertEqual(v3 >> (2 ** 1000), -1)
|
| 448 |
+
|
| 449 |
+
def test_in_place_right_shift(self):
|
| 450 |
+
v1, v2, v3 = self.Integers(0x10, 1, -0x10)
|
| 451 |
+
v1 >>= 0
|
| 452 |
+
self.assertEqual(v1, 0x10)
|
| 453 |
+
v1 >>= 1
|
| 454 |
+
self.assertEqual(v1, 0x08)
|
| 455 |
+
v1 >>= v2
|
| 456 |
+
self.assertEqual(v1, 0x04)
|
| 457 |
+
v3 >>= 1
|
| 458 |
+
self.assertEqual(v3, -0x08)
|
| 459 |
+
def l():
|
| 460 |
+
v4 = self.Integer(0x90)
|
| 461 |
+
v4 >>= -1
|
| 462 |
+
self.assertRaises(ValueError, l)
|
| 463 |
+
def m1():
|
| 464 |
+
v4 = self.Integer(0x90)
|
| 465 |
+
v4 >>= 2 ** 1000
|
| 466 |
+
return v4
|
| 467 |
+
self.assertEqual(0, m1())
|
| 468 |
+
def m2():
|
| 469 |
+
v4 = self.Integer(-1)
|
| 470 |
+
v4 >>= 2 ** 1000
|
| 471 |
+
return v4
|
| 472 |
+
self.assertEqual(-1, m2())
|
| 473 |
+
|
| 474 |
+
def _test_left_shift(self):
|
| 475 |
+
v1, v2, v3 = self.Integers(0x10, 1, -0x10)
|
| 476 |
+
self.assertEqual(v1 << 0, v1)
|
| 477 |
+
self.assertTrue(isinstance(v1 << v2, self.Integer))
|
| 478 |
+
self.assertEqual(v1 << v2, 0x20)
|
| 479 |
+
self.assertEqual(v1 << 1, 0x20)
|
| 480 |
+
self.assertEqual(v3 << 1, -0x20)
|
| 481 |
+
self.assertRaises(ValueError, lambda: v1 << -1)
|
| 482 |
+
self.assertRaises(ValueError, lambda: v1 << (2 ** 1000))
|
| 483 |
+
|
| 484 |
+
def test_in_place_left_shift(self):
|
| 485 |
+
v1, v2, v3 = self.Integers(0x10, 1, -0x10)
|
| 486 |
+
v1 <<= 0
|
| 487 |
+
self.assertEqual(v1, 0x10)
|
| 488 |
+
v1 <<= 1
|
| 489 |
+
self.assertEqual(v1, 0x20)
|
| 490 |
+
v1 <<= v2
|
| 491 |
+
self.assertEqual(v1, 0x40)
|
| 492 |
+
v3 <<= 1
|
| 493 |
+
self.assertEqual(v3, -0x20)
|
| 494 |
+
def l():
|
| 495 |
+
v4 = self.Integer(0x90)
|
| 496 |
+
v4 <<= -1
|
| 497 |
+
self.assertRaises(ValueError, l)
|
| 498 |
+
def m():
|
| 499 |
+
v4 = self.Integer(0x90)
|
| 500 |
+
v4 <<= 2 ** 1000
|
| 501 |
+
self.assertRaises(ValueError, m)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def test_get_bit(self):
|
| 505 |
+
v1, v2, v3 = self.Integers(0x102, -3, 1)
|
| 506 |
+
self.assertEqual(v1.get_bit(0), 0)
|
| 507 |
+
self.assertEqual(v1.get_bit(1), 1)
|
| 508 |
+
self.assertEqual(v1.get_bit(v3), 1)
|
| 509 |
+
self.assertEqual(v1.get_bit(8), 1)
|
| 510 |
+
self.assertEqual(v1.get_bit(9), 0)
|
| 511 |
+
|
| 512 |
+
self.assertRaises(ValueError, v1.get_bit, -1)
|
| 513 |
+
self.assertEqual(v1.get_bit(2 ** 1000), 0)
|
| 514 |
+
|
| 515 |
+
self.assertRaises(ValueError, v2.get_bit, -1)
|
| 516 |
+
self.assertRaises(ValueError, v2.get_bit, 0)
|
| 517 |
+
self.assertRaises(ValueError, v2.get_bit, 1)
|
| 518 |
+
self.assertRaises(ValueError, v2.get_bit, 2 * 1000)
|
| 519 |
+
|
| 520 |
+
def test_odd_even(self):
|
| 521 |
+
v1, v2, v3, v4, v5 = self.Integers(0, 4, 17, -4, -17)
|
| 522 |
+
|
| 523 |
+
self.assertTrue(v1.is_even())
|
| 524 |
+
self.assertTrue(v2.is_even())
|
| 525 |
+
self.assertFalse(v3.is_even())
|
| 526 |
+
self.assertTrue(v4.is_even())
|
| 527 |
+
self.assertFalse(v5.is_even())
|
| 528 |
+
|
| 529 |
+
self.assertFalse(v1.is_odd())
|
| 530 |
+
self.assertFalse(v2.is_odd())
|
| 531 |
+
self.assertTrue(v3.is_odd())
|
| 532 |
+
self.assertFalse(v4.is_odd())
|
| 533 |
+
self.assertTrue(v5.is_odd())
|
| 534 |
+
|
| 535 |
+
def test_size_in_bits(self):
|
| 536 |
+
v1, v2, v3, v4 = self.Integers(0, 1, 0x100, -90)
|
| 537 |
+
self.assertEqual(v1.size_in_bits(), 1)
|
| 538 |
+
self.assertEqual(v2.size_in_bits(), 1)
|
| 539 |
+
self.assertEqual(v3.size_in_bits(), 9)
|
| 540 |
+
self.assertRaises(ValueError, v4.size_in_bits)
|
| 541 |
+
|
| 542 |
+
def test_size_in_bytes(self):
|
| 543 |
+
v1, v2, v3, v4, v5, v6 = self.Integers(0, 1, 0xFF, 0x1FF, 0x10000, -9)
|
| 544 |
+
self.assertEqual(v1.size_in_bytes(), 1)
|
| 545 |
+
self.assertEqual(v2.size_in_bytes(), 1)
|
| 546 |
+
self.assertEqual(v3.size_in_bytes(), 1)
|
| 547 |
+
self.assertEqual(v4.size_in_bytes(), 2)
|
| 548 |
+
self.assertEqual(v5.size_in_bytes(), 3)
|
| 549 |
+
self.assertRaises(ValueError, v6.size_in_bits)
|
| 550 |
+
|
| 551 |
+
def test_perfect_square(self):
|
| 552 |
+
|
| 553 |
+
self.assertFalse(self.Integer(-9).is_perfect_square())
|
| 554 |
+
self.assertTrue(self.Integer(0).is_perfect_square())
|
| 555 |
+
self.assertTrue(self.Integer(1).is_perfect_square())
|
| 556 |
+
self.assertFalse(self.Integer(2).is_perfect_square())
|
| 557 |
+
self.assertFalse(self.Integer(3).is_perfect_square())
|
| 558 |
+
self.assertTrue(self.Integer(4).is_perfect_square())
|
| 559 |
+
self.assertTrue(self.Integer(39*39).is_perfect_square())
|
| 560 |
+
self.assertFalse(self.Integer(39*39+1).is_perfect_square())
|
| 561 |
+
|
| 562 |
+
for x in range(100, 1000):
|
| 563 |
+
self.assertFalse(self.Integer(x**2+1).is_perfect_square())
|
| 564 |
+
self.assertTrue(self.Integer(x**2).is_perfect_square())
|
| 565 |
+
|
| 566 |
+
def test_fail_if_divisible_by(self):
|
| 567 |
+
v1, v2, v3 = self.Integers(12, -12, 4)
|
| 568 |
+
|
| 569 |
+
# No failure expected
|
| 570 |
+
v1.fail_if_divisible_by(7)
|
| 571 |
+
v2.fail_if_divisible_by(7)
|
| 572 |
+
v2.fail_if_divisible_by(2 ** 80)
|
| 573 |
+
|
| 574 |
+
# Failure expected
|
| 575 |
+
self.assertRaises(ValueError, v1.fail_if_divisible_by, 4)
|
| 576 |
+
self.assertRaises(ValueError, v1.fail_if_divisible_by, v3)
|
| 577 |
+
|
| 578 |
+
def test_multiply_accumulate(self):
|
| 579 |
+
v1, v2, v3 = self.Integers(4, 3, 2)
|
| 580 |
+
v1.multiply_accumulate(v2, v3)
|
| 581 |
+
self.assertEqual(v1, 10)
|
| 582 |
+
v1.multiply_accumulate(v2, 2)
|
| 583 |
+
self.assertEqual(v1, 16)
|
| 584 |
+
v1.multiply_accumulate(3, v3)
|
| 585 |
+
self.assertEqual(v1, 22)
|
| 586 |
+
v1.multiply_accumulate(1, -2)
|
| 587 |
+
self.assertEqual(v1, 20)
|
| 588 |
+
v1.multiply_accumulate(-2, 1)
|
| 589 |
+
self.assertEqual(v1, 18)
|
| 590 |
+
v1.multiply_accumulate(1, 2 ** 1000)
|
| 591 |
+
self.assertEqual(v1, 18 + 2 ** 1000)
|
| 592 |
+
v1.multiply_accumulate(2 ** 1000, 1)
|
| 593 |
+
self.assertEqual(v1, 18 + 2 ** 1001)
|
| 594 |
+
|
| 595 |
+
def test_set(self):
|
| 596 |
+
v1, v2 = self.Integers(3, 6)
|
| 597 |
+
v1.set(v2)
|
| 598 |
+
self.assertEqual(v1, 6)
|
| 599 |
+
v1.set(9)
|
| 600 |
+
self.assertEqual(v1, 9)
|
| 601 |
+
v1.set(-2)
|
| 602 |
+
self.assertEqual(v1, -2)
|
| 603 |
+
v1.set(2 ** 1000)
|
| 604 |
+
self.assertEqual(v1, 2 ** 1000)
|
| 605 |
+
|
| 606 |
+
def test_inverse(self):
|
| 607 |
+
v1, v2, v3, v4, v5, v6 = self.Integers(2, 5, -3, 0, 723872, 3433)
|
| 608 |
+
|
| 609 |
+
self.assertTrue(isinstance(v1.inverse(v2), self.Integer))
|
| 610 |
+
self.assertEqual(v1.inverse(v2), 3)
|
| 611 |
+
self.assertEqual(v1.inverse(5), 3)
|
| 612 |
+
self.assertEqual(v3.inverse(5), 3)
|
| 613 |
+
self.assertEqual(v5.inverse(92929921), 58610507)
|
| 614 |
+
self.assertEqual(v6.inverse(9912), 5353)
|
| 615 |
+
|
| 616 |
+
self.assertRaises(ValueError, v2.inverse, 10)
|
| 617 |
+
self.assertRaises(ValueError, v1.inverse, -3)
|
| 618 |
+
self.assertRaises(ValueError, v4.inverse, 10)
|
| 619 |
+
self.assertRaises(ZeroDivisionError, v2.inverse, 0)
|
| 620 |
+
|
| 621 |
+
def test_inplace_inverse(self):
|
| 622 |
+
v1, v2 = self.Integers(2, 5)
|
| 623 |
+
|
| 624 |
+
v1.inplace_inverse(v2)
|
| 625 |
+
self.assertEqual(v1, 3)
|
| 626 |
+
|
| 627 |
+
def test_gcd(self):
|
| 628 |
+
v1, v2, v3, v4 = self.Integers(6, 10, 17, -2)
|
| 629 |
+
self.assertTrue(isinstance(v1.gcd(v2), self.Integer))
|
| 630 |
+
self.assertEqual(v1.gcd(v2), 2)
|
| 631 |
+
self.assertEqual(v1.gcd(10), 2)
|
| 632 |
+
self.assertEqual(v1.gcd(v3), 1)
|
| 633 |
+
self.assertEqual(v1.gcd(-2), 2)
|
| 634 |
+
self.assertEqual(v4.gcd(6), 2)
|
| 635 |
+
|
| 636 |
+
def test_lcm(self):
|
| 637 |
+
v1, v2, v3, v4, v5 = self.Integers(6, 10, 17, -2, 0)
|
| 638 |
+
self.assertTrue(isinstance(v1.lcm(v2), self.Integer))
|
| 639 |
+
self.assertEqual(v1.lcm(v2), 30)
|
| 640 |
+
self.assertEqual(v1.lcm(10), 30)
|
| 641 |
+
self.assertEqual(v1.lcm(v3), 102)
|
| 642 |
+
self.assertEqual(v1.lcm(-2), 6)
|
| 643 |
+
self.assertEqual(v4.lcm(6), 6)
|
| 644 |
+
self.assertEqual(v1.lcm(0), 0)
|
| 645 |
+
self.assertEqual(v5.lcm(0), 0)
|
| 646 |
+
|
| 647 |
+
def test_jacobi_symbol(self):
|
| 648 |
+
|
| 649 |
+
data = (
|
| 650 |
+
(1001, 1, 1),
|
| 651 |
+
(19, 45, 1),
|
| 652 |
+
(8, 21, -1),
|
| 653 |
+
(5, 21, 1),
|
| 654 |
+
(610, 987, -1),
|
| 655 |
+
(1001, 9907, -1),
|
| 656 |
+
(5, 3439601197, -1)
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
js = self.Integer.jacobi_symbol
|
| 660 |
+
|
| 661 |
+
# Jacobi symbol is always 1 for k==1 or n==1
|
| 662 |
+
for k in range(1, 30):
|
| 663 |
+
self.assertEqual(js(k, 1), 1)
|
| 664 |
+
for n in range(1, 30, 2):
|
| 665 |
+
self.assertEqual(js(1, n), 1)
|
| 666 |
+
|
| 667 |
+
# Fail if n is not positive odd
|
| 668 |
+
self.assertRaises(ValueError, js, 6, -2)
|
| 669 |
+
self.assertRaises(ValueError, js, 6, -1)
|
| 670 |
+
self.assertRaises(ValueError, js, 6, 0)
|
| 671 |
+
self.assertRaises(ValueError, js, 0, 0)
|
| 672 |
+
self.assertRaises(ValueError, js, 6, 2)
|
| 673 |
+
self.assertRaises(ValueError, js, 6, 4)
|
| 674 |
+
self.assertRaises(ValueError, js, 6, 6)
|
| 675 |
+
self.assertRaises(ValueError, js, 6, 8)
|
| 676 |
+
|
| 677 |
+
for tv in data:
|
| 678 |
+
self.assertEqual(js(tv[0], tv[1]), tv[2])
|
| 679 |
+
self.assertEqual(js(self.Integer(tv[0]), tv[1]), tv[2])
|
| 680 |
+
self.assertEqual(js(tv[0], self.Integer(tv[1])), tv[2])
|
| 681 |
+
|
| 682 |
+
def test_jacobi_symbol_wikipedia(self):
|
| 683 |
+
|
| 684 |
+
# Test vectors from https://en.wikipedia.org/wiki/Jacobi_symbol
|
| 685 |
+
tv = [
|
| 686 |
+
(3, [(1, 1), (2, -1), (3, 0), (4, 1), (5, -1), (6, 0), (7, 1), (8, -1), (9, 0), (10, 1), (11, -1), (12, 0), (13, 1), (14, -1), (15, 0), (16, 1), (17, -1), (18, 0), (19, 1), (20, -1), (21, 0), (22, 1), (23, -1), (24, 0), (25, 1), (26, -1), (27, 0), (28, 1), (29, -1), (30, 0)]),
|
| 687 |
+
(5, [(1, 1), (2, -1), (3, -1), (4, 1), (5, 0), (6, 1), (7, -1), (8, -1), (9, 1), (10, 0), (11, 1), (12, -1), (13, -1), (14, 1), (15, 0), (16, 1), (17, -1), (18, -1), (19, 1), (20, 0), (21, 1), (22, -1), (23, -1), (24, 1), (25, 0), (26, 1), (27, -1), (28, -1), (29, 1), (30, 0)]),
|
| 688 |
+
(7, [(1, 1), (2, 1), (3, -1), (4, 1), (5, -1), (6, -1), (7, 0), (8, 1), (9, 1), (10, -1), (11, 1), (12, -1), (13, -1), (14, 0), (15, 1), (16, 1), (17, -1), (18, 1), (19, -1), (20, -1), (21, 0), (22, 1), (23, 1), (24, -1), (25, 1), (26, -1), (27, -1), (28, 0), (29, 1), (30, 1)]),
|
| 689 |
+
(9, [(1, 1), (2, 1), (3, 0), (4, 1), (5, 1), (6, 0), (7, 1), (8, 1), (9, 0), (10, 1), (11, 1), (12, 0), (13, 1), (14, 1), (15, 0), (16, 1), (17, 1), (18, 0), (19, 1), (20, 1), (21, 0), (22, 1), (23, 1), (24, 0), (25, 1), (26, 1), (27, 0), (28, 1), (29, 1), (30, 0)]),
|
| 690 |
+
(11, [(1, 1), (2, -1), (3, 1), (4, 1), (5, 1), (6, -1), (7, -1), (8, -1), (9, 1), (10, -1), (11, 0), (12, 1), (13, -1), (14, 1), (15, 1), (16, 1), (17, -1), (18, -1), (19, -1), (20, 1), (21, -1), (22, 0), (23, 1), (24, -1), (25, 1), (26, 1), (27, 1), (28, -1), (29, -1), (30, -1)]),
|
| 691 |
+
(13, [(1, 1), (2, -1), (3, 1), (4, 1), (5, -1), (6, -1), (7, -1), (8, -1), (9, 1), (10, 1), (11, -1), (12, 1), (13, 0), (14, 1), (15, -1), (16, 1), (17, 1), (18, -1), (19, -1), (20, -1), (21, -1), (22, 1), (23, 1), (24, -1), (25, 1), (26, 0), (27, 1), (28, -1), (29, 1), (30, 1)]),
|
| 692 |
+
(15, [(1, 1), (2, 1), (3, 0), (4, 1), (5, 0), (6, 0), (7, -1), (8, 1), (9, 0), (10, 0), (11, -1), (12, 0), (13, -1), (14, -1), (15, 0), (16, 1), (17, 1), (18, 0), (19, 1), (20, 0), (21, 0), (22, -1), (23, 1), (24, 0), (25, 0), (26, -1), (27, 0), (28, -1), (29, -1), (30, 0)]),
|
| 693 |
+
(17, [(1, 1), (2, 1), (3, -1), (4, 1), (5, -1), (6, -1), (7, -1), (8, 1), (9, 1), (10, -1), (11, -1), (12, -1), (13, 1), (14, -1), (15, 1), (16, 1), (17, 0), (18, 1), (19, 1), (20, -1), (21, 1), (22, -1), (23, -1), (24, -1), (25, 1), (26, 1), (27, -1), (28, -1), (29, -1), (30, 1)]),
|
| 694 |
+
(19, [(1, 1), (2, -1), (3, -1), (4, 1), (5, 1), (6, 1), (7, 1), (8, -1), (9, 1), (10, -1), (11, 1), (12, -1), (13, -1), (14, -1), (15, -1), (16, 1), (17, 1), (18, -1), (19, 0), (20, 1), (21, -1), (22, -1), (23, 1), (24, 1), (25, 1), (26, 1), (27, -1), (28, 1), (29, -1), (30, 1)]),
|
| 695 |
+
(21, [(1, 1), (2, -1), (3, 0), (4, 1), (5, 1), (6, 0), (7, 0), (8, -1), (9, 0), (10, -1), (11, -1), (12, 0), (13, -1), (14, 0), (15, 0), (16, 1), (17, 1), (18, 0), (19, -1), (20, 1), (21, 0), (22, 1), (23, -1), (24, 0), (25, 1), (26, 1), (27, 0), (28, 0), (29, -1), (30, 0)]),
|
| 696 |
+
(23, [(1, 1), (2, 1), (3, 1), (4, 1), (5, -1), (6, 1), (7, -1), (8, 1), (9, 1), (10, -1), (11, -1), (12, 1), (13, 1), (14, -1), (15, -1), (16, 1), (17, -1), (18, 1), (19, -1), (20, -1), (21, -1), (22, -1), (23, 0), (24, 1), (25, 1), (26, 1), (27, 1), (28, -1), (29, 1), (30, -1)]),
|
| 697 |
+
(25, [(1, 1), (2, 1), (3, 1), (4, 1), (5, 0), (6, 1), (7, 1), (8, 1), (9, 1), (10, 0), (11, 1), (12, 1), (13, 1), (14, 1), (15, 0), (16, 1), (17, 1), (18, 1), (19, 1), (20, 0), (21, 1), (22, 1), (23, 1), (24, 1), (25, 0), (26, 1), (27, 1), (28, 1), (29, 1), (30, 0)]),
|
| 698 |
+
(27, [(1, 1), (2, -1), (3, 0), (4, 1), (5, -1), (6, 0), (7, 1), (8, -1), (9, 0), (10, 1), (11, -1), (12, 0), (13, 1), (14, -1), (15, 0), (16, 1), (17, -1), (18, 0), (19, 1), (20, -1), (21, 0), (22, 1), (23, -1), (24, 0), (25, 1), (26, -1), (27, 0), (28, 1), (29, -1), (30, 0)]),
|
| 699 |
+
(29, [(1, 1), (2, -1), (3, -1), (4, 1), (5, 1), (6, 1), (7, 1), (8, -1), (9, 1), (10, -1), (11, -1), (12, -1), (13, 1), (14, -1), (15, -1), (16, 1), (17, -1), (18, -1), (19, -1), (20, 1), (21, -1), (22, 1), (23, 1), (24, 1), (25, 1), (26, -1), (27, -1), (28, 1), (29, 0), (30, 1)]),
|
| 700 |
+
]
|
| 701 |
+
|
| 702 |
+
js = self.Integer.jacobi_symbol
|
| 703 |
+
|
| 704 |
+
for n, kj in tv:
|
| 705 |
+
for k, j in kj:
|
| 706 |
+
self.assertEqual(js(k, n), j)
|
| 707 |
+
|
| 708 |
+
def test_hex(self):
|
| 709 |
+
v1, = self.Integers(0x10)
|
| 710 |
+
self.assertEqual(hex(v1), "0x10")
|
| 711 |
+
|
| 712 |
+
def test_mult_modulo_bytes(self):
|
| 713 |
+
modmult = self.Integer._mult_modulo_bytes
|
| 714 |
+
|
| 715 |
+
res = modmult(4, 5, 19)
|
| 716 |
+
self.assertEqual(res, b'\x01')
|
| 717 |
+
|
| 718 |
+
res = modmult(4 - 19, 5, 19)
|
| 719 |
+
self.assertEqual(res, b'\x01')
|
| 720 |
+
|
| 721 |
+
res = modmult(4, 5 - 19, 19)
|
| 722 |
+
self.assertEqual(res, b'\x01')
|
| 723 |
+
|
| 724 |
+
res = modmult(4 + 19, 5, 19)
|
| 725 |
+
self.assertEqual(res, b'\x01')
|
| 726 |
+
|
| 727 |
+
res = modmult(4, 5 + 19, 19)
|
| 728 |
+
self.assertEqual(res, b'\x01')
|
| 729 |
+
|
| 730 |
+
modulus = 2**512 - 1 # 64 bytes
|
| 731 |
+
t1 = 13**100
|
| 732 |
+
t2 = 17**100
|
| 733 |
+
expect = b"\xfa\xb2\x11\x87\xc3(y\x07\xf8\xf1n\xdepq\x0b\xca\xf3\xd3B,\xef\xf2\xfbf\xcc)\x8dZ*\x95\x98r\x96\xa8\xd5\xc3}\xe2q:\xa2'z\xf48\xde%\xef\t\x07\xbc\xc4[C\x8bUE2\x90\xef\x81\xaa:\x08"
|
| 734 |
+
self.assertEqual(expect, modmult(t1, t2, modulus))
|
| 735 |
+
|
| 736 |
+
self.assertRaises(ZeroDivisionError, modmult, 4, 5, 0)
|
| 737 |
+
self.assertRaises(ValueError, modmult, 4, 5, -1)
|
| 738 |
+
self.assertRaises(ValueError, modmult, 4, 5, 4)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
class TestIntegerInt(TestIntegerBase):
|
| 742 |
+
|
| 743 |
+
def setUp(self):
|
| 744 |
+
self.Integer = IntegerNative
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
class testIntegerRandom(unittest.TestCase):
|
| 748 |
+
|
| 749 |
+
def test_random_exact_bits(self):
|
| 750 |
+
|
| 751 |
+
for _ in range(1000):
|
| 752 |
+
a = IntegerNative.random(exact_bits=8)
|
| 753 |
+
self.assertFalse(a < 128)
|
| 754 |
+
self.assertFalse(a >= 256)
|
| 755 |
+
|
| 756 |
+
for bits_value in range(1024, 1024 + 8):
|
| 757 |
+
a = IntegerNative.random(exact_bits=bits_value)
|
| 758 |
+
self.assertFalse(a < 2**(bits_value - 1))
|
| 759 |
+
self.assertFalse(a >= 2**bits_value)
|
| 760 |
+
|
| 761 |
+
def test_random_max_bits(self):
|
| 762 |
+
|
| 763 |
+
flag = False
|
| 764 |
+
for _ in range(1000):
|
| 765 |
+
a = IntegerNative.random(max_bits=8)
|
| 766 |
+
flag = flag or a < 128
|
| 767 |
+
self.assertFalse(a>=256)
|
| 768 |
+
self.assertTrue(flag)
|
| 769 |
+
|
| 770 |
+
for bits_value in range(1024, 1024 + 8):
|
| 771 |
+
a = IntegerNative.random(max_bits=bits_value)
|
| 772 |
+
self.assertFalse(a >= 2**bits_value)
|
| 773 |
+
|
| 774 |
+
def test_random_bits_custom_rng(self):
|
| 775 |
+
|
| 776 |
+
class CustomRNG(object):
|
| 777 |
+
def __init__(self):
|
| 778 |
+
self.counter = 0
|
| 779 |
+
|
| 780 |
+
def __call__(self, size):
|
| 781 |
+
self.counter += size
|
| 782 |
+
return bchr(0) * size
|
| 783 |
+
|
| 784 |
+
custom_rng = CustomRNG()
|
| 785 |
+
a = IntegerNative.random(exact_bits=32, randfunc=custom_rng)
|
| 786 |
+
self.assertEqual(custom_rng.counter, 4)
|
| 787 |
+
|
| 788 |
+
def test_random_range(self):
|
| 789 |
+
|
| 790 |
+
func = IntegerNative.random_range
|
| 791 |
+
|
| 792 |
+
for x in range(200):
|
| 793 |
+
a = func(min_inclusive=1, max_inclusive=15)
|
| 794 |
+
self.assertTrue(1 <= a <= 15)
|
| 795 |
+
|
| 796 |
+
for x in range(200):
|
| 797 |
+
a = func(min_inclusive=1, max_exclusive=15)
|
| 798 |
+
self.assertTrue(1 <= a < 15)
|
| 799 |
+
|
| 800 |
+
self.assertRaises(ValueError, func, min_inclusive=1, max_inclusive=2,
|
| 801 |
+
max_exclusive=3)
|
| 802 |
+
self.assertRaises(ValueError, func, max_inclusive=2, max_exclusive=3)
|
| 803 |
+
|
| 804 |
+
def get_tests(config={}):
|
| 805 |
+
tests = []
|
| 806 |
+
tests += list_test_cases(TestIntegerInt)
|
| 807 |
+
|
| 808 |
+
try:
|
| 809 |
+
from Crypto.Math._IntegerGMP import IntegerGMP
|
| 810 |
+
|
| 811 |
+
class TestIntegerGMP(TestIntegerBase):
|
| 812 |
+
def setUp(self):
|
| 813 |
+
self.Integer = IntegerGMP
|
| 814 |
+
|
| 815 |
+
tests += list_test_cases(TestIntegerGMP)
|
| 816 |
+
except (ImportError, OSError) as e:
|
| 817 |
+
if sys.platform == "win32":
|
| 818 |
+
sys.stdout.write("Skipping GMP tests on Windows\n")
|
| 819 |
+
else:
|
| 820 |
+
sys.stdout.write("Skipping GMP tests (%s)\n" % str(e) )
|
| 821 |
+
|
| 822 |
+
try:
|
| 823 |
+
from Crypto.Math._IntegerCustom import IntegerCustom
|
| 824 |
+
|
| 825 |
+
class TestIntegerCustomModexp(TestIntegerBase):
|
| 826 |
+
def setUp(self):
|
| 827 |
+
self.Integer = IntegerCustom
|
| 828 |
+
|
| 829 |
+
tests += list_test_cases(TestIntegerCustomModexp)
|
| 830 |
+
except (ImportError, OSError) as e:
|
| 831 |
+
sys.stdout.write("Skipping custom modexp tests (%s)\n" % str(e) )
|
| 832 |
+
|
| 833 |
+
tests += list_test_cases(testIntegerRandom)
|
| 834 |
+
return tests
|
| 835 |
+
|
| 836 |
+
if __name__ == '__main__':
|
| 837 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 838 |
+
unittest.main(defaultTest='suite')
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_Primality.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SelfTest/Math/test_Primality.py: Self-test for Primality module
|
| 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 |
+
"""Self-test for Math.Numbers"""
|
| 35 |
+
|
| 36 |
+
import unittest
|
| 37 |
+
|
| 38 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 39 |
+
|
| 40 |
+
from Crypto.Util.py3compat import *
|
| 41 |
+
|
| 42 |
+
from Crypto.Math.Numbers import Integer
|
| 43 |
+
from Crypto.Math.Primality import (
|
| 44 |
+
PROBABLY_PRIME, COMPOSITE,
|
| 45 |
+
miller_rabin_test, lucas_test,
|
| 46 |
+
test_probable_prime,
|
| 47 |
+
generate_probable_prime,
|
| 48 |
+
generate_probable_safe_prime,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TestPrimality(unittest.TestCase):
|
| 53 |
+
|
| 54 |
+
primes = (1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 2**127-1, 175637383534939453397801320455508570374088202376942372758907369518414308188137781042871856139027160010343454418881888953150175357127346872102307696660678617989191485418582475696230580407111841072614783095326672517315988762029036079794994990250662362650625650262324085116467511357592728695033227611029693067539)
|
| 55 |
+
composites = (0, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 7*23, (2**19-1)*(2**67-1), 9746347772161,)
|
| 56 |
+
|
| 57 |
+
def test_miller_rabin(self):
|
| 58 |
+
for prime in self.primes:
|
| 59 |
+
self.assertEqual(miller_rabin_test(prime, 3), PROBABLY_PRIME)
|
| 60 |
+
for composite in self.composites:
|
| 61 |
+
self.assertEqual(miller_rabin_test(composite, 3), COMPOSITE)
|
| 62 |
+
self.assertRaises(ValueError, miller_rabin_test, -1, 3)
|
| 63 |
+
|
| 64 |
+
def test_lucas(self):
|
| 65 |
+
for prime in self.primes:
|
| 66 |
+
res = lucas_test(prime)
|
| 67 |
+
self.assertEqual(res, PROBABLY_PRIME)
|
| 68 |
+
for composite in self.composites:
|
| 69 |
+
res = lucas_test(composite)
|
| 70 |
+
self.assertEqual(res, COMPOSITE)
|
| 71 |
+
self.assertRaises(ValueError, lucas_test, -1)
|
| 72 |
+
|
| 73 |
+
def test_is_prime(self):
|
| 74 |
+
primes = (170141183460469231731687303715884105727,
|
| 75 |
+
19175002942688032928599,
|
| 76 |
+
1363005552434666078217421284621279933627102780881053358473,
|
| 77 |
+
2 ** 521 - 1)
|
| 78 |
+
for p in primes:
|
| 79 |
+
self.assertEqual(test_probable_prime(p), PROBABLY_PRIME)
|
| 80 |
+
|
| 81 |
+
not_primes = (
|
| 82 |
+
4754868377601046732119933839981363081972014948522510826417784001,
|
| 83 |
+
1334733877147062382486934807105197899496002201113849920496510541601,
|
| 84 |
+
260849323075371835669784094383812120359260783810157225730623388382401,
|
| 85 |
+
)
|
| 86 |
+
for np in not_primes:
|
| 87 |
+
self.assertEqual(test_probable_prime(np), COMPOSITE)
|
| 88 |
+
|
| 89 |
+
from Crypto.Util.number import sieve_base
|
| 90 |
+
for p in sieve_base[:100]:
|
| 91 |
+
res = test_probable_prime(p)
|
| 92 |
+
self.assertEqual(res, PROBABLY_PRIME)
|
| 93 |
+
|
| 94 |
+
def test_generate_prime_bit_size(self):
|
| 95 |
+
p = generate_probable_prime(exact_bits=512)
|
| 96 |
+
self.assertEqual(p.size_in_bits(), 512)
|
| 97 |
+
|
| 98 |
+
def test_generate_prime_filter(self):
|
| 99 |
+
def ending_with_one(number):
|
| 100 |
+
return number % 10 == 1
|
| 101 |
+
|
| 102 |
+
for x in range(20):
|
| 103 |
+
q = generate_probable_prime(exact_bits=160,
|
| 104 |
+
prime_filter=ending_with_one)
|
| 105 |
+
self.assertEqual(q % 10, 1)
|
| 106 |
+
|
| 107 |
+
def test_generate_safe_prime(self):
|
| 108 |
+
p = generate_probable_safe_prime(exact_bits=161)
|
| 109 |
+
self.assertEqual(p.size_in_bits(), 161)
|
| 110 |
+
|
| 111 |
+
def get_tests(config={}):
|
| 112 |
+
tests = []
|
| 113 |
+
tests += list_test_cases(TestPrimality)
|
| 114 |
+
return tests
|
| 115 |
+
|
| 116 |
+
if __name__ == '__main__':
|
| 117 |
+
suite = lambda: unittest.TestSuite(get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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SelfTest/Math/test_modexp.py: Self-test for module exponentiation
|
| 3 |
+
#
|
| 4 |
+
# ===================================================================
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2017, Helder Eijs <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 |
+
"""Self-test for the custom module exponentiation"""
|
| 35 |
+
|
| 36 |
+
import unittest
|
| 37 |
+
|
| 38 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 39 |
+
|
| 40 |
+
from Crypto.Util.number import long_to_bytes, bytes_to_long
|
| 41 |
+
|
| 42 |
+
from Crypto.Util.py3compat import *
|
| 43 |
+
|
| 44 |
+
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
|
| 45 |
+
create_string_buffer,
|
| 46 |
+
get_raw_buffer,
|
| 47 |
+
c_size_t,
|
| 48 |
+
c_ulonglong)
|
| 49 |
+
|
| 50 |
+
from Crypto.Hash import SHAKE128
|
| 51 |
+
from Crypto.Math.Numbers import Integer
|
| 52 |
+
from Crypto.Math._IntegerCustom import _raw_montgomery
|
| 53 |
+
|
| 54 |
+
from Crypto.Random.random import StrongRandom
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def create_rng(tag):
|
| 58 |
+
rng = StrongRandom(SHAKE128.new(data=tag))
|
| 59 |
+
return rng
|
| 60 |
+
|
| 61 |
+
class ExceptionModulus(ValueError):
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
def monty_pow(base, exp, modulus):
|
| 65 |
+
max_len = len(long_to_bytes(max(base, exp, modulus)))
|
| 66 |
+
|
| 67 |
+
base_b, exp_b, modulus_b = [ long_to_bytes(x, max_len) for x in
|
| 68 |
+
(base, exp, modulus) ]
|
| 69 |
+
|
| 70 |
+
out = create_string_buffer(max_len)
|
| 71 |
+
error = _raw_montgomery.monty_pow(
|
| 72 |
+
out,
|
| 73 |
+
base_b,
|
| 74 |
+
exp_b,
|
| 75 |
+
modulus_b,
|
| 76 |
+
c_size_t(max_len),
|
| 77 |
+
c_ulonglong(32)
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if error == 17:
|
| 81 |
+
raise ExceptionModulus()
|
| 82 |
+
if error:
|
| 83 |
+
raise ValueError("monty_pow failed with error: %d" % error)
|
| 84 |
+
|
| 85 |
+
result = bytes_to_long(get_raw_buffer(out))
|
| 86 |
+
return result
|
| 87 |
+
|
| 88 |
+
exponent1 = 0x2ce0af628901460a419a08ef950d498b9fd6f271a1a52ac293b86fe5c60efe8e8ba93fa1ebe1eb3d614d2e7b328cb60a2591440e163441a190ecf101ceec245f600fffdcf3f5b3a17a7baeacb96a424db1d7ec985e8ec998bb479fecfffed6a75f9a90fc97062fd973303bce855ad7b8d8272a94025e8532be9aabd54a183f303538d2a7e621b4131d59e823a4625f39bd7d518d7784f7c3a8f19061da74974ff42fa1c063dec2db97d461e291a7d6e721708a5229de166c1246363372854e27f3f08ae274bc16bfd205b028a4d81386494433d516dfbb35f495acba5e4e1d1843cb3c3129b6642a85fc7244ce5845fac071c7f622e4ee12ac43fabeeaa0cd01
|
| 89 |
+
modulus1 = 0xd66691b20071be4d66d4b71032b37fa007cfabf579fcb91e50bfc2753b3f0ce7be74e216aef7e26d4ae180bc20d7bd3ea88a6cbf6f87380e613c8979b5b043b200a8ff8856a3b12875e36e98a7569f3852d028e967551000b02c19e9fa52e83115b89309aabb1e1cf1e2cb6369d637d46775ce4523ea31f64ad2794cbc365dd8a35e007ed3b57695877fbf102dbeb8b3212491398e494314e93726926e1383f8abb5889bea954eb8c0ca1c62c8e9d83f41888095c5e645ed6d32515fe0c58c1368cad84694e18da43668c6f43e61d7c9bca633ddcda7aef5b79bc396d4a9f48e2a9abe0836cc455e435305357228e93d25aaed46b952defae0f57339bf26f5a9
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class TestModExp(unittest.TestCase):
|
| 93 |
+
|
| 94 |
+
def test_small(self):
|
| 95 |
+
self.assertEqual(1, monty_pow(11,12,19))
|
| 96 |
+
|
| 97 |
+
def test_large_1(self):
|
| 98 |
+
base = 0xfffffffffffffffffffffffffffffffffffffffffffffffffff
|
| 99 |
+
expected = pow(base, exponent1, modulus1)
|
| 100 |
+
result = monty_pow(base, exponent1, modulus1)
|
| 101 |
+
self.assertEqual(result, expected)
|
| 102 |
+
|
| 103 |
+
def test_zero_exp(self):
|
| 104 |
+
base = 0xfffffffffffffffffffffffffffffffffffffffffffffffffff
|
| 105 |
+
result = monty_pow(base, 0, modulus1)
|
| 106 |
+
self.assertEqual(result, 1)
|
| 107 |
+
|
| 108 |
+
def test_zero_base(self):
|
| 109 |
+
result = monty_pow(0, exponent1, modulus1)
|
| 110 |
+
self.assertEqual(result, 0)
|
| 111 |
+
|
| 112 |
+
def test_zero_modulus(self):
|
| 113 |
+
base = 0xfffffffffffffffffffffffffffffffffffffffffffffffff
|
| 114 |
+
self.assertRaises(ExceptionModulus, monty_pow, base, exponent1, 0)
|
| 115 |
+
self.assertRaises(ExceptionModulus, monty_pow, 0, 0, 0)
|
| 116 |
+
|
| 117 |
+
def test_larger_exponent(self):
|
| 118 |
+
base = modulus1 - 0xFFFFFFF
|
| 119 |
+
expected = pow(base, modulus1<<64, modulus1)
|
| 120 |
+
result = monty_pow(base, modulus1<<64, modulus1)
|
| 121 |
+
self.assertEqual(result, expected)
|
| 122 |
+
|
| 123 |
+
def test_even_modulus(self):
|
| 124 |
+
base = modulus1 >> 4
|
| 125 |
+
self.assertRaises(ExceptionModulus, monty_pow, base, exponent1, modulus1-1)
|
| 126 |
+
|
| 127 |
+
def test_several_lengths(self):
|
| 128 |
+
prng = SHAKE128.new().update(b('Test'))
|
| 129 |
+
for length in range(1, 100):
|
| 130 |
+
modulus2 = Integer.from_bytes(prng.read(length)) | 1
|
| 131 |
+
base = Integer.from_bytes(prng.read(length)) % modulus2
|
| 132 |
+
exponent2 = Integer.from_bytes(prng.read(length))
|
| 133 |
+
|
| 134 |
+
expected = pow(base, exponent2, modulus2)
|
| 135 |
+
result = monty_pow(base, exponent2, modulus2)
|
| 136 |
+
self.assertEqual(result, expected)
|
| 137 |
+
|
| 138 |
+
def test_variable_exponent(self):
|
| 139 |
+
prng = create_rng(b('Test variable exponent'))
|
| 140 |
+
for i in range(20):
|
| 141 |
+
for j in range(7):
|
| 142 |
+
modulus = prng.getrandbits(8*30) | 1
|
| 143 |
+
base = prng.getrandbits(8*30) % modulus
|
| 144 |
+
exponent = prng.getrandbits(i*8+j)
|
| 145 |
+
|
| 146 |
+
expected = pow(base, exponent, modulus)
|
| 147 |
+
result = monty_pow(base, exponent, modulus)
|
| 148 |
+
self.assertEqual(result, expected)
|
| 149 |
+
|
| 150 |
+
exponent ^= (1 << (i*8+j)) - 1
|
| 151 |
+
|
| 152 |
+
expected = pow(base, exponent, modulus)
|
| 153 |
+
result = monty_pow(base, exponent, modulus)
|
| 154 |
+
self.assertEqual(result, expected)
|
| 155 |
+
|
| 156 |
+
def test_stress_63(self):
|
| 157 |
+
prng = create_rng(b('Test 63'))
|
| 158 |
+
length = 63
|
| 159 |
+
for _ in range(2000):
|
| 160 |
+
modulus = prng.getrandbits(8*length) | 1
|
| 161 |
+
base = prng.getrandbits(8*length) % modulus
|
| 162 |
+
exponent = prng.getrandbits(8*length)
|
| 163 |
+
|
| 164 |
+
expected = pow(base, exponent, modulus)
|
| 165 |
+
result = monty_pow(base, exponent, modulus)
|
| 166 |
+
self.assertEqual(result, expected)
|
| 167 |
+
|
| 168 |
+
def test_stress_64(self):
|
| 169 |
+
prng = create_rng(b('Test 64'))
|
| 170 |
+
length = 64
|
| 171 |
+
for _ in range(2000):
|
| 172 |
+
modulus = prng.getrandbits(8*length) | 1
|
| 173 |
+
base = prng.getrandbits(8*length) % modulus
|
| 174 |
+
exponent = prng.getrandbits(8*length)
|
| 175 |
+
|
| 176 |
+
expected = pow(base, exponent, modulus)
|
| 177 |
+
result = monty_pow(base, exponent, modulus)
|
| 178 |
+
self.assertEqual(result, expected)
|
| 179 |
+
|
| 180 |
+
def test_stress_65(self):
|
| 181 |
+
prng = create_rng(b('Test 65'))
|
| 182 |
+
length = 65
|
| 183 |
+
for _ in range(2000):
|
| 184 |
+
modulus = prng.getrandbits(8*length) | 1
|
| 185 |
+
base = prng.getrandbits(8*length) % modulus
|
| 186 |
+
exponent = prng.getrandbits(8*length)
|
| 187 |
+
|
| 188 |
+
expected = pow(base, exponent, modulus)
|
| 189 |
+
result = monty_pow(base, exponent, modulus)
|
| 190 |
+
self.assertEqual(result, expected)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def get_tests(config={}):
|
| 194 |
+
tests = []
|
| 195 |
+
tests += list_test_cases(TestModExp)
|
| 196 |
+
return tests
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == '__main__':
|
| 200 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 201 |
+
unittest.main(defaultTest='suite')
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Math/test_modmult.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SelfTest/Math/test_modmult.py: Self-test for custom modular multiplication
|
| 3 |
+
#
|
| 4 |
+
# ===================================================================
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2023, Helder Eijs <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 |
+
"""Self-test for the custom modular multiplication"""
|
| 35 |
+
|
| 36 |
+
import unittest
|
| 37 |
+
|
| 38 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 39 |
+
|
| 40 |
+
from Crypto.Util.number import long_to_bytes, bytes_to_long
|
| 41 |
+
|
| 42 |
+
from Crypto.Util._raw_api import (create_string_buffer,
|
| 43 |
+
get_raw_buffer,
|
| 44 |
+
c_size_t)
|
| 45 |
+
|
| 46 |
+
from Crypto.Math._IntegerCustom import _raw_montgomery
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ExceptionModulus(ValueError):
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def monty_mult(term1, term2, modulus):
|
| 54 |
+
|
| 55 |
+
if term1 >= modulus:
|
| 56 |
+
term1 %= modulus
|
| 57 |
+
if term2 >= modulus:
|
| 58 |
+
term2 %= modulus
|
| 59 |
+
|
| 60 |
+
modulus_b = long_to_bytes(modulus)
|
| 61 |
+
numbers_len = len(modulus_b)
|
| 62 |
+
term1_b = long_to_bytes(term1, numbers_len)
|
| 63 |
+
term2_b = long_to_bytes(term2, numbers_len)
|
| 64 |
+
|
| 65 |
+
out = create_string_buffer(numbers_len)
|
| 66 |
+
error = _raw_montgomery.monty_multiply(
|
| 67 |
+
out,
|
| 68 |
+
term1_b,
|
| 69 |
+
term2_b,
|
| 70 |
+
modulus_b,
|
| 71 |
+
c_size_t(numbers_len)
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
if error == 17:
|
| 75 |
+
raise ExceptionModulus()
|
| 76 |
+
if error:
|
| 77 |
+
raise ValueError("monty_multiply() failed with error: %d" % error)
|
| 78 |
+
|
| 79 |
+
return get_raw_buffer(out)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
modulus1 = 0xd66691b20071be4d66d4b71032b37fa007cfabf579fcb91e50bfc2753b3f0ce7be74e216aef7e26d4ae180bc20d7bd3ea88a6cbf6f87380e613c8979b5b043b200a8ff8856a3b12875e36e98a7569f3852d028e967551000b02c19e9fa52e83115b89309aabb1e1cf1e2cb6369d637d46775ce4523ea31f64ad2794cbc365dd8a35e007ed3b57695877fbf102dbeb8b3212491398e494314e93726926e1383f8abb5889bea954eb8c0ca1c62c8e9d83f41888095c5e645ed6d32515fe0c58c1368cad84694e18da43668c6f43e61d7c9bca633ddcda7aef5b79bc396d4a9f48e2a9abe0836cc455e435305357228e93d25aaed46b952defae0f57339bf26f5a9
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TestModMultiply(unittest.TestCase):
|
| 86 |
+
|
| 87 |
+
def test_small(self):
|
| 88 |
+
self.assertEqual(b"\x01", monty_mult(5, 6, 29))
|
| 89 |
+
|
| 90 |
+
def test_large(self):
|
| 91 |
+
numbers_len = (modulus1.bit_length() + 7) // 8
|
| 92 |
+
|
| 93 |
+
t1 = modulus1 // 2
|
| 94 |
+
t2 = modulus1 - 90
|
| 95 |
+
expect = b'\x00' * (numbers_len - 1) + b'\x2d'
|
| 96 |
+
self.assertEqual(expect, monty_mult(t1, t2, modulus1))
|
| 97 |
+
|
| 98 |
+
def test_zero_term(self):
|
| 99 |
+
numbers_len = (modulus1.bit_length() + 7) // 8
|
| 100 |
+
expect = b'\x00' * numbers_len
|
| 101 |
+
self.assertEqual(expect, monty_mult(0x100, 0, modulus1))
|
| 102 |
+
self.assertEqual(expect, monty_mult(0, 0x100, modulus1))
|
| 103 |
+
|
| 104 |
+
def test_larger_term(self):
|
| 105 |
+
t1 = 2**2047
|
| 106 |
+
expect_int = 0x8edf4071f78e3d7ba622cdbbbef74612e301d69186776ae6bf87ff38c320d9aebaa64889c2f67de2324e6bccd2b10ad89e91fd21ba4bb523904d033eff5e70e62f01a84f41fa90a4f248ef249b82e1d2729253fdfc2a3b5b740198123df8bfbf7057d03e15244ad5f26eb9a099763b5c5972121ec076b0bf899f59bd95f7cc129abddccf24217bce52ca0f3a44c9ccc504765dbb89734205f3ae6a8cc560494a60ea84b27d8e00fa24bdd5b4f1d4232edb61e47d3d984c1fa50a3820a2e580fbc3fc8bc11e99df53b9efadf5a40ac75d384e400905aa6f1d88950cd53b1c54dc2222115ad84a27260fa4d978155c1434c551de1ee7361a17a2f79d4388f78a5d
|
| 107 |
+
res = bytes_to_long(monty_mult(t1, t1, modulus1))
|
| 108 |
+
self.assertEqual(res, expect_int)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def get_tests(config={}):
|
| 112 |
+
tests = []
|
| 113 |
+
tests += list_test_cases(TestModMultiply)
|
| 114 |
+
return tests
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == '__main__':
|
| 118 |
+
def suite():
|
| 119 |
+
return unittest.TestSuite(get_tests())
|
| 120 |
+
unittest.main(defaultTest='suite')
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# SelfTest/Protocol/__init__.py: Self-tests for Crypto.Protocol
|
| 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-test for Crypto.Protocol"""
|
| 26 |
+
|
| 27 |
+
__revision__ = "$Id$"
|
| 28 |
+
|
| 29 |
+
def get_tests(config={}):
|
| 30 |
+
tests = []
|
| 31 |
+
from Crypto.SelfTest.Protocol import test_rfc1751; tests += test_rfc1751.get_tests(config=config)
|
| 32 |
+
from Crypto.SelfTest.Protocol import test_KDF; tests += test_KDF.get_tests(config=config)
|
| 33 |
+
from Crypto.SelfTest.Protocol import test_ecdh; tests += test_ecdh.get_tests(config=config)
|
| 34 |
+
|
| 35 |
+
from Crypto.SelfTest.Protocol import test_SecretSharing;
|
| 36 |
+
tests += test_SecretSharing.get_tests(config=config)
|
| 37 |
+
|
| 38 |
+
return tests
|
| 39 |
+
|
| 40 |
+
if __name__ == '__main__':
|
| 41 |
+
import unittest
|
| 42 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 43 |
+
unittest.main(defaultTest='suite')
|
| 44 |
+
|
| 45 |
+
# vim:set ts=4 sw=4 sts=4 expandtab:
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (868 Bytes). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_KDF.cpython-310.pyc
ADDED
|
Binary file (28.5 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_SecretSharing.cpython-310.pyc
ADDED
|
Binary file (7.51 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_ecdh.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/__pycache__/test_rfc1751.cpython-310.pyc
ADDED
|
Binary file (1.57 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/test_KDF.py
ADDED
|
@@ -0,0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# SelfTest/Protocol/test_KDF.py: Self-test for key derivation functions
|
| 4 |
+
#
|
| 5 |
+
# ===================================================================
|
| 6 |
+
# The contents of this file are dedicated to the public domain. To
|
| 7 |
+
# the extent that dedication to the public domain is not available,
|
| 8 |
+
# everyone is granted a worldwide, perpetual, royalty-free,
|
| 9 |
+
# non-exclusive license to exercise all rights associated with the
|
| 10 |
+
# contents of this file for any purpose whatsoever.
|
| 11 |
+
# No rights are reserved.
|
| 12 |
+
#
|
| 13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 14 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 15 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 16 |
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
| 17 |
+
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
| 18 |
+
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 19 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
# SOFTWARE.
|
| 21 |
+
# ===================================================================
|
| 22 |
+
|
| 23 |
+
import re
|
| 24 |
+
import unittest
|
| 25 |
+
from binascii import unhexlify
|
| 26 |
+
|
| 27 |
+
from Crypto.Util.py3compat import b, bchr
|
| 28 |
+
|
| 29 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 30 |
+
from Crypto.SelfTest.loader import load_test_vectors, load_test_vectors_wycheproof
|
| 31 |
+
from Crypto.Hash import SHA1, HMAC, SHA256, MD5, SHA224, SHA384, SHA512
|
| 32 |
+
from Crypto.Cipher import AES, DES3
|
| 33 |
+
|
| 34 |
+
from Crypto.Protocol.KDF import (PBKDF1, PBKDF2, _S2V, HKDF, scrypt,
|
| 35 |
+
bcrypt, bcrypt_check,
|
| 36 |
+
SP800_108_Counter)
|
| 37 |
+
|
| 38 |
+
from Crypto.Protocol.KDF import _bcrypt_decode
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def t2b(t):
|
| 42 |
+
if t is None:
|
| 43 |
+
return None
|
| 44 |
+
t2 = t.replace(" ", "").replace("\n", "")
|
| 45 |
+
return unhexlify(b(t2))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestVector(object):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class PBKDF1_Tests(unittest.TestCase):
|
| 53 |
+
|
| 54 |
+
# List of tuples with test data.
|
| 55 |
+
# Each tuple is made up by:
|
| 56 |
+
# Item #0: a pass phrase
|
| 57 |
+
# Item #1: salt (8 bytes encoded in hex)
|
| 58 |
+
# Item #2: output key length
|
| 59 |
+
# Item #3: iterations to use
|
| 60 |
+
# Item #4: expected result (encoded in hex)
|
| 61 |
+
_testData = (
|
| 62 |
+
# From http://www.di-mgt.com.au/cryptoKDFs.html#examplespbkdf
|
| 63 |
+
("password", "78578E5A5D63CB06", 16, 1000, "DC19847E05C64D2FAF10EBFB4A3D2A20"),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def test1(self):
|
| 67 |
+
v = self._testData[0]
|
| 68 |
+
res = PBKDF1(v[0], t2b(v[1]), v[2], v[3], SHA1)
|
| 69 |
+
self.assertEqual(res, t2b(v[4]))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class PBKDF2_Tests(unittest.TestCase):
|
| 73 |
+
|
| 74 |
+
# List of tuples with test data.
|
| 75 |
+
# Each tuple is made up by:
|
| 76 |
+
# Item #0: a pass phrase
|
| 77 |
+
# Item #1: salt (encoded in hex)
|
| 78 |
+
# Item #2: output key length
|
| 79 |
+
# Item #3: iterations to use
|
| 80 |
+
# Item #4: hash module
|
| 81 |
+
# Item #5: expected result (encoded in hex)
|
| 82 |
+
_testData = (
|
| 83 |
+
# From http://www.di-mgt.com.au/cryptoKDFs.html#examplespbkdf
|
| 84 |
+
("password","78578E5A5D63CB06",24,2048, SHA1, "BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643"),
|
| 85 |
+
# From RFC 6050
|
| 86 |
+
("password","73616c74", 20, 1, SHA1, "0c60c80f961f0e71f3a9b524af6012062fe037a6"),
|
| 87 |
+
("password","73616c74", 20, 2, SHA1, "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
|
| 88 |
+
("password","73616c74", 20, 4096, SHA1, "4b007901b765489abead49d926f721d065a429c1"),
|
| 89 |
+
("passwordPASSWORDpassword","73616c7453414c5473616c7453414c5473616c7453414c5473616c7453414c5473616c74",
|
| 90 |
+
25, 4096, SHA1, "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"),
|
| 91 |
+
( 'pass\x00word',"7361006c74",16,4096, SHA1, "56fa6aa75548099dcc37d7f03425e0c3"),
|
| 92 |
+
# From draft-josefsson-scrypt-kdf-01, Chapter 10
|
| 93 |
+
( 'passwd', '73616c74', 64, 1, SHA256, "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783"),
|
| 94 |
+
( 'Password', '4e61436c', 64, 80000, SHA256, "4ddcd8f60b98be21830cee5ef22701f9641a4418d04c0414aeff08876b34ab56a1d425a1225833549adb841b51c9b3176a272bdebba1d078478f62b397f33c8d"),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def test1(self):
|
| 98 |
+
# Test only for HMAC-SHA1 as PRF
|
| 99 |
+
|
| 100 |
+
def prf_SHA1(p,s):
|
| 101 |
+
return HMAC.new(p,s,SHA1).digest()
|
| 102 |
+
|
| 103 |
+
def prf_SHA256(p,s):
|
| 104 |
+
return HMAC.new(p,s,SHA256).digest()
|
| 105 |
+
|
| 106 |
+
for i in range(len(self._testData)):
|
| 107 |
+
v = self._testData[i]
|
| 108 |
+
password = v[0]
|
| 109 |
+
salt = t2b(v[1])
|
| 110 |
+
out_len = v[2]
|
| 111 |
+
iters = v[3]
|
| 112 |
+
hash_mod = v[4]
|
| 113 |
+
expected = t2b(v[5])
|
| 114 |
+
|
| 115 |
+
if hash_mod is SHA1:
|
| 116 |
+
res = PBKDF2(password, salt, out_len, iters)
|
| 117 |
+
self.assertEqual(res, expected)
|
| 118 |
+
|
| 119 |
+
res = PBKDF2(password, salt, out_len, iters, prf_SHA1)
|
| 120 |
+
self.assertEqual(res, expected)
|
| 121 |
+
else:
|
| 122 |
+
res = PBKDF2(password, salt, out_len, iters, prf_SHA256)
|
| 123 |
+
self.assertEqual(res, expected)
|
| 124 |
+
|
| 125 |
+
def test2(self):
|
| 126 |
+
# Verify that prf and hmac_hash_module are mutual exclusive
|
| 127 |
+
def prf_SHA1(p,s):
|
| 128 |
+
return HMAC.new(p,s,SHA1).digest()
|
| 129 |
+
|
| 130 |
+
self.assertRaises(ValueError, PBKDF2, b("xxx"), b("yyy"), 16, 100,
|
| 131 |
+
prf=prf_SHA1, hmac_hash_module=SHA1)
|
| 132 |
+
|
| 133 |
+
def test3(self):
|
| 134 |
+
# Verify that hmac_hash_module works like prf
|
| 135 |
+
|
| 136 |
+
password = b("xxx")
|
| 137 |
+
salt = b("yyy")
|
| 138 |
+
|
| 139 |
+
for hashmod in (MD5, SHA1, SHA224, SHA256, SHA384, SHA512):
|
| 140 |
+
|
| 141 |
+
pr1 = PBKDF2(password, salt, 16, 100,
|
| 142 |
+
prf=lambda p, s: HMAC.new(p,s,hashmod).digest())
|
| 143 |
+
pr2 = PBKDF2(password, salt, 16, 100, hmac_hash_module=hashmod)
|
| 144 |
+
|
| 145 |
+
self.assertEqual(pr1, pr2)
|
| 146 |
+
|
| 147 |
+
def test4(self):
|
| 148 |
+
# Verify that PBKDF2 can take bytes or strings as password or salt
|
| 149 |
+
k1 = PBKDF2("xxx", b("yyy"), 16, 10)
|
| 150 |
+
k2 = PBKDF2(b("xxx"), b("yyy"), 16, 10)
|
| 151 |
+
self.assertEqual(k1, k2)
|
| 152 |
+
|
| 153 |
+
k1 = PBKDF2(b("xxx"), "yyy", 16, 10)
|
| 154 |
+
k2 = PBKDF2(b("xxx"), b("yyy"), 16, 10)
|
| 155 |
+
self.assertEqual(k1, k2)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class S2V_Tests(unittest.TestCase):
|
| 159 |
+
|
| 160 |
+
# Sequence of test vectors.
|
| 161 |
+
# Each test vector is made up by:
|
| 162 |
+
# Item #0: a tuple of strings
|
| 163 |
+
# Item #1: an AES key
|
| 164 |
+
# Item #2: the result
|
| 165 |
+
# Item #3: the cipher module S2V is based on
|
| 166 |
+
# Everything is hex encoded
|
| 167 |
+
_testData = [
|
| 168 |
+
|
| 169 |
+
# RFC5297, A.1
|
| 170 |
+
(
|
| 171 |
+
( '101112131415161718191a1b1c1d1e1f2021222324252627',
|
| 172 |
+
'112233445566778899aabbccddee' ),
|
| 173 |
+
'fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0',
|
| 174 |
+
'85632d07c6e8f37f950acd320a2ecc93',
|
| 175 |
+
AES
|
| 176 |
+
),
|
| 177 |
+
|
| 178 |
+
# RFC5297, A.2
|
| 179 |
+
(
|
| 180 |
+
( '00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddcc'+
|
| 181 |
+
'bbaa99887766554433221100',
|
| 182 |
+
'102030405060708090a0',
|
| 183 |
+
'09f911029d74e35bd84156c5635688c0',
|
| 184 |
+
'7468697320697320736f6d6520706c61'+
|
| 185 |
+
'696e7465787420746f20656e63727970'+
|
| 186 |
+
'74207573696e67205349562d414553'),
|
| 187 |
+
'7f7e7d7c7b7a79787776757473727170',
|
| 188 |
+
'7bdb6e3b432667eb06f4d14bff2fbd0f',
|
| 189 |
+
AES
|
| 190 |
+
),
|
| 191 |
+
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
def test1(self):
|
| 195 |
+
"""Verify correctness of test vector"""
|
| 196 |
+
for tv in self._testData:
|
| 197 |
+
s2v = _S2V.new(t2b(tv[1]), tv[3])
|
| 198 |
+
for s in tv[0]:
|
| 199 |
+
s2v.update(t2b(s))
|
| 200 |
+
result = s2v.derive()
|
| 201 |
+
self.assertEqual(result, t2b(tv[2]))
|
| 202 |
+
|
| 203 |
+
def test2(self):
|
| 204 |
+
"""Verify that no more than 127(AES) and 63(TDES)
|
| 205 |
+
components are accepted."""
|
| 206 |
+
key = bchr(0) * 8 + bchr(255) * 8
|
| 207 |
+
for module in (AES, DES3):
|
| 208 |
+
s2v = _S2V.new(key, module)
|
| 209 |
+
max_comps = module.block_size*8-1
|
| 210 |
+
for i in range(max_comps):
|
| 211 |
+
s2v.update(b("XX"))
|
| 212 |
+
self.assertRaises(TypeError, s2v.update, b("YY"))
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class HKDF_Tests(unittest.TestCase):
|
| 216 |
+
|
| 217 |
+
# Test vectors from RFC5869, Appendix A
|
| 218 |
+
# Each tuple is made up by:
|
| 219 |
+
# Item #0: hash module
|
| 220 |
+
# Item #1: secret
|
| 221 |
+
# Item #2: salt
|
| 222 |
+
# Item #3: context
|
| 223 |
+
# Item #4: expected result
|
| 224 |
+
_test_vector = (
|
| 225 |
+
(
|
| 226 |
+
SHA256,
|
| 227 |
+
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
|
| 228 |
+
"000102030405060708090a0b0c",
|
| 229 |
+
"f0f1f2f3f4f5f6f7f8f9",
|
| 230 |
+
42,
|
| 231 |
+
"3cb25f25faacd57a90434f64d0362f2a" +
|
| 232 |
+
"2d2d0a90cf1a5a4c5db02d56ecc4c5bf" +
|
| 233 |
+
"34007208d5b887185865"
|
| 234 |
+
),
|
| 235 |
+
(
|
| 236 |
+
SHA256,
|
| 237 |
+
"000102030405060708090a0b0c0d0e0f" +
|
| 238 |
+
"101112131415161718191a1b1c1d1e1f" +
|
| 239 |
+
"202122232425262728292a2b2c2d2e2f" +
|
| 240 |
+
"303132333435363738393a3b3c3d3e3f" +
|
| 241 |
+
"404142434445464748494a4b4c4d4e4f",
|
| 242 |
+
"606162636465666768696a6b6c6d6e6f" +
|
| 243 |
+
"707172737475767778797a7b7c7d7e7f" +
|
| 244 |
+
"808182838485868788898a8b8c8d8e8f" +
|
| 245 |
+
"909192939495969798999a9b9c9d9e9f" +
|
| 246 |
+
"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf",
|
| 247 |
+
"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" +
|
| 248 |
+
"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" +
|
| 249 |
+
"d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" +
|
| 250 |
+
"e0e1e2e3e4e5e6e7e8e9eaebecedeeef" +
|
| 251 |
+
"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
|
| 252 |
+
82,
|
| 253 |
+
"b11e398dc80327a1c8e7f78c596a4934" +
|
| 254 |
+
"4f012eda2d4efad8a050cc4c19afa97c" +
|
| 255 |
+
"59045a99cac7827271cb41c65e590e09" +
|
| 256 |
+
"da3275600c2f09b8367793a9aca3db71" +
|
| 257 |
+
"cc30c58179ec3e87c14c01d5c1f3434f" +
|
| 258 |
+
"1d87"
|
| 259 |
+
),
|
| 260 |
+
(
|
| 261 |
+
SHA256,
|
| 262 |
+
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
|
| 263 |
+
None,
|
| 264 |
+
None,
|
| 265 |
+
42,
|
| 266 |
+
"8da4e775a563c18f715f802a063c5a31" +
|
| 267 |
+
"b8a11f5c5ee1879ec3454e5f3c738d2d" +
|
| 268 |
+
"9d201395faa4b61a96c8"
|
| 269 |
+
),
|
| 270 |
+
(
|
| 271 |
+
SHA1,
|
| 272 |
+
"0b0b0b0b0b0b0b0b0b0b0b",
|
| 273 |
+
"000102030405060708090a0b0c",
|
| 274 |
+
"f0f1f2f3f4f5f6f7f8f9",
|
| 275 |
+
42,
|
| 276 |
+
"085a01ea1b10f36933068b56efa5ad81" +
|
| 277 |
+
"a4f14b822f5b091568a9cdd4f155fda2" +
|
| 278 |
+
"c22e422478d305f3f896"
|
| 279 |
+
),
|
| 280 |
+
(
|
| 281 |
+
SHA1,
|
| 282 |
+
"000102030405060708090a0b0c0d0e0f" +
|
| 283 |
+
"101112131415161718191a1b1c1d1e1f" +
|
| 284 |
+
"202122232425262728292a2b2c2d2e2f" +
|
| 285 |
+
"303132333435363738393a3b3c3d3e3f" +
|
| 286 |
+
"404142434445464748494a4b4c4d4e4f",
|
| 287 |
+
"606162636465666768696a6b6c6d6e6f" +
|
| 288 |
+
"707172737475767778797a7b7c7d7e7f" +
|
| 289 |
+
"808182838485868788898a8b8c8d8e8f" +
|
| 290 |
+
"909192939495969798999a9b9c9d9e9f" +
|
| 291 |
+
"a0a1a2a3a4a5a6a7a8a9aaabacadaeaf",
|
| 292 |
+
"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" +
|
| 293 |
+
"c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" +
|
| 294 |
+
"d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" +
|
| 295 |
+
"e0e1e2e3e4e5e6e7e8e9eaebecedeeef" +
|
| 296 |
+
"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
|
| 297 |
+
82,
|
| 298 |
+
"0bd770a74d1160f7c9f12cd5912a06eb" +
|
| 299 |
+
"ff6adcae899d92191fe4305673ba2ffe" +
|
| 300 |
+
"8fa3f1a4e5ad79f3f334b3b202b2173c" +
|
| 301 |
+
"486ea37ce3d397ed034c7f9dfeb15c5e" +
|
| 302 |
+
"927336d0441f4c4300e2cff0d0900b52" +
|
| 303 |
+
"d3b4"
|
| 304 |
+
),
|
| 305 |
+
(
|
| 306 |
+
SHA1,
|
| 307 |
+
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
|
| 308 |
+
"",
|
| 309 |
+
"",
|
| 310 |
+
42,
|
| 311 |
+
"0ac1af7002b3d761d1e55298da9d0506" +
|
| 312 |
+
"b9ae52057220a306e07b6b87e8df21d0" +
|
| 313 |
+
"ea00033de03984d34918"
|
| 314 |
+
),
|
| 315 |
+
(
|
| 316 |
+
SHA1,
|
| 317 |
+
"0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c",
|
| 318 |
+
None,
|
| 319 |
+
"",
|
| 320 |
+
42,
|
| 321 |
+
"2c91117204d745f3500d636a62f64f0a" +
|
| 322 |
+
"b3bae548aa53d423b0d1f27ebba6f5e5" +
|
| 323 |
+
"673a081d70cce7acfc48"
|
| 324 |
+
)
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
def test1(self):
|
| 328 |
+
for tv in self._test_vector:
|
| 329 |
+
secret, salt, info, exp = [ t2b(tv[x]) for x in (1,2,3,5) ]
|
| 330 |
+
key_len, hashmod = [ tv[x] for x in (4,0) ]
|
| 331 |
+
|
| 332 |
+
output = HKDF(secret, key_len, salt, hashmod, 1, info)
|
| 333 |
+
self.assertEqual(output, exp)
|
| 334 |
+
|
| 335 |
+
def test2(self):
|
| 336 |
+
ref = HKDF(b("XXXXXX"), 12, b("YYYY"), SHA1)
|
| 337 |
+
|
| 338 |
+
# Same output, but this time split over 2 keys
|
| 339 |
+
key1, key2 = HKDF(b("XXXXXX"), 6, b("YYYY"), SHA1, 2)
|
| 340 |
+
self.assertEqual((ref[:6], ref[6:]), (key1, key2))
|
| 341 |
+
|
| 342 |
+
# Same output, but this time split over 3 keys
|
| 343 |
+
key1, key2, key3 = HKDF(b("XXXXXX"), 4, b("YYYY"), SHA1, 3)
|
| 344 |
+
self.assertEqual((ref[:4], ref[4:8], ref[8:]), (key1, key2, key3))
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class scrypt_Tests(unittest.TestCase):
|
| 348 |
+
|
| 349 |
+
# Test vectors taken from
|
| 350 |
+
# https://tools.ietf.org/html/rfc7914
|
| 351 |
+
# - password
|
| 352 |
+
# - salt
|
| 353 |
+
# - N
|
| 354 |
+
# - r
|
| 355 |
+
# - p
|
| 356 |
+
data = (
|
| 357 |
+
(
|
| 358 |
+
"",
|
| 359 |
+
"",
|
| 360 |
+
16, # 2K
|
| 361 |
+
1,
|
| 362 |
+
1,
|
| 363 |
+
"""
|
| 364 |
+
77 d6 57 62 38 65 7b 20 3b 19 ca 42 c1 8a 04 97
|
| 365 |
+
f1 6b 48 44 e3 07 4a e8 df df fa 3f ed e2 14 42
|
| 366 |
+
fc d0 06 9d ed 09 48 f8 32 6a 75 3a 0f c8 1f 17
|
| 367 |
+
e8 d3 e0 fb 2e 0d 36 28 cf 35 e2 0c 38 d1 89 06
|
| 368 |
+
"""
|
| 369 |
+
),
|
| 370 |
+
(
|
| 371 |
+
"password",
|
| 372 |
+
"NaCl",
|
| 373 |
+
1024, # 1M
|
| 374 |
+
8,
|
| 375 |
+
16,
|
| 376 |
+
"""
|
| 377 |
+
fd ba be 1c 9d 34 72 00 78 56 e7 19 0d 01 e9 fe
|
| 378 |
+
7c 6a d7 cb c8 23 78 30 e7 73 76 63 4b 37 31 62
|
| 379 |
+
2e af 30 d9 2e 22 a3 88 6f f1 09 27 9d 98 30 da
|
| 380 |
+
c7 27 af b9 4a 83 ee 6d 83 60 cb df a2 cc 06 40
|
| 381 |
+
"""
|
| 382 |
+
),
|
| 383 |
+
(
|
| 384 |
+
"pleaseletmein",
|
| 385 |
+
"SodiumChloride",
|
| 386 |
+
16384, # 16M
|
| 387 |
+
8,
|
| 388 |
+
1,
|
| 389 |
+
"""
|
| 390 |
+
70 23 bd cb 3a fd 73 48 46 1c 06 cd 81 fd 38 eb
|
| 391 |
+
fd a8 fb ba 90 4f 8e 3e a9 b5 43 f6 54 5d a1 f2
|
| 392 |
+
d5 43 29 55 61 3f 0f cf 62 d4 97 05 24 2a 9a f9
|
| 393 |
+
e6 1e 85 dc 0d 65 1e 40 df cf 01 7b 45 57 58 87
|
| 394 |
+
"""
|
| 395 |
+
),
|
| 396 |
+
(
|
| 397 |
+
"pleaseletmein",
|
| 398 |
+
"SodiumChloride",
|
| 399 |
+
1048576, # 1G
|
| 400 |
+
8,
|
| 401 |
+
1,
|
| 402 |
+
"""
|
| 403 |
+
21 01 cb 9b 6a 51 1a ae ad db be 09 cf 70 f8 81
|
| 404 |
+
ec 56 8d 57 4a 2f fd 4d ab e5 ee 98 20 ad aa 47
|
| 405 |
+
8e 56 fd 8f 4b a5 d0 9f fa 1c 6d 92 7c 40 f4 c3
|
| 406 |
+
37 30 40 49 e8 a9 52 fb cb f4 5c 6f a7 7a 41 a4
|
| 407 |
+
"""
|
| 408 |
+
),
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
def setUp(self):
|
| 412 |
+
new_test_vectors = []
|
| 413 |
+
for tv in self.data:
|
| 414 |
+
new_tv = TestVector()
|
| 415 |
+
new_tv.P = b(tv[0])
|
| 416 |
+
new_tv.S = b(tv[1])
|
| 417 |
+
new_tv.N = tv[2]
|
| 418 |
+
new_tv.r = tv[3]
|
| 419 |
+
new_tv.p = tv[4]
|
| 420 |
+
new_tv.output = t2b(tv[5])
|
| 421 |
+
new_tv.dkLen = len(new_tv.output)
|
| 422 |
+
new_test_vectors.append(new_tv)
|
| 423 |
+
self.data = new_test_vectors
|
| 424 |
+
|
| 425 |
+
def test2(self):
|
| 426 |
+
|
| 427 |
+
for tv in self.data:
|
| 428 |
+
try:
|
| 429 |
+
output = scrypt(tv.P, tv.S, tv.dkLen, tv.N, tv.r, tv.p)
|
| 430 |
+
except ValueError as e:
|
| 431 |
+
if " 2 " in str(e) and tv.N >= 1048576:
|
| 432 |
+
import warnings
|
| 433 |
+
warnings.warn("Not enough memory to unit test scrypt() with N=1048576", RuntimeWarning)
|
| 434 |
+
continue
|
| 435 |
+
else:
|
| 436 |
+
raise e
|
| 437 |
+
self.assertEqual(output, tv.output)
|
| 438 |
+
|
| 439 |
+
def test3(self):
|
| 440 |
+
ref = scrypt(b("password"), b("salt"), 12, 16, 1, 1)
|
| 441 |
+
|
| 442 |
+
# Same output, but this time split over 2 keys
|
| 443 |
+
key1, key2 = scrypt(b("password"), b("salt"), 6, 16, 1, 1, 2)
|
| 444 |
+
self.assertEqual((ref[:6], ref[6:]), (key1, key2))
|
| 445 |
+
|
| 446 |
+
# Same output, but this time split over 3 keys
|
| 447 |
+
key1, key2, key3 = scrypt(b("password"), b("salt"), 4, 16, 1, 1, 3)
|
| 448 |
+
self.assertEqual((ref[:4], ref[4:8], ref[8:]), (key1, key2, key3))
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class bcrypt_Tests(unittest.TestCase):
|
| 452 |
+
|
| 453 |
+
def test_negative_cases(self):
|
| 454 |
+
self.assertRaises(ValueError, bcrypt, b"1" * 73, 10)
|
| 455 |
+
self.assertRaises(ValueError, bcrypt, b"1" * 10, 3)
|
| 456 |
+
self.assertRaises(ValueError, bcrypt, b"1" * 10, 32)
|
| 457 |
+
self.assertRaises(ValueError, bcrypt, b"1" * 10, 4, salt=b"")
|
| 458 |
+
self.assertRaises(ValueError, bcrypt, b"1" * 10, 4, salt=b"1")
|
| 459 |
+
self.assertRaises(ValueError, bcrypt, b"1" * 10, 4, salt=b"1" * 17)
|
| 460 |
+
self.assertRaises(ValueError, bcrypt, b"1\x00" * 10, 4)
|
| 461 |
+
|
| 462 |
+
def test_bytearray_mismatch(self):
|
| 463 |
+
ref = bcrypt("pwd", 4)
|
| 464 |
+
bcrypt_check("pwd", ref)
|
| 465 |
+
bref = bytearray(ref)
|
| 466 |
+
bcrypt_check("pwd", bref)
|
| 467 |
+
|
| 468 |
+
wrong = ref[:-1] + bchr(bref[-1] ^ 0x01)
|
| 469 |
+
self.assertRaises(ValueError, bcrypt_check, "pwd", wrong)
|
| 470 |
+
|
| 471 |
+
wrong = b"x" + ref[1:]
|
| 472 |
+
self.assertRaises(ValueError, bcrypt_check, "pwd", wrong)
|
| 473 |
+
|
| 474 |
+
# https://github.com/patrickfav/bcrypt/wiki/Published-Test-Vectors
|
| 475 |
+
|
| 476 |
+
def test_empty_password(self):
|
| 477 |
+
# password, cost, salt, bcrypt hash
|
| 478 |
+
tvs = [
|
| 479 |
+
(b"", 4, b"zVHmKQtGGQob.b/Nc7l9NO", b"$2a$04$zVHmKQtGGQob.b/Nc7l9NO8UlrYcW05FiuCj/SxsFO/ZtiN9.mNzy"),
|
| 480 |
+
(b"", 5, b"zVHmKQtGGQob.b/Nc7l9NO", b"$2a$05$zVHmKQtGGQob.b/Nc7l9NOWES.1hkVBgy5IWImh9DOjKNU8atY4Iy"),
|
| 481 |
+
(b"", 6, b"zVHmKQtGGQob.b/Nc7l9NO", b"$2a$06$zVHmKQtGGQob.b/Nc7l9NOjOl7l4oz3WSh5fJ6414Uw8IXRAUoiaO"),
|
| 482 |
+
(b"", 7, b"zVHmKQtGGQob.b/Nc7l9NO", b"$2a$07$zVHmKQtGGQob.b/Nc7l9NOBsj1dQpBA1HYNGpIETIByoNX9jc.hOi"),
|
| 483 |
+
(b"", 8, b"zVHmKQtGGQob.b/Nc7l9NO", b"$2a$08$zVHmKQtGGQob.b/Nc7l9NOiLTUh/9MDpX86/DLyEzyiFjqjBFePgO"),
|
| 484 |
+
]
|
| 485 |
+
|
| 486 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 487 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 488 |
+
self.assertEqual(x, result)
|
| 489 |
+
bcrypt_check(password, result)
|
| 490 |
+
|
| 491 |
+
def test_random_password_and_salt_short_pw(self):
|
| 492 |
+
# password, cost, salt, bcrypt hash
|
| 493 |
+
tvs = [
|
| 494 |
+
(b"<.S.2K(Zq'", 4, b"VYAclAMpaXY/oqAo9yUpku", b"$2a$04$VYAclAMpaXY/oqAo9yUpkuWmoYywaPzyhu56HxXpVltnBIfmO9tgu"),
|
| 495 |
+
(b"5.rApO%5jA", 5, b"kVNDrnYKvbNr5AIcxNzeIu", b"$2a$05$kVNDrnYKvbNr5AIcxNzeIuRcyIF5cZk6UrwHGxENbxP5dVv.WQM/G"),
|
| 496 |
+
(b"oW++kSrQW^", 6, b"QLKkRMH9Am6irtPeSKN5sO", b"$2a$06$QLKkRMH9Am6irtPeSKN5sObJGr3j47cO6Pdf5JZ0AsJXuze0IbsNm"),
|
| 497 |
+
(b"ggJ\\KbTnDG", 7, b"4H896R09bzjhapgCPS/LYu", b"$2a$07$4H896R09bzjhapgCPS/LYuMzAQluVgR5iu/ALF8L8Aln6lzzYXwbq"),
|
| 498 |
+
(b"49b0:;VkH/", 8, b"hfvO2retKrSrx5f2RXikWe", b"$2a$08$hfvO2retKrSrx5f2RXikWeFWdtSesPlbj08t/uXxCeZoHRWDz/xFe"),
|
| 499 |
+
(b">9N^5jc##'", 9, b"XZLvl7rMB3EvM0c1.JHivu", b"$2a$09$XZLvl7rMB3EvM0c1.JHivuIDPJWeNJPTVrpjZIEVRYYB/mF6cYgJK"),
|
| 500 |
+
(b"\\$ch)s4WXp", 10, b"aIjpMOLK5qiS9zjhcHR5TO", b"$2a$10$aIjpMOLK5qiS9zjhcHR5TOU7v2NFDmcsBmSFDt5EHOgp/jeTF3O/q"),
|
| 501 |
+
(b"RYoj\\_>2P7", 12, b"esIAHiQAJNNBrsr5V13l7.", b"$2a$12$esIAHiQAJNNBrsr5V13l7.RFWWJI2BZFtQlkFyiWXjou05GyuREZa"),
|
| 502 |
+
]
|
| 503 |
+
|
| 504 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 505 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 506 |
+
self.assertEqual(x, result)
|
| 507 |
+
bcrypt_check(password, result)
|
| 508 |
+
|
| 509 |
+
def test_random_password_and_salt_long_pw(self):
|
| 510 |
+
# password, cost, salt, bcrypt hash
|
| 511 |
+
tvs = [
|
| 512 |
+
(b"^Q&\"]A`%/A(BVGt>QaX0M-#<Q148&f", 4, b"vrRP5vQxyD4LrqiLd/oWRO", b"$2a$04$vrRP5vQxyD4LrqiLd/oWROgrrGINsw3gb4Ga5x2sn01jNmiLVECl6"),
|
| 513 |
+
(b"nZa!rRf\\U;OL;R?>1ghq_+\":Y0CRmY", 5, b"YuQvhokOGVnevctykUYpKu", b"$2a$05$YuQvhokOGVnevctykUYpKutZD2pWeGGYn3auyLOasguMY3/0BbIyq"),
|
| 514 |
+
(b"F%uN/j>[GuB7-jB'_Yj!Tnb7Y!u^6)", 6, b"5L3vpQ0tG9O7k5gQ8nAHAe", b"$2a$06$5L3vpQ0tG9O7k5gQ8nAHAe9xxQiOcOLh8LGcI0PLWhIznsDt.S.C6"),
|
| 515 |
+
(b"Z>BobP32ub\"Cfe*Q<<WUq3rc=[GJr-", 7, b"hp8IdLueqE6qFh1zYycUZ.", b"$2a$07$hp8IdLueqE6qFh1zYycUZ.twmUH8eSTPQAEpdNXKMlwms9XfKqfea"),
|
| 516 |
+
(b"Ik&8N['7*[1aCc1lOm8\\jWeD*H$eZM", 8, b"2ANDTYCB9m7vf0Prh7rSru", b"$2a$08$2ANDTYCB9m7vf0Prh7rSrupqpO3jJOkIz2oW/QHB4lCmK7qMytGV6"),
|
| 517 |
+
(b"O)=%3[E$*q+>-q-=tRSjOBh8\\mLNW.", 9, b"nArqOfdCsD9kIbVnAixnwe", b"$2a$09$nArqOfdCsD9kIbVnAixnwe6s8QvyPYWtQBpEXKir2OJF9/oNBsEFe"),
|
| 518 |
+
(b"/MH51`!BP&0tj3%YCA;Xk%e3S`o\\EI", 10, b"ePiAc.s.yoBi3B6p1iQUCe", b"$2a$10$ePiAc.s.yoBi3B6p1iQUCezn3mraLwpVJ5XGelVyYFKyp5FZn/y.u"),
|
| 519 |
+
(b"ptAP\"mcg6oH.\";c0U2_oll.OKi<!ku", 12, b"aroG/pwwPj1tU5fl9a9pkO", b"$2a$12$aroG/pwwPj1tU5fl9a9pkO4rydAmkXRj/LqfHZOSnR6LGAZ.z.jwa"),
|
| 520 |
+
]
|
| 521 |
+
|
| 522 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 523 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 524 |
+
self.assertEqual(x, result)
|
| 525 |
+
bcrypt_check(password, result)
|
| 526 |
+
|
| 527 |
+
def test_same_password_and_random_salt(self):
|
| 528 |
+
# password, cost, salt, bcrypt hash
|
| 529 |
+
tvs = [
|
| 530 |
+
(b"Q/A:k3DP;X@=<0\"hg&9c", 4, b"wbgDTvLMtyjQlNK7fjqwyO", b"$2a$04$wbgDTvLMtyjQlNK7fjqwyOakBoACQuYh11.VsKNarF4xUIOBWgD6S"),
|
| 531 |
+
(b"Q/A:k3DP;X@=<0\"hg&9c", 5, b"zbAaOmloOhxiKItjznRqru", b"$2a$05$zbAaOmloOhxiKItjznRqrunRqHlu3MAa7pMGv26Rr3WwyfGcwoRm6"),
|
| 532 |
+
(b"Q/A:k3DP;X@=<0\"hg&9c", 6, b"aOK0bWUvLI0qLkc3ti5jyu", b"$2a$06$aOK0bWUvLI0qLkc3ti5jyuAIQoqRzuqoK09kQqQ6Ou/YKDhW50/qa"),
|
| 533 |
+
]
|
| 534 |
+
|
| 535 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 536 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 537 |
+
self.assertEqual(x, result)
|
| 538 |
+
bcrypt_check(password, result)
|
| 539 |
+
|
| 540 |
+
def test_same_password_and_salt_increasing_cost_factor(self):
|
| 541 |
+
# password, cost, salt, bcrypt hash
|
| 542 |
+
tvs = [
|
| 543 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 4, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$04$BK5u.QHk1Driey7bvnFTH.3smGwxd91PtoK2GxH5nZ7pcBsYX4lMq"),
|
| 544 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 5, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$05$BK5u.QHk1Driey7bvnFTH.t5P.jZvFBMzDB1IY4PwkkRPOyVbEtFG"),
|
| 545 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 6, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$06$BK5u.QHk1Driey7bvnFTH.6Ea1Z5db2p25CPXZbxb/3OyKQagg3pa"),
|
| 546 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 7, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$07$BK5u.QHk1Driey7bvnFTH.sruuQi8Lhv/0LWKDvNp3AGFk7ltdkm6"),
|
| 547 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 8, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$08$BK5u.QHk1Driey7bvnFTH.IE7KsaUzc4m7gzAMlyUPUeiYyACWe0q"),
|
| 548 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 9, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$09$BK5u.QHk1Driey7bvnFTH.1v4Xj1dwkp44QNg0cVAoQt4FQMMrvnS"),
|
| 549 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 10, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$10$BK5u.QHk1Driey7bvnFTH.ESINe9YntUMcVgFDfkC.Vbhc9vMhNX2"),
|
| 550 |
+
(b"o<&+X'F4AQ8H,LU,N`&r", 12, b"BK5u.QHk1Driey7bvnFTH.", b"$2a$12$BK5u.QHk1Driey7bvnFTH.QM1/nnGe/f5cTzb6XTTi/vMzcAnycqG"),
|
| 551 |
+
]
|
| 552 |
+
|
| 553 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 554 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 555 |
+
self.assertEqual(x, result)
|
| 556 |
+
bcrypt_check(password, result)
|
| 557 |
+
|
| 558 |
+
def test_long_passwords(self):
|
| 559 |
+
# password, cost, salt, bcrypt hash
|
| 560 |
+
tvs = [
|
| 561 |
+
(b"g*3Q45=\"8NNgpT&mbMJ$Omfr.#ZeW?FP=CE$#roHd?97uL0F-]`?u73c\"\\[.\"*)qU34@VG",
|
| 562 |
+
4, b"T2XJ5MOWvHQZRijl8LIKkO", b"$2a$04$T2XJ5MOWvHQZRijl8LIKkOQKIyX75KBfuLsuRYOJz5OjwBNF2lM8a"),
|
| 563 |
+
(b"\\M+*8;&QE=Ll[>5?Ui\"^ai#iQH7ZFtNMfs3AROnIncE9\"BNNoEgO[[*Yk8;RQ(#S,;I+aT",
|
| 564 |
+
5, b"wgkOlGNXIVE2fWkT3gyRoO", b"$2a$05$wgkOlGNXIVE2fWkT3gyRoOqWi4gbi1Wv2Q2Jx3xVs3apl1w.Wtj8C"),
|
| 565 |
+
(b"M.E1=dt<.L0Q&p;94NfGm_Oo23+Kpl@M5?WIAL.[@/:'S)W96G8N^AWb7_smmC]>7#fGoB",
|
| 566 |
+
6, b"W9zTCl35nEvUukhhFzkKMe", b"$2a$06$W9zTCl35nEvUukhhFzkKMekjT9/pj7M0lihRVEZrX3m8/SBNZRX7i"),
|
| 567 |
+
]
|
| 568 |
+
|
| 569 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 570 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 571 |
+
self.assertEqual(x, result)
|
| 572 |
+
bcrypt_check(password, result)
|
| 573 |
+
|
| 574 |
+
def test_increasing_password_length(self):
|
| 575 |
+
# password, cost, salt, bcrypt hash
|
| 576 |
+
tvs = [
|
| 577 |
+
(b"a", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.l4WvgHIVg17ZawDIrDM2IjlE64GDNQS"),
|
| 578 |
+
(b"aa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.AyUxBk.ThHlsLvRTH7IqcG7yVHJ3SXq"),
|
| 579 |
+
(b"aaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.BxOVac5xPB6XFdRc/ZrzM9FgZkqmvbW"),
|
| 580 |
+
(b"aaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.Qbr209bpCtfl5hN7UQlG/L4xiD3AKau"),
|
| 581 |
+
(b"aaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.oWszihPjDZI0ypReKsaDOW1jBl7oOii"),
|
| 582 |
+
(b"aaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ./k.Xxn9YiqtV/sxh3EHbnOHd0Qsq27K"),
|
| 583 |
+
(b"aaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.PYJqRFQbgRbIjMd5VNKmdKS4sBVOyDe"),
|
| 584 |
+
(b"aaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ..VMYfzaw1wP/SGxowpLeGf13fxCCt.q"),
|
| 585 |
+
(b"aaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.5B0p054nO5WgAD1n04XslDY/bqY9RJi"),
|
| 586 |
+
(b"aaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.INBTgqm7sdlBJDg.J5mLMSRK25ri04y"),
|
| 587 |
+
(b"aaaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.s3y7CdFD0OR5p6rsZw/eZ.Dla40KLfm"),
|
| 588 |
+
(b"aaaaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.Jx742Djra6Q7PqJWnTAS.85c28g.Siq"),
|
| 589 |
+
(b"aaaaaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.oKMXW3EZcPHcUV0ib5vDBnh9HojXnLu"),
|
| 590 |
+
(b"aaaaaaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.w6nIjWpDPNSH5pZUvLjC1q25ONEQpeS"),
|
| 591 |
+
(b"aaaaaaaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.k1b2/r9A/hxdwKEKurg6OCn4MwMdiGq"),
|
| 592 |
+
(b"aaaaaaaaaaaaaaaa", 4, b"5DCebwootqWMCp59ISrMJ.", b"$2a$04$5DCebwootqWMCp59ISrMJ.3prCNHVX1Ws.7Hm2bJxFUnQOX9f7DFa"),
|
| 593 |
+
]
|
| 594 |
+
|
| 595 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 596 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 597 |
+
self.assertEqual(x, result)
|
| 598 |
+
bcrypt_check(password, result)
|
| 599 |
+
|
| 600 |
+
def test_non_ascii_characters(self):
|
| 601 |
+
# password, cost, salt, bcrypt hash
|
| 602 |
+
tvs = [
|
| 603 |
+
("àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝðÐ", 4, b"D3qS2aoTVyqM7z8v8crLm.", b"$2a$04$D3qS2aoTVyqM7z8v8crLm.3nKt4CzBZJbyFB.ZebmfCvRw7BGs.Xm"),
|
| 604 |
+
("àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝðÐ", 5, b"VA1FujiOCMPkUHQ8kF7IaO", b"$2a$05$VA1FujiOCMPkUHQ8kF7IaOg7NGaNvpxwWzSluQutxEVmbZItRTsAa"),
|
| 605 |
+
("àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝðÐ", 6, b"TXiaNrPeBSz5ugiQlehRt.", b"$2a$06$TXiaNrPeBSz5ugiQlehRt.gwpeDQnXWteQL4z2FulouBr6G7D9KUi"),
|
| 606 |
+
("âêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿ", 4, b"YTn1Qlvps8e1odqMn6G5x.", b"$2a$04$YTn1Qlvps8e1odqMn6G5x.85pqKql6w773EZJAExk7/BatYAI4tyO"),
|
| 607 |
+
("âêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿ", 5, b"C.8k5vJKD2NtfrRI9o17DO", b"$2a$05$C.8k5vJKD2NtfrRI9o17DOfIW0XnwItA529vJnh2jzYTb1QdoY0py"),
|
| 608 |
+
("âêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿ", 6, b"xqfRPj3RYAgwurrhcA6uRO", b"$2a$06$xqfRPj3RYAgwurrhcA6uROtGlXDp/U6/gkoDYHwlubtcVcNft5.vW"),
|
| 609 |
+
("ÄËÏÖÜŸåÅæÆœŒßçÇøØ¢¿¡€", 4, b"y8vGgMmr9EdyxP9rmMKjH.", b"$2a$04$y8vGgMmr9EdyxP9rmMKjH.wv2y3r7yRD79gykQtmb3N3zrwjKsyay"),
|
| 610 |
+
("ÄËÏÖÜŸåÅæÆœŒßçÇøØ¢¿¡€", 5, b"iYH4XIKAOOm/xPQs7xKP1u", b"$2a$05$iYH4XIKAOOm/xPQs7xKP1upD0cWyMn3Jf0ZWiizXbEkVpS41K1dcO"),
|
| 611 |
+
("ÄËÏÖÜŸåÅæÆœŒßçÇøØ¢¿¡€", 6, b"wCOob.D0VV8twafNDB2ape", b"$2a$06$wCOob.D0VV8twafNDB2apegiGD5nqF6Y1e6K95q6Y.R8C4QGd265q"),
|
| 612 |
+
("ΔημοσιεύθηκεστηνΕφημερίδατης", 4, b"E5SQtS6P4568MDXW7cyUp.", b"$2a$04$E5SQtS6P4568MDXW7cyUp.18wfDisKZBxifnPZjAI1d/KTYMfHPYO"),
|
| 613 |
+
("АБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмН", 4, b"03e26gQFHhQwRNf81/ww9.", b"$2a$04$03e26gQFHhQwRNf81/ww9.p1UbrNwxpzWjLuT.zpTLH4t/w5WhAhC"),
|
| 614 |
+
("нОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮю", 4, b"PHNoJwpXCfe32nUtLv2Upu", b"$2a$04$PHNoJwpXCfe32nUtLv2UpuhJXOzd4k7IdFwnEpYwfJVCZ/f/.8Pje"),
|
| 615 |
+
("電电電島岛島兔兔兎龜龟亀國国国區区区", 4, b"wU4/0i1TmNl2u.1jIwBX.u", b"$2a$04$wU4/0i1TmNl2u.1jIwBX.uZUaOL3Rc5ID7nlQRloQh6q5wwhV/zLW"),
|
| 616 |
+
("诶比伊艾弗豆贝尔维吾艾尺开艾丝维贼德", 4, b"P4kreGLhCd26d4WIy7DJXu", b"$2a$04$P4kreGLhCd26d4WIy7DJXusPkhxLvBouzV6OXkL5EB0jux0osjsry"),
|
| 617 |
+
]
|
| 618 |
+
|
| 619 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 620 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 621 |
+
self.assertEqual(x, result)
|
| 622 |
+
bcrypt_check(password, result)
|
| 623 |
+
|
| 624 |
+
def test_special_case_salt(self):
|
| 625 |
+
# password, cost, salt, bcrypt hash
|
| 626 |
+
tvs = [
|
| 627 |
+
("-O_=*N!2JP", 4, b"......................", b"$2a$04$......................JjuKLOX9OOwo5PceZZXSkaLDvdmgb82"),
|
| 628 |
+
("7B[$Q<4b>U", 5, b"......................", b"$2a$05$......................DRiedDQZRL3xq5A5FL8y7/6NM8a2Y5W"),
|
| 629 |
+
(">d5-I_8^.h", 6, b"......................", b"$2a$06$......................5Mq1Ng8jgDY.uHNU4h5p/x6BedzNH2W"),
|
| 630 |
+
(")V`/UM/]1t", 4, b".OC/.OC/.OC/.OC/.OC/.O", b"$2a$04$.OC/.OC/.OC/.OC/.OC/.OQIvKRDAam.Hm5/IaV/.hc7P8gwwIbmi"),
|
| 631 |
+
(":@t2.bWuH]", 5, b".OC/.OC/.OC/.OC/.OC/.O", b"$2a$05$.OC/.OC/.OC/.OC/.OC/.ONDbUvdOchUiKmQORX6BlkPofa/QxW9e"),
|
| 632 |
+
("b(#KljF5s\"", 6, b".OC/.OC/.OC/.OC/.OC/.O", b"$2a$06$.OC/.OC/.OC/.OC/.OC/.OHfTd9e7svOu34vi1PCvOcAEq07ST7.K"),
|
| 633 |
+
("@3YaJ^Xs]*", 4, b"eGA.eGA.eGA.eGA.eGA.e.", b"$2a$04$eGA.eGA.eGA.eGA.eGA.e.stcmvh.R70m.0jbfSFVxlONdj1iws0C"),
|
| 634 |
+
("'\"5\\!k*C(p", 5, b"eGA.eGA.eGA.eGA.eGA.e.", b"$2a$05$eGA.eGA.eGA.eGA.eGA.e.vR37mVSbfdHwu.F0sNMvgn8oruQRghy"),
|
| 635 |
+
("edEu7C?$'W", 6, b"eGA.eGA.eGA.eGA.eGA.e.", b"$2a$06$eGA.eGA.eGA.eGA.eGA.e.tSq0FN8MWHQXJXNFnHTPQKtA.n2a..G"),
|
| 636 |
+
("N7dHmg\\PI^", 4, b"999999999999999999999u", b"$2a$04$999999999999999999999uCZfA/pLrlyngNDMq89r1uUk.bQ9icOu"),
|
| 637 |
+
("\"eJuHh!)7*", 5, b"999999999999999999999u", b"$2a$05$999999999999999999999uj8Pfx.ufrJFAoWFLjapYBS5vVEQQ/hK"),
|
| 638 |
+
("ZeDRJ:_tu:", 6, b"999999999999999999999u", b"$2a$06$999999999999999999999u6RB0P9UmbdbQgjoQFEJsrvrKe.BoU6q"),
|
| 639 |
+
]
|
| 640 |
+
|
| 641 |
+
for (idx, (password, cost, salt64, result)) in enumerate(tvs):
|
| 642 |
+
x = bcrypt(password, cost, salt=_bcrypt_decode(salt64))
|
| 643 |
+
self.assertEqual(x, result)
|
| 644 |
+
bcrypt_check(password, result)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
class TestVectorsHKDFWycheproof(unittest.TestCase):
|
| 648 |
+
|
| 649 |
+
def __init__(self, wycheproof_warnings):
|
| 650 |
+
unittest.TestCase.__init__(self)
|
| 651 |
+
self._wycheproof_warnings = wycheproof_warnings
|
| 652 |
+
self._id = "None"
|
| 653 |
+
|
| 654 |
+
def add_tests(self, filename):
|
| 655 |
+
|
| 656 |
+
def filter_algo(root):
|
| 657 |
+
algo_name = root['algorithm']
|
| 658 |
+
if algo_name == "HKDF-SHA-1":
|
| 659 |
+
return SHA1
|
| 660 |
+
elif algo_name == "HKDF-SHA-256":
|
| 661 |
+
return SHA256
|
| 662 |
+
elif algo_name == "HKDF-SHA-384":
|
| 663 |
+
return SHA384
|
| 664 |
+
elif algo_name == "HKDF-SHA-512":
|
| 665 |
+
return SHA512
|
| 666 |
+
else:
|
| 667 |
+
raise ValueError("Unknown algorithm " + algo_name)
|
| 668 |
+
|
| 669 |
+
def filter_size(unit):
|
| 670 |
+
return int(unit['size'])
|
| 671 |
+
|
| 672 |
+
result = load_test_vectors_wycheproof(("Protocol", "wycheproof"),
|
| 673 |
+
filename,
|
| 674 |
+
"Wycheproof HMAC (%s)" % filename,
|
| 675 |
+
root_tag={'hash_module': filter_algo},
|
| 676 |
+
unit_tag={'size': filter_size})
|
| 677 |
+
return result
|
| 678 |
+
|
| 679 |
+
def setUp(self):
|
| 680 |
+
self.tv = []
|
| 681 |
+
self.add_tests("hkdf_sha1_test.json")
|
| 682 |
+
self.add_tests("hkdf_sha256_test.json")
|
| 683 |
+
self.add_tests("hkdf_sha384_test.json")
|
| 684 |
+
self.add_tests("hkdf_sha512_test.json")
|
| 685 |
+
|
| 686 |
+
def shortDescription(self):
|
| 687 |
+
return self._id
|
| 688 |
+
|
| 689 |
+
def warn(self, tv):
|
| 690 |
+
if tv.warning and self._wycheproof_warnings:
|
| 691 |
+
import warnings
|
| 692 |
+
warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
|
| 693 |
+
|
| 694 |
+
def test_verify(self, tv):
|
| 695 |
+
self._id = "Wycheproof HKDF Test #%d (%s, %s)" % (tv.id, tv.comment, tv.filename)
|
| 696 |
+
|
| 697 |
+
try:
|
| 698 |
+
key = HKDF(tv.ikm, tv.size, tv.salt, tv.hash_module, 1, tv.info)
|
| 699 |
+
except ValueError:
|
| 700 |
+
assert not tv.valid
|
| 701 |
+
else:
|
| 702 |
+
if key != tv.okm:
|
| 703 |
+
assert not tv.valid
|
| 704 |
+
else:
|
| 705 |
+
assert tv.valid
|
| 706 |
+
self.warn(tv)
|
| 707 |
+
|
| 708 |
+
def runTest(self):
|
| 709 |
+
for tv in self.tv:
|
| 710 |
+
self.test_verify(tv)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def load_hash_by_name(hash_name):
|
| 714 |
+
return __import__("Crypto.Hash." + hash_name, globals(), locals(), ["new"])
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
class SP800_180_Counter_Tests(unittest.TestCase):
|
| 718 |
+
|
| 719 |
+
def test_negative_zeroes(self):
|
| 720 |
+
def prf(s, x):
|
| 721 |
+
return HMAC.new(s, x, SHA256).digest()
|
| 722 |
+
|
| 723 |
+
try:
|
| 724 |
+
_ = SP800_108_Counter(b'0' * 16, 1, prf, label=b'A\x00B')
|
| 725 |
+
except ValueError:
|
| 726 |
+
self.fail('SP800_108_Counter failed with zero in label')
|
| 727 |
+
self.assertRaises(ValueError, SP800_108_Counter, b'0' * 16, 1, prf,
|
| 728 |
+
context=b'A\x00B')
|
| 729 |
+
|
| 730 |
+
def test_multiple_keys(self):
|
| 731 |
+
def prf(s, x):
|
| 732 |
+
return HMAC.new(s, x, SHA256).digest()
|
| 733 |
+
|
| 734 |
+
key = b'0' * 16
|
| 735 |
+
expected = SP800_108_Counter(key, 2*3*23, prf)
|
| 736 |
+
for r in (1, 2, 3, 23):
|
| 737 |
+
dks = SP800_108_Counter(key, r, prf, 138//r)
|
| 738 |
+
self.assertEqual(len(dks), 138//r)
|
| 739 |
+
self.assertEqual(len(dks[0]), r)
|
| 740 |
+
self.assertEqual(b''.join(dks), expected)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def add_tests_sp800_108_counter(cls):
|
| 744 |
+
|
| 745 |
+
test_vectors_sp800_108_counter = load_test_vectors(("Protocol", ),
|
| 746 |
+
"KDF_SP800_108_COUNTER.txt",
|
| 747 |
+
"NIST SP 800 108 KDF Counter Mode",
|
| 748 |
+
{'count': lambda x: int(x)},
|
| 749 |
+
) or []
|
| 750 |
+
|
| 751 |
+
mac_type = None
|
| 752 |
+
for idx, tv in enumerate(test_vectors_sp800_108_counter):
|
| 753 |
+
|
| 754 |
+
if isinstance(tv, str):
|
| 755 |
+
res = re.match(r"\[HMAC-(SHA-[0-9]+)\]", tv)
|
| 756 |
+
if res:
|
| 757 |
+
hash_name = res.group(1).replace("-", "")
|
| 758 |
+
hash_module = load_hash_by_name(hash_name)
|
| 759 |
+
mac_type = "hmac"
|
| 760 |
+
continue
|
| 761 |
+
res = re.match(r"\[CMAC-AES-128\]", tv)
|
| 762 |
+
if res:
|
| 763 |
+
mac_type = "cmac"
|
| 764 |
+
continue
|
| 765 |
+
assert res
|
| 766 |
+
|
| 767 |
+
if mac_type == "hmac":
|
| 768 |
+
def prf(s, x, hash_module=hash_module):
|
| 769 |
+
return HMAC.new(s, x, hash_module).digest()
|
| 770 |
+
elif mac_type == "cmac":
|
| 771 |
+
def prf(s, x, hash_module=hash_module):
|
| 772 |
+
return CMAC.new(s, x, AES).digest()
|
| 773 |
+
continue
|
| 774 |
+
|
| 775 |
+
def kdf_test(self, prf=prf, kin=tv.kin, label=tv.label,
|
| 776 |
+
context=tv.context, kout=tv.kout, count=tv.count):
|
| 777 |
+
result = SP800_108_Counter(kin, len(kout), prf, 1, label, context)
|
| 778 |
+
assert(len(result) == len(kout))
|
| 779 |
+
self.assertEqual(result, kout)
|
| 780 |
+
|
| 781 |
+
setattr(cls, "test_kdf_sp800_108_counter_%d" % idx, kdf_test)
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
add_tests_sp800_108_counter(SP800_180_Counter_Tests)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def get_tests(config={}):
|
| 788 |
+
wycheproof_warnings = config.get('wycheproof_warnings')
|
| 789 |
+
|
| 790 |
+
if not config.get('slow_tests'):
|
| 791 |
+
PBKDF2_Tests._testData = PBKDF2_Tests._testData[:3]
|
| 792 |
+
scrypt_Tests.data = scrypt_Tests.data[:3]
|
| 793 |
+
|
| 794 |
+
tests = []
|
| 795 |
+
tests += list_test_cases(PBKDF1_Tests)
|
| 796 |
+
tests += list_test_cases(PBKDF2_Tests)
|
| 797 |
+
tests += list_test_cases(S2V_Tests)
|
| 798 |
+
tests += list_test_cases(HKDF_Tests)
|
| 799 |
+
tests += [TestVectorsHKDFWycheproof(wycheproof_warnings)]
|
| 800 |
+
tests += list_test_cases(scrypt_Tests)
|
| 801 |
+
tests += list_test_cases(bcrypt_Tests)
|
| 802 |
+
tests += list_test_cases(SP800_180_Counter_Tests)
|
| 803 |
+
|
| 804 |
+
return tests
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
if __name__ == '__main__':
|
| 808 |
+
suite = lambda: unittest.TestSuite(get_tests())
|
| 809 |
+
unittest.main(defaultTest='suite')
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/test_SecretSharing.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
#
|
| 2 |
+
# SelfTest/Protocol/test_secret_sharing.py: Self-test for secret sharing protocols
|
| 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 unittest import main, TestCase, TestSuite
|
| 35 |
+
from binascii import unhexlify, hexlify
|
| 36 |
+
|
| 37 |
+
from Crypto.Util.py3compat import *
|
| 38 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 39 |
+
|
| 40 |
+
from Crypto.Protocol.SecretSharing import Shamir, _Element, \
|
| 41 |
+
_mult_gf2, _div_gf2
|
| 42 |
+
|
| 43 |
+
class GF2_Tests(TestCase):
|
| 44 |
+
|
| 45 |
+
def test_mult_gf2(self):
|
| 46 |
+
# Prove mult by zero
|
| 47 |
+
x = _mult_gf2(0,0)
|
| 48 |
+
self.assertEqual(x, 0)
|
| 49 |
+
|
| 50 |
+
# Prove mult by unity
|
| 51 |
+
x = _mult_gf2(34, 1)
|
| 52 |
+
self.assertEqual(x, 34)
|
| 53 |
+
|
| 54 |
+
z = 3 # (x+1)
|
| 55 |
+
y = _mult_gf2(z, z)
|
| 56 |
+
self.assertEqual(y, 5) # (x+1)^2 = x^2 + 1
|
| 57 |
+
y = _mult_gf2(y, z)
|
| 58 |
+
self.assertEqual(y, 15) # (x+1)^3 = x^3 + x^2 + x + 1
|
| 59 |
+
y = _mult_gf2(y, z)
|
| 60 |
+
self.assertEqual(y, 17) # (x+1)^4 = x^4 + 1
|
| 61 |
+
|
| 62 |
+
# Prove linearity works
|
| 63 |
+
comps = [1, 4, 128, 2**34]
|
| 64 |
+
sum_comps = 1+4+128+2**34
|
| 65 |
+
y = 908
|
| 66 |
+
z = _mult_gf2(sum_comps, y)
|
| 67 |
+
w = 0
|
| 68 |
+
for x in comps:
|
| 69 |
+
w ^= _mult_gf2(x, y)
|
| 70 |
+
self.assertEqual(w, z)
|
| 71 |
+
|
| 72 |
+
def test_div_gf2(self):
|
| 73 |
+
from Crypto.Util.number import size as deg
|
| 74 |
+
|
| 75 |
+
x, y = _div_gf2(567, 7)
|
| 76 |
+
self.assertTrue(deg(y) < deg(7))
|
| 77 |
+
|
| 78 |
+
w = _mult_gf2(x, 7) ^ y
|
| 79 |
+
self.assertEqual(567, w)
|
| 80 |
+
|
| 81 |
+
x, y = _div_gf2(7, 567)
|
| 82 |
+
self.assertEqual(x, 0)
|
| 83 |
+
self.assertEqual(y, 7)
|
| 84 |
+
|
| 85 |
+
class Element_Tests(TestCase):
|
| 86 |
+
|
| 87 |
+
def test1(self):
|
| 88 |
+
# Test encondings
|
| 89 |
+
e = _Element(256)
|
| 90 |
+
self.assertEqual(int(e), 256)
|
| 91 |
+
self.assertEqual(e.encode(), bchr(0)*14 + b("\x01\x00"))
|
| 92 |
+
|
| 93 |
+
e = _Element(bchr(0)*14 + b("\x01\x10"))
|
| 94 |
+
self.assertEqual(int(e), 0x110)
|
| 95 |
+
self.assertEqual(e.encode(), bchr(0)*14 + b("\x01\x10"))
|
| 96 |
+
|
| 97 |
+
# Only 16 byte string are a valid encoding
|
| 98 |
+
self.assertRaises(ValueError, _Element, bchr(0))
|
| 99 |
+
|
| 100 |
+
def test2(self):
|
| 101 |
+
# Test addition
|
| 102 |
+
e = _Element(0x10)
|
| 103 |
+
f = _Element(0x0A)
|
| 104 |
+
self.assertEqual(int(e+f), 0x1A)
|
| 105 |
+
|
| 106 |
+
def test3(self):
|
| 107 |
+
# Test multiplication
|
| 108 |
+
zero = _Element(0)
|
| 109 |
+
one = _Element(1)
|
| 110 |
+
two = _Element(2)
|
| 111 |
+
|
| 112 |
+
x = _Element(6) * zero
|
| 113 |
+
self.assertEqual(int(x), 0)
|
| 114 |
+
|
| 115 |
+
x = _Element(6) * one
|
| 116 |
+
self.assertEqual(int(x), 6)
|
| 117 |
+
|
| 118 |
+
x = _Element(2**127) * two
|
| 119 |
+
self.assertEqual(int(x), 1 + 2 + 4 + 128)
|
| 120 |
+
|
| 121 |
+
def test4(self):
|
| 122 |
+
# Test inversion
|
| 123 |
+
one = _Element(1)
|
| 124 |
+
|
| 125 |
+
x = one.inverse()
|
| 126 |
+
self.assertEqual(int(x), 1)
|
| 127 |
+
|
| 128 |
+
x = _Element(82323923)
|
| 129 |
+
y = x.inverse()
|
| 130 |
+
self.assertEqual(int(x * y), 1)
|
| 131 |
+
|
| 132 |
+
class Shamir_Tests(TestCase):
|
| 133 |
+
|
| 134 |
+
def test1(self):
|
| 135 |
+
# Test splitting
|
| 136 |
+
shares = Shamir.split(2, 3, bchr(90)*16)
|
| 137 |
+
self.assertEqual(len(shares), 3)
|
| 138 |
+
for index in range(3):
|
| 139 |
+
self.assertEqual(shares[index][0], index+1)
|
| 140 |
+
self.assertEqual(len(shares[index][1]), 16)
|
| 141 |
+
|
| 142 |
+
def test2(self):
|
| 143 |
+
# Test recombine
|
| 144 |
+
from itertools import permutations
|
| 145 |
+
|
| 146 |
+
test_vectors = (
|
| 147 |
+
(2, "d9fe73909bae28b3757854c0af7ad405",
|
| 148 |
+
"1-594ae8964294174d95c33756d2504170",
|
| 149 |
+
"2-d897459d29da574eb40e93ec552ffe6e",
|
| 150 |
+
"3-5823de9bf0e068b054b5f07a28056b1b",
|
| 151 |
+
"4-db2c1f8bff46d748f795da995bd080cb"),
|
| 152 |
+
(2, "bf4f902d9a7efafd1f3ffd9291fd5de9",
|
| 153 |
+
"1-557bd3b0748064b533469722d1cc7935",
|
| 154 |
+
"2-6b2717164783c66d47cd28f2119f14d0",
|
| 155 |
+
"3-8113548ba97d58256bb4424251ae300c",
|
| 156 |
+
"4-179e9e5a218483ddaeda57539139cf04"),
|
| 157 |
+
(3, "ec96aa5c14c9faa699354cf1da74e904",
|
| 158 |
+
"1-64579fbf1908d66f7239bf6e2b4e41e1",
|
| 159 |
+
"2-6cd9428df8017b52322561e8c672ae3e",
|
| 160 |
+
"3-e418776ef5c0579bd9299277374806dd",
|
| 161 |
+
"4-ab3f77a0107398d23b323e581bb43f5d",
|
| 162 |
+
"5-23fe42431db2b41bd03ecdc7ea8e97ac"),
|
| 163 |
+
(3, "44cf249b68b80fcdc27b47be60c2c145",
|
| 164 |
+
"1-d6515a3905cd755119b86e311c801e31",
|
| 165 |
+
"2-16693d9ac9f10c254036ced5f8917fa3",
|
| 166 |
+
"3-84f74338a48476b99bf5e75a84d3a0d1",
|
| 167 |
+
"4-3fe8878dc4a5d35811cf3cbcd33dbe52",
|
| 168 |
+
"5-ad76f92fa9d0a9c4ca0c1533af7f6132"),
|
| 169 |
+
(5, "5398717c982db935d968eebe53a47f5a",
|
| 170 |
+
"1-be7be2dd4c068e7ef576aaa1b1c11b01",
|
| 171 |
+
"2-f821f5848441cb98b3eb467e2733ee21",
|
| 172 |
+
"3-25ee52f53e203f6e29a0297b5ab486b5",
|
| 173 |
+
"4-fc9fb58ef74dab947fbf9acd9d5d83cd",
|
| 174 |
+
"5-b1949cce46d81552e65f248d3f74cc5c",
|
| 175 |
+
"6-d64797f59977c4d4a7956ad916da7699",
|
| 176 |
+
"7-ab608a6546a8b9af8820ff832b1135c7"),
|
| 177 |
+
(5, "4a78db90fbf35da5545d2fb728e87596",
|
| 178 |
+
"1-08daf9a25d8aa184cfbf02b30a0ed6a0",
|
| 179 |
+
"2-dda28261e36f0b14168c2cf153fb734e",
|
| 180 |
+
"3-e9fdec5505d674a57f9836c417c1ecaa",
|
| 181 |
+
"4-4dce5636ae06dee42d2c82e65f06c735",
|
| 182 |
+
"5-3963dc118afc2ba798fa1d452b28ef00",
|
| 183 |
+
"6-6dfe6ff5b09e94d2f84c382b12f42424",
|
| 184 |
+
"7-6faea9d4d4a4e201bf6c90b9000630c3"),
|
| 185 |
+
(10, "eccbf6d66d680b49b073c4f1ddf804aa",
|
| 186 |
+
"01-7d8ac32fe4ae209ead1f3220fda34466",
|
| 187 |
+
"02-f9144e76988aad647d2e61353a6e96d5",
|
| 188 |
+
"03-b14c3b80179203363922d60760271c98",
|
| 189 |
+
"04-770bb2a8c28f6cee89e00f4d5cc7f861",
|
| 190 |
+
"05-6e3d7073ea368334ef67467871c66799",
|
| 191 |
+
"06-248792bc74a98ce024477c13c8fb5f8d",
|
| 192 |
+
"07-fcea4640d2db820c0604851e293d2487",
|
| 193 |
+
"08-2776c36fb714bb1f8525a0be36fc7dba",
|
| 194 |
+
"09-6ee7ac8be773e473a4bf75ee5f065762",
|
| 195 |
+
"10-33657fc073354cf91d4a68c735aacfc8",
|
| 196 |
+
"11-7645c65094a5868bf225c516fdee2d0c",
|
| 197 |
+
"12-840485aacb8226631ecd9c70e3018086"),
|
| 198 |
+
(10, "377e63bdbb5f7d4dc58a483d035212bb",
|
| 199 |
+
"01-32c53260103be431c843b1a633afe3bd",
|
| 200 |
+
"02-0107eb16cb8695084d452d2cc50bc7d6",
|
| 201 |
+
"03-df1e5c66cd755287fb0446faccd72a06",
|
| 202 |
+
"04-361bbcd5d40797f49dfa1898652da197",
|
| 203 |
+
"05-160d3ad1512f7dec7fd9344aed318591",
|
| 204 |
+
"06-659af6d95df4f25beca4fb9bfee3b7e8",
|
| 205 |
+
"07-37f3b208977bad50b3724566b72bfa9d",
|
| 206 |
+
"08-6c1de2dfc69c2986142c26a8248eb316",
|
| 207 |
+
"09-5e19220837a396bd4bc8cd685ff314c3",
|
| 208 |
+
"10-86e7b864fb0f3d628e46d50c1ba92f1c",
|
| 209 |
+
"11-065d0082c80b1aea18f4abe0c49df72e",
|
| 210 |
+
"12-84a09430c1d20ea9f388f3123c3733a3"),
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
def get_share(p):
|
| 214 |
+
pos = p.find('-')
|
| 215 |
+
return int(p[:pos]), unhexlify(p[pos + 1:])
|
| 216 |
+
|
| 217 |
+
for tv in test_vectors:
|
| 218 |
+
k = tv[0]
|
| 219 |
+
secret = unhexlify(tv[1])
|
| 220 |
+
max_perms = 10
|
| 221 |
+
for perm, shares_idx in enumerate(permutations(range(2, len(tv)), k)):
|
| 222 |
+
if perm > max_perms:
|
| 223 |
+
break
|
| 224 |
+
shares = [ get_share(tv[x]) for x in shares_idx ]
|
| 225 |
+
result = Shamir.combine(shares, True)
|
| 226 |
+
self.assertEqual(secret, result)
|
| 227 |
+
|
| 228 |
+
def test3(self):
|
| 229 |
+
# Loopback split/recombine
|
| 230 |
+
secret = unhexlify(b("000102030405060708090a0b0c0d0e0f"))
|
| 231 |
+
|
| 232 |
+
shares = Shamir.split(2, 3, secret)
|
| 233 |
+
|
| 234 |
+
secret2 = Shamir.combine(shares[:2])
|
| 235 |
+
self.assertEqual(secret, secret2)
|
| 236 |
+
|
| 237 |
+
secret3 = Shamir.combine([ shares[0], shares[2] ])
|
| 238 |
+
self.assertEqual(secret, secret3)
|
| 239 |
+
|
| 240 |
+
def test4(self):
|
| 241 |
+
# Loopback split/recombine (SSSS)
|
| 242 |
+
secret = unhexlify(b("000102030405060708090a0b0c0d0e0f"))
|
| 243 |
+
|
| 244 |
+
shares = Shamir.split(2, 3, secret, ssss=True)
|
| 245 |
+
|
| 246 |
+
secret2 = Shamir.combine(shares[:2], ssss=True)
|
| 247 |
+
self.assertEqual(secret, secret2)
|
| 248 |
+
|
| 249 |
+
def test5(self):
|
| 250 |
+
# Detect duplicate shares
|
| 251 |
+
secret = unhexlify(b("000102030405060708090a0b0c0d0e0f"))
|
| 252 |
+
|
| 253 |
+
shares = Shamir.split(2, 3, secret)
|
| 254 |
+
self.assertRaises(ValueError, Shamir.combine, (shares[0], shares[0]))
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def get_tests(config={}):
|
| 258 |
+
tests = []
|
| 259 |
+
tests += list_test_cases(GF2_Tests)
|
| 260 |
+
tests += list_test_cases(Element_Tests)
|
| 261 |
+
tests += list_test_cases(Shamir_Tests)
|
| 262 |
+
return tests
|
| 263 |
+
|
| 264 |
+
if __name__ == '__main__':
|
| 265 |
+
suite = lambda: TestSuite(get_tests())
|
| 266 |
+
main(defaultTest='suite')
|
| 267 |
+
|
minigpt2/lib/python3.10/site-packages/Crypto/SelfTest/Protocol/test_ecdh.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import base64
|
| 3 |
+
import unittest
|
| 4 |
+
from binascii import hexlify, unhexlify
|
| 5 |
+
|
| 6 |
+
from Crypto.Util.py3compat import bord
|
| 7 |
+
|
| 8 |
+
from Crypto.Hash import SHA256
|
| 9 |
+
from Crypto.PublicKey import ECC
|
| 10 |
+
from Crypto.SelfTest.st_common import list_test_cases
|
| 11 |
+
from Crypto.SelfTest.loader import load_test_vectors, load_test_vectors_wycheproof
|
| 12 |
+
|
| 13 |
+
from Crypto.Protocol import DH
|
| 14 |
+
from Crypto.Protocol.DH import (key_agreement,
|
| 15 |
+
import_x25519_public_key,
|
| 16 |
+
import_x25519_private_key)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FIPS_ECDH_Tests_KAT(unittest.TestCase):
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
test_vectors_verify = load_test_vectors(("Protocol", ),
|
| 24 |
+
"KAS_ECC_CDH_PrimitiveTest.txt",
|
| 25 |
+
"ECC CDH Primitive (SP800-56A Section 5.7.1.2)",
|
| 26 |
+
{
|
| 27 |
+
'qcavsx': lambda x: int(x, 16),
|
| 28 |
+
'qcavsy': lambda x: int(x, 16),
|
| 29 |
+
'diut': lambda x: int(x, 16),
|
| 30 |
+
'qiutx': lambda x: int(x, 16),
|
| 31 |
+
'qiuty': lambda x: int(x, 16),
|
| 32 |
+
}) or []
|
| 33 |
+
|
| 34 |
+
for idx, tv in enumerate(test_vectors_verify):
|
| 35 |
+
|
| 36 |
+
# Stand-alone header with curve name
|
| 37 |
+
if isinstance(tv, str):
|
| 38 |
+
res = re.match(r"\[([A-Za-z0-9-]+)\]", tv)
|
| 39 |
+
assert res
|
| 40 |
+
curve_name = res.group(1)
|
| 41 |
+
continue
|
| 42 |
+
|
| 43 |
+
public_key = ECC.construct(curve=curve_name,
|
| 44 |
+
point_x=tv.qcavsx,
|
| 45 |
+
point_y=tv.qcavsy)
|
| 46 |
+
|
| 47 |
+
private_key = ECC.construct(curve=curve_name,
|
| 48 |
+
d=tv.diut)
|
| 49 |
+
|
| 50 |
+
exp_response = tv.ziut
|
| 51 |
+
|
| 52 |
+
def ecdh_test(self,
|
| 53 |
+
public_key=public_key,
|
| 54 |
+
private_key=private_key,
|
| 55 |
+
exp_response=exp_response):
|
| 56 |
+
z = key_agreement(
|
| 57 |
+
static_pub=public_key,
|
| 58 |
+
static_priv=private_key,
|
| 59 |
+
kdf=lambda x: x)
|
| 60 |
+
self.assertEqual(z, exp_response)
|
| 61 |
+
|
| 62 |
+
def ecdh_test_rev(self,
|
| 63 |
+
public_key=public_key,
|
| 64 |
+
private_key=private_key,
|
| 65 |
+
exp_response=exp_response):
|
| 66 |
+
z = key_agreement(
|
| 67 |
+
static_pub=public_key,
|
| 68 |
+
static_priv=private_key,
|
| 69 |
+
kdf=lambda x: x)
|
| 70 |
+
self.assertEqual(z, exp_response)
|
| 71 |
+
|
| 72 |
+
setattr(FIPS_ECDH_Tests_KAT, "test_verify_positive_%d" % idx, ecdh_test)
|
| 73 |
+
if idx == 1:
|
| 74 |
+
setattr(FIPS_ECDH_Tests_KAT, "test_verify_positive_rev_%d" % idx, ecdh_test_rev)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class TestVectorsECDHWycheproof(unittest.TestCase):
|
| 78 |
+
|
| 79 |
+
desc = "Wycheproof ECDH tests"
|
| 80 |
+
|
| 81 |
+
def add_tests(self, filename):
|
| 82 |
+
|
| 83 |
+
def curve(g):
|
| 84 |
+
return g['curve']
|
| 85 |
+
|
| 86 |
+
def private(u):
|
| 87 |
+
return int(u['private'], 16)
|
| 88 |
+
|
| 89 |
+
result = load_test_vectors_wycheproof(("Protocol", "wycheproof"),
|
| 90 |
+
filename,
|
| 91 |
+
"Wycheproof ECDH (%s)"
|
| 92 |
+
% filename,
|
| 93 |
+
group_tag={'curve': curve},
|
| 94 |
+
unit_tag={'private': private},
|
| 95 |
+
)
|
| 96 |
+
self.tv += result
|
| 97 |
+
|
| 98 |
+
def setUp(self):
|
| 99 |
+
self.tv = []
|
| 100 |
+
self.desc = None
|
| 101 |
+
|
| 102 |
+
self.add_tests("ecdh_secp224r1_ecpoint_test.json")
|
| 103 |
+
self.add_tests("ecdh_secp256r1_ecpoint_test.json")
|
| 104 |
+
self.add_tests("ecdh_secp384r1_ecpoint_test.json")
|
| 105 |
+
self.add_tests("ecdh_secp521r1_ecpoint_test.json")
|
| 106 |
+
|
| 107 |
+
self.add_tests("ecdh_secp224r1_test.json")
|
| 108 |
+
self.add_tests("ecdh_secp256r1_test.json")
|
| 109 |
+
self.add_tests("ecdh_secp384r1_test.json")
|
| 110 |
+
self.add_tests("ecdh_secp521r1_test.json")
|
| 111 |
+
|
| 112 |
+
def shortDescription(self):
|
| 113 |
+
return self.desc
|
| 114 |
+
|
| 115 |
+
def test_verify(self, tv):
|
| 116 |
+
|
| 117 |
+
if len(tv.public) == 0:
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
if bord(tv.public[0]) == 4: # SEC1
|
| 122 |
+
public_key = ECC.import_key(tv.public, curve_name=tv.curve)
|
| 123 |
+
else:
|
| 124 |
+
public_key = ECC.import_key(tv.public)
|
| 125 |
+
except ValueError:
|
| 126 |
+
assert tv.warning or not tv.valid
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
private_key = ECC.construct(curve=tv.curve, d=tv.private)
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
z = key_agreement(static_pub=public_key,
|
| 133 |
+
static_priv=private_key,
|
| 134 |
+
kdf=lambda x: x)
|
| 135 |
+
except ValueError:
|
| 136 |
+
assert not tv.valid
|
| 137 |
+
except TypeError as e:
|
| 138 |
+
assert not tv.valid
|
| 139 |
+
assert "incompatible curve" in str(e)
|
| 140 |
+
else:
|
| 141 |
+
self.assertEqual(z, tv.shared)
|
| 142 |
+
assert tv.valid
|
| 143 |
+
|
| 144 |
+
def runTest(self):
|
| 145 |
+
for tv in self.tv:
|
| 146 |
+
self.desc = "Wycheproof ECDH Verify Test #%d (%s, %s)" % (tv.id, tv.comment, tv.filename)
|
| 147 |
+
self.test_verify(tv)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class ECDH_Tests(unittest.TestCase):
|
| 151 |
+
|
| 152 |
+
static_priv = ECC.import_key('-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg9VHFVKh2a1aVFifH\n+BiyNaRa2kttEg3165Ye/dJxJ7KhRANCAARImIEXro5ZOcyWU2mq/+d79FEZXtTA\nbKkz1aICQXihQdCMzRNbeNtC9LFLzhu1slRKJ2xsDAlw9r6w6vwtkRzr\n-----END PRIVATE KEY-----')
|
| 153 |
+
static_pub = ECC.import_key('-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgHhmv8zmZ+Nw8fsZd\ns8tlZflyfw2NE1CRS9DWr3Y3O46hRANCAAS3hZVUCbk+uk3w4S/YOraEVGG+WYpk\nNO/vrwzufUUks2GV2OnBQESe0EBk4Jq8gn4ij8Lvs3rZX2yT+XfeATYd\n-----END PRIVATE KEY-----').public_key()
|
| 154 |
+
|
| 155 |
+
eph_priv = ECC.import_key('-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGPdJmFFFKzLPspIr\nE1T2cEjeIf4ajS9CpneP0e2b3AyhRANCAAQBexAA5BYDcXHs2KOksTYUsst4HhPt\nkp0zkgI2virc3OGJFNGPaCCPfFCQJHwLRaEpiq3SoQlgoBwSc8ZPsl3y\n-----END PRIVATE KEY-----')
|
| 156 |
+
|
| 157 |
+
eph_pub = ECC.import_key('-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQghaVZXElSEGEojFKF\nOU0JCpxWUWHvWQUR81gwWrOp76ShRANCAATi1Ib2K+YR3AckD8wxypWef7pw5PRw\ntBaB3RDPyE7IjHZC6yu1DbcXoCdtaw+F5DM+4zpl59n5ZaIy/Yl1BdIy\n-----END PRIVATE KEY-----')
|
| 158 |
+
|
| 159 |
+
def test_1(self):
|
| 160 |
+
# C(0, 2s)
|
| 161 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 162 |
+
z = key_agreement(
|
| 163 |
+
kdf=kdf,
|
| 164 |
+
static_pub=self.static_pub,
|
| 165 |
+
static_priv=self.static_priv)
|
| 166 |
+
self.assertEqual(hexlify(z),
|
| 167 |
+
b"3960a1101d1193cbaffef4cc7202ebff783c22c6d2e0d5d530ffc66dc197ea9c")
|
| 168 |
+
|
| 169 |
+
def test_2(self):
|
| 170 |
+
# C(2e, 2s)
|
| 171 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 172 |
+
z = key_agreement(
|
| 173 |
+
kdf=kdf,
|
| 174 |
+
static_pub=self.static_pub,
|
| 175 |
+
static_priv=self.static_priv,
|
| 176 |
+
eph_pub=self.eph_pub,
|
| 177 |
+
eph_priv=self.eph_priv)
|
| 178 |
+
self.assertEqual(hexlify(z),
|
| 179 |
+
b"7447b733d40c8fab2c633b3dc61e4a8c742f3a6af7e16fb0cc486f5bdb5d6ba2")
|
| 180 |
+
|
| 181 |
+
def test_3(self):
|
| 182 |
+
# C(1e, 2s)
|
| 183 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 184 |
+
z = key_agreement(
|
| 185 |
+
kdf=kdf,
|
| 186 |
+
static_pub=self.static_pub,
|
| 187 |
+
static_priv=self.static_priv,
|
| 188 |
+
eph_priv=self.eph_priv)
|
| 189 |
+
self.assertEqual(hexlify(z),
|
| 190 |
+
b"9e977ae45f33bf67f285d064d83e6632bcafe3a7d33fe571233bab4794ace759")
|
| 191 |
+
|
| 192 |
+
def test_4(self):
|
| 193 |
+
# C(1e, 2s)
|
| 194 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 195 |
+
z = key_agreement(
|
| 196 |
+
kdf=kdf,
|
| 197 |
+
static_pub=self.static_pub,
|
| 198 |
+
static_priv=self.static_priv,
|
| 199 |
+
eph_pub=self.eph_pub)
|
| 200 |
+
self.assertEqual(hexlify(z),
|
| 201 |
+
b"c9532df6aa7e9dbe5fe85da31ee25ff19c179c88691ec4b8328cc2036dcdadf2")
|
| 202 |
+
|
| 203 |
+
def test_5(self):
|
| 204 |
+
# C(2e, 1s) is not supported
|
| 205 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 206 |
+
self.assertRaises(ValueError,
|
| 207 |
+
key_agreement,
|
| 208 |
+
kdf=kdf,
|
| 209 |
+
static_priv=self.static_priv,
|
| 210 |
+
eph_pub=self.eph_pub,
|
| 211 |
+
eph_priv=self.eph_priv)
|
| 212 |
+
|
| 213 |
+
def test_6(self):
|
| 214 |
+
# C(2e, 1s) is not supported
|
| 215 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 216 |
+
self.assertRaises(ValueError,
|
| 217 |
+
key_agreement,
|
| 218 |
+
kdf=kdf,
|
| 219 |
+
static_pub=self.static_pub,
|
| 220 |
+
eph_pub=self.eph_pub,
|
| 221 |
+
eph_priv=self.eph_priv)
|
| 222 |
+
|
| 223 |
+
def test_7(self):
|
| 224 |
+
# C(2e, 0)
|
| 225 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 226 |
+
z = key_agreement(
|
| 227 |
+
kdf=kdf,
|
| 228 |
+
eph_pub=self.eph_pub,
|
| 229 |
+
eph_priv=self.eph_priv)
|
| 230 |
+
self.assertEqual(hexlify(z),
|
| 231 |
+
b"feb257ebe063078b1391aac07913283d7b642ad7df61b46dfc9cd6f420bb896a")
|
| 232 |
+
|
| 233 |
+
def test_8(self):
|
| 234 |
+
# C(1e, 1s)
|
| 235 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 236 |
+
z = key_agreement(
|
| 237 |
+
kdf=kdf,
|
| 238 |
+
static_priv=self.static_priv,
|
| 239 |
+
eph_pub=self.eph_pub)
|
| 240 |
+
self.assertEqual(hexlify(z),
|
| 241 |
+
b"ee4dc995117476ed57fd17ff0ed44e9f0466d46b929443bc0db9380317583b04")
|
| 242 |
+
|
| 243 |
+
def test_9(self):
|
| 244 |
+
# C(1e, 1s)
|
| 245 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 246 |
+
z = key_agreement(
|
| 247 |
+
kdf=kdf,
|
| 248 |
+
static_pub=self.static_pub,
|
| 249 |
+
eph_priv=self.eph_priv)
|
| 250 |
+
self.assertEqual(hexlify(z),
|
| 251 |
+
b"2351cc2014f7c40468fa072b5d30f706eeaeef7507311cd8e59bab3b43f03c51")
|
| 252 |
+
|
| 253 |
+
def test_10(self):
|
| 254 |
+
# No private (local) keys
|
| 255 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 256 |
+
self.assertRaises(ValueError,
|
| 257 |
+
key_agreement,
|
| 258 |
+
kdf=kdf,
|
| 259 |
+
static_pub=self.static_pub,
|
| 260 |
+
eph_pub=self.eph_pub)
|
| 261 |
+
|
| 262 |
+
def test_11(self):
|
| 263 |
+
# No public (peer) keys
|
| 264 |
+
kdf = lambda x: SHA256.new(x).digest()
|
| 265 |
+
self.assertRaises(ValueError,
|
| 266 |
+
key_agreement,
|
| 267 |
+
kdf=kdf,
|
| 268 |
+
static_priv=self.static_priv,
|
| 269 |
+
eph_priv=self.eph_priv)
|
| 270 |
+
|
| 271 |
+
def test_12(self):
|
| 272 |
+
# failure if kdf is missing
|
| 273 |
+
self.assertRaises(ValueError,
|
| 274 |
+
key_agreement,
|
| 275 |
+
static_pub=self.static_pub,
|
| 276 |
+
static_priv=self.static_priv)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class X25519_Tests(unittest.TestCase):
|
| 280 |
+
|
| 281 |
+
def test_rfc7748_1(self):
|
| 282 |
+
tvs = (
|
| 283 |
+
("a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4",
|
| 284 |
+
"e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c",
|
| 285 |
+
"c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"),
|
| 286 |
+
("4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d",
|
| 287 |
+
"e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493",
|
| 288 |
+
"95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957"),
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
for tv1, tv2, tv3 in tvs:
|
| 292 |
+
priv_key = DH.import_x25519_private_key(unhexlify(tv1))
|
| 293 |
+
pub_key = DH.import_x25519_public_key(unhexlify(tv2))
|
| 294 |
+
result = key_agreement(static_pub=pub_key,
|
| 295 |
+
static_priv=priv_key,
|
| 296 |
+
kdf=lambda x: x)
|
| 297 |
+
self.assertEqual(result, unhexlify(tv3))
|
| 298 |
+
|
| 299 |
+
def test_rfc7748_2(self):
|
| 300 |
+
k = unhexlify("0900000000000000000000000000000000000000000000000000000000000000")
|
| 301 |
+
|
| 302 |
+
priv_key = DH.import_x25519_private_key(k)
|
| 303 |
+
pub_key = DH.import_x25519_public_key(k)
|
| 304 |
+
result = key_agreement(static_pub=pub_key,
|
| 305 |
+
static_priv=priv_key,
|
| 306 |
+
kdf=lambda x: x)
|
| 307 |
+
self.assertEqual(
|
| 308 |
+
result,
|
| 309 |
+
unhexlify("422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079")
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
for _ in range(999):
|
| 313 |
+
priv_key = DH.import_x25519_private_key(result)
|
| 314 |
+
pub_key = DH.import_x25519_public_key(k)
|
| 315 |
+
k = result
|
| 316 |
+
result = key_agreement(static_pub=pub_key,
|
| 317 |
+
static_priv=priv_key,
|
| 318 |
+
kdf=lambda x: x)
|
| 319 |
+
|
| 320 |
+
self.assertEqual(
|
| 321 |
+
result,
|
| 322 |
+
unhexlify("684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51")
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
def test_rfc7748_3(self):
|
| 326 |
+
tv1 = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"
|
| 327 |
+
tv2 = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"
|
| 328 |
+
tv3 = "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"
|
| 329 |
+
tv4 = "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"
|
| 330 |
+
tv5 = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
|
| 331 |
+
|
| 332 |
+
alice_priv_key = DH.import_x25519_private_key(unhexlify(tv1))
|
| 333 |
+
alice_pub_key = DH.import_x25519_public_key(unhexlify(tv2))
|
| 334 |
+
bob_priv_key = DH.import_x25519_private_key(unhexlify(tv3))
|
| 335 |
+
bob_pub_key = DH.import_x25519_public_key(unhexlify(tv4))
|
| 336 |
+
secret = unhexlify(tv5)
|
| 337 |
+
|
| 338 |
+
result1 = key_agreement(static_pub=alice_pub_key,
|
| 339 |
+
static_priv=bob_priv_key,
|
| 340 |
+
kdf=lambda x: x)
|
| 341 |
+
result2 = key_agreement(static_pub=bob_pub_key,
|
| 342 |
+
static_priv=alice_priv_key,
|
| 343 |
+
kdf=lambda x: x)
|
| 344 |
+
self.assertEqual(result1, secret)
|
| 345 |
+
self.assertEqual(result2, secret)
|
| 346 |
+
|
| 347 |
+
def test_weak(self):
|
| 348 |
+
|
| 349 |
+
weak_keys = (
|
| 350 |
+
"0000000000000000000000000000000000000000000000000000000000000000",
|
| 351 |
+
"0100000000000000000000000000000000000000000000000000000000000000",
|
| 352 |
+
"e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",
|
| 353 |
+
"5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",
|
| 354 |
+
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
|
| 355 |
+
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
|
| 356 |
+
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
|
| 357 |
+
# The implementation will accept these value, but only because
|
| 358 |
+
# it will set the MSB to zero (as required by RFC7748, Section 5),
|
| 359 |
+
# therefore leading to another public key (and to a point which is
|
| 360 |
+
# not of low order anymore).
|
| 361 |
+
# "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",
|
| 362 |
+
# "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",
|
| 363 |
+
# "d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
| 364 |
+
# "daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
| 365 |
+
# "dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
for x in weak_keys:
|
| 369 |
+
self.assertRaises(ValueError,
|
| 370 |
+
DH.import_x25519_public_key,
|
| 371 |
+
unhexlify(x))
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class X448_Tests(unittest.TestCase):
|
| 375 |
+
|
| 376 |
+
def test_rfc7748_1(self):
|
| 377 |
+
tvs = (
|
| 378 |
+
("3d262fddf9ec8e88495266fea19a34d28882acef045104d0d1aae121700a779c984c24f8cdd78fbff44943eba368f54b29259a4f1c600ad3",
|
| 379 |
+
"06fce640fa3487bfda5f6cf2d5263f8aad88334cbd07437f020f08f9814dc031ddbdc38c19c6da2583fa5429db94ada18aa7a7fb4ef8a086",
|
| 380 |
+
"ce3e4ff95a60dc6697da1db1d85e6afbdf79b50a2412d7546d5f239fe14fbaadeb445fc66a01b0779d98223961111e21766282f73dd96b6f"),
|
| 381 |
+
("203d494428b8399352665ddca42f9de8fef600908e0d461cb021f8c538345dd77c3e4806e25f46d3315c44e0a5b4371282dd2c8d5be3095f",
|
| 382 |
+
"0fbcc2f993cd56d3305b0b7d9e55d4c1a8fb5dbb52f8e9a1e9b6201b165d015894e56c4d3570bee52fe205e28a78b91cdfbde71ce8d157db",
|
| 383 |
+
"884a02576239ff7a2f2f63b2db6a9ff37047ac13568e1e30fe63c4a7ad1b3ee3a5700df34321d62077e63633c575c1c954514e99da7c179d"),
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
for tv1, tv2, tv3 in tvs:
|
| 387 |
+
priv_key = DH.import_x448_private_key(unhexlify(tv1))
|
| 388 |
+
pub_key = DH.import_x448_public_key(unhexlify(tv2))
|
| 389 |
+
result = key_agreement(static_pub=pub_key,
|
| 390 |
+
static_priv=priv_key,
|
| 391 |
+
kdf=lambda x: x)
|
| 392 |
+
self.assertEqual(result, unhexlify(tv3))
|
| 393 |
+
|
| 394 |
+
def test_rfc7748_2(self):
|
| 395 |
+
k = unhexlify("0500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
|
| 396 |
+
|
| 397 |
+
priv_key = DH.import_x448_private_key(k)
|
| 398 |
+
pub_key = DH.import_x448_public_key(k)
|
| 399 |
+
result = key_agreement(static_pub=pub_key,
|
| 400 |
+
static_priv=priv_key,
|
| 401 |
+
kdf=lambda x: x)
|
| 402 |
+
self.assertEqual(
|
| 403 |
+
result,
|
| 404 |
+
unhexlify("3f482c8a9f19b01e6c46ee9711d9dc14fd4bf67af30765c2ae2b846a4d23a8cd0db897086239492caf350b51f833868b9bc2b3bca9cf4113")
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
for _ in range(999):
|
| 408 |
+
priv_key = DH.import_x448_private_key(result)
|
| 409 |
+
pub_key = DH.import_x448_public_key(k)
|
| 410 |
+
k = result
|
| 411 |
+
result = key_agreement(static_pub=pub_key,
|
| 412 |
+
static_priv=priv_key,
|
| 413 |
+
kdf=lambda x: x)
|
| 414 |
+
|
| 415 |
+
self.assertEqual(
|
| 416 |
+
result,
|
| 417 |
+
unhexlify("aa3b4749d55b9daf1e5b00288826c467274ce3ebbdd5c17b975e09d4af6c67cf10d087202db88286e2b79fceea3ec353ef54faa26e219f38")
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
def test_rfc7748_3(self):
|
| 421 |
+
tv1 = "9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28dd9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b"
|
| 422 |
+
tv2 = "9b08f7cc31b7e3e67d22d5aea121074a273bd2b83de09c63faa73d2c22c5d9bbc836647241d953d40c5b12da88120d53177f80e532c41fa0"
|
| 423 |
+
tv3 = "1c306a7ac2a0e2e0990b294470cba339e6453772b075811d8fad0d1d6927c120bb5ee8972b0d3e21374c9c921b09d1b0366f10b65173992d"
|
| 424 |
+
tv4 = "3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b43027d8b972fc3e34fb4232a13ca706dcb57aec3dae07bdc1c67bf33609"
|
| 425 |
+
tv5 = "07fff4181ac6cc95ec1c16a94a0f74d12da232ce40a77552281d282bb60c0b56fd2464c335543936521c24403085d59a449a5037514a879d"
|
| 426 |
+
|
| 427 |
+
alice_priv_key = DH.import_x448_private_key(unhexlify(tv1))
|
| 428 |
+
alice_pub_key = DH.import_x448_public_key(unhexlify(tv2))
|
| 429 |
+
bob_priv_key = DH.import_x448_private_key(unhexlify(tv3))
|
| 430 |
+
bob_pub_key = DH.import_x448_public_key(unhexlify(tv4))
|
| 431 |
+
secret = unhexlify(tv5)
|
| 432 |
+
|
| 433 |
+
result1 = key_agreement(static_pub=alice_pub_key,
|
| 434 |
+
static_priv=bob_priv_key,
|
| 435 |
+
kdf=lambda x: x)
|
| 436 |
+
result2 = key_agreement(static_pub=bob_pub_key,
|
| 437 |
+
static_priv=alice_priv_key,
|
| 438 |
+
kdf=lambda x: x)
|
| 439 |
+
self.assertEqual(result1, secret)
|
| 440 |
+
self.assertEqual(result2, secret)
|
| 441 |
+
|
| 442 |
+
def test_weak(self):
|
| 443 |
+
|
| 444 |
+
weak_keys = (
|
| 445 |
+
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
| 446 |
+
"0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
| 447 |
+
"fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
| 448 |
+
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
| 449 |
+
"00000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
for x in weak_keys:
|
| 453 |
+
self.assertRaises(ValueError,
|
| 454 |
+
DH.import_x448_public_key,
|
| 455 |
+
unhexlify(x))
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class TestVectorsXECDHWycheproof(unittest.TestCase):
|
| 459 |
+
|
| 460 |
+
desc = "Wycheproof XECDH tests"
|
| 461 |
+
|
| 462 |
+
def add_tests_hex(self, filename):
|
| 463 |
+
|
| 464 |
+
def encoding(g):
|
| 465 |
+
return g['type']
|
| 466 |
+
|
| 467 |
+
def private(u):
|
| 468 |
+
return unhexlify(u['private'])
|
| 469 |
+
|
| 470 |
+
result = load_test_vectors_wycheproof(("Protocol", "wycheproof"),
|
| 471 |
+
filename,
|
| 472 |
+
"Wycheproof ECDH (%s)"
|
| 473 |
+
% filename,
|
| 474 |
+
group_tag={'encoding': encoding},
|
| 475 |
+
unit_tag={'private': private}
|
| 476 |
+
)
|
| 477 |
+
self.tv += result
|
| 478 |
+
|
| 479 |
+
def add_tests_ascii(self, filename):
|
| 480 |
+
|
| 481 |
+
def encoding(g):
|
| 482 |
+
return g['type']
|
| 483 |
+
|
| 484 |
+
def public(u):
|
| 485 |
+
return u['public']
|
| 486 |
+
|
| 487 |
+
def private(u):
|
| 488 |
+
return u['private']
|
| 489 |
+
|
| 490 |
+
result = load_test_vectors_wycheproof(("Protocol", "wycheproof"),
|
| 491 |
+
filename,
|
| 492 |
+
"Wycheproof ECDH (%s)"
|
| 493 |
+
% filename,
|
| 494 |
+
group_tag={'encoding': encoding},
|
| 495 |
+
unit_tag={'public': public,
|
| 496 |
+
'private': private}
|
| 497 |
+
)
|
| 498 |
+
self.tv += result
|
| 499 |
+
|
| 500 |
+
def setUp(self):
|
| 501 |
+
self.tv = []
|
| 502 |
+
self.desc = None
|
| 503 |
+
|
| 504 |
+
self.add_tests_hex("x25519_test.json")
|
| 505 |
+
self.add_tests_hex("x25519_asn_test.json")
|
| 506 |
+
self.add_tests_ascii("x25519_pem_test.json")
|
| 507 |
+
self.add_tests_ascii("x25519_jwk_test.json")
|
| 508 |
+
|
| 509 |
+
def shortDescription(self):
|
| 510 |
+
return self.desc
|
| 511 |
+
|
| 512 |
+
def test_verify(self, tv):
|
| 513 |
+
|
| 514 |
+
if tv.encoding == "XdhComp":
|
| 515 |
+
try:
|
| 516 |
+
public_key = import_x25519_public_key(tv.public)
|
| 517 |
+
except ValueError as e:
|
| 518 |
+
assert tv.valid
|
| 519 |
+
assert tv.warning
|
| 520 |
+
assert "LowOrderPublic" in tv.flags
|
| 521 |
+
assert "Invalid Curve25519" in str(e)
|
| 522 |
+
return
|
| 523 |
+
private_key = import_x25519_private_key(tv.private)
|
| 524 |
+
elif tv.encoding in ("XdhAsnComp", "XdhPemComp"):
|
| 525 |
+
try:
|
| 526 |
+
public_key = ECC.import_key(tv.public)
|
| 527 |
+
private_key = ECC.import_key(tv.private)
|
| 528 |
+
except ECC.UnsupportedEccFeature as e:
|
| 529 |
+
assert not tv.valid
|
| 530 |
+
assert "Unsupported ECC" in str(e)
|
| 531 |
+
return
|
| 532 |
+
except ValueError:
|
| 533 |
+
assert tv.valid
|
| 534 |
+
assert tv.warning
|
| 535 |
+
assert "LowOrderPublic" in tv.flags
|
| 536 |
+
return
|
| 537 |
+
elif tv.encoding == "XdhJwkComp":
|
| 538 |
+
|
| 539 |
+
if 'y' in tv.public:
|
| 540 |
+
return
|
| 541 |
+
if 'x' not in tv.public:
|
| 542 |
+
return
|
| 543 |
+
if 'x' not in tv.private:
|
| 544 |
+
return
|
| 545 |
+
if tv.public.get('kty') != 'OKP':
|
| 546 |
+
return
|
| 547 |
+
if tv.public.get('crv') != 'X25519':
|
| 548 |
+
return
|
| 549 |
+
if tv.private.get('crv') != 'X25519':
|
| 550 |
+
return
|
| 551 |
+
|
| 552 |
+
def base64url_decode(input_str):
|
| 553 |
+
input_str = input_str.replace('-', '+').replace('_', '/')
|
| 554 |
+
padding = 4 - (len(input_str) % 4)
|
| 555 |
+
if padding != 4:
|
| 556 |
+
input_str += '=' * padding
|
| 557 |
+
decoded_bytes = base64.b64decode(input_str)
|
| 558 |
+
return decoded_bytes
|
| 559 |
+
|
| 560 |
+
jwk_public = base64url_decode(tv.public['x'])
|
| 561 |
+
jwk_private = base64url_decode(tv.private['d'])
|
| 562 |
+
|
| 563 |
+
try:
|
| 564 |
+
public_key = import_x25519_public_key(jwk_public)
|
| 565 |
+
private_key = import_x25519_private_key(jwk_private)
|
| 566 |
+
except ValueError as e:
|
| 567 |
+
if tv.valid:
|
| 568 |
+
assert tv.warning
|
| 569 |
+
assert "LowOrderPublic" in tv.flags
|
| 570 |
+
assert "Invalid Curve25519" in str(e)
|
| 571 |
+
return
|
| 572 |
+
else:
|
| 573 |
+
assert "Incorrect length" in str(e)
|
| 574 |
+
return
|
| 575 |
+
except ValueError:
|
| 576 |
+
assert tv.valid
|
| 577 |
+
else:
|
| 578 |
+
raise ValueError("Unknown encoding", tv.encoding)
|
| 579 |
+
|
| 580 |
+
try:
|
| 581 |
+
z = key_agreement(static_pub=public_key,
|
| 582 |
+
static_priv=private_key,
|
| 583 |
+
kdf=lambda x: x)
|
| 584 |
+
except ValueError:
|
| 585 |
+
assert not tv.valid
|
| 586 |
+
except TypeError as e:
|
| 587 |
+
assert not tv.valid
|
| 588 |
+
assert "incompatible curve" in str(e)
|
| 589 |
+
else:
|
| 590 |
+
self.assertEqual(z, tv.shared)
|
| 591 |
+
assert tv.valid
|
| 592 |
+
|
| 593 |
+
def runTest(self):
|
| 594 |
+
for tv in self.tv:
|
| 595 |
+
self.desc = "Wycheproof XECDH Verify Test #%d (%s, %s)" % (tv.id, tv.comment, tv.filename)
|
| 596 |
+
self.test_verify(tv)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def get_tests(config={}):
|
| 600 |
+
|
| 601 |
+
tests = []
|
| 602 |
+
tests += list_test_cases(FIPS_ECDH_Tests_KAT)
|
| 603 |
+
tests += [TestVectorsECDHWycheproof()]
|
| 604 |
+
tests += list_test_cases(ECDH_Tests)
|
| 605 |
+
tests += list_test_cases(X25519_Tests)
|
| 606 |
+
tests += list_test_cases(X448_Tests)
|
| 607 |
+
tests += [TestVectorsXECDHWycheproof()]
|
| 608 |
+
|
| 609 |
+
slow_tests = config.get('slow_tests')
|
| 610 |
+
if slow_tests:
|
| 611 |
+
pass
|
| 612 |
+
|
| 613 |
+
return tests
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
if __name__ == '__main__':
|
| 617 |
+
def suite():
|
| 618 |
+
return unittest.TestSuite(get_tests())
|
| 619 |
+
unittest.main(defaultTest='suite')
|