Example #1
0
def build_vectors(mgf1alg, hashalg, filename):
    vectors = load_vectors_from_file(filename, load_pkcs1_vectors)

    output = []
    for vector in vectors:
        # RSA keys for this must be long enough to accommodate the length of
        # the underlying hash function. This means we can't use the keys from
        # the sha1 test vectors for sha512 tests because 1024-bit keys are too
        # small. Instead we parse the vectors for the test cases, then
        # generate our own 2048-bit keys for each.
        private, _ = vector
        skey = rsa.generate_private_key(65537, 2048, backend)
        pn = skey.private_numbers()
        examples = private["examples"]
        output.append(b"# =============================================")
        output.append(b"# Example")
        output.append(b"# Public key")
        output.append(b"# Modulus:")
        output.append(format(pn.public_numbers.n, "x"))
        output.append(b"# Exponent:")
        output.append(format(pn.public_numbers.e, "x"))
        output.append(b"# Private key")
        output.append(b"# Modulus:")
        output.append(format(pn.public_numbers.n, "x"))
        output.append(b"# Public exponent:")
        output.append(format(pn.public_numbers.e, "x"))
        output.append(b"# Exponent:")
        output.append(format(pn.d, "x"))
        output.append(b"# Prime 1:")
        output.append(format(pn.p, "x"))
        output.append(b"# Prime 2:")
        output.append(format(pn.q, "x"))
        output.append(b"# Prime exponent 1:")
        output.append(format(pn.dmp1, "x"))
        output.append(b"# Prime exponent 2:")
        output.append(format(pn.dmq1, "x"))
        output.append(b"# Coefficient:")
        output.append(format(pn.iqmp, "x"))
        pkey = skey.public_key()
        vectorkey = rsa.RSAPrivateNumbers(
            p=private["p"],
            q=private["q"],
            d=private["private_exponent"],
            dmp1=private["dmp1"],
            dmq1=private["dmq1"],
            iqmp=private["iqmp"],
            public_numbers=rsa.RSAPublicNumbers(
                e=private["public_exponent"],
                n=private["modulus"]
            )
        ).private_key(backend)
        count = 1

        for example in examples:
            message = vectorkey.decrypt(
                binascii.unhexlify(example["encryption"]),
                padding.OAEP(
                    mgf=padding.MGF1(algorithm=hashes.SHA1()),
                    algorithm=hashes.SHA1(),
                    label=None
                )
            )
            assert message == binascii.unhexlify(example["message"])
            ct = pkey.encrypt(
                message,
                padding.OAEP(
                    mgf=padding.MGF1(algorithm=mgf1alg),
                    algorithm=hashalg,
                    label=None
                )
            )
            output.append(
                b"# OAEP Example {0} alg={1} mgf1={2}".format(
                    count, hashalg.name, mgf1alg.name
                )
            )
            count += 1
            output.append(b"# Message:")
            output.append(example["message"])
            output.append(b"# Encryption:")
            output.append(binascii.hexlify(ct))

    return b"\n".join(output)
Example #2
0

def verify_one_vector(vector):
    digest_algorithm = vector['digest_algorithm']
    message = vector['message']
    x = vector['x']
    y = vector['y']
    signature = encode_rfc6979_signature(vector['r'], vector['s'])

    numbers = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256K1())

    key = numbers.public_key(default_backend())

    verifier = key.verifier(
        signature, ec.ECDSA(CRYPTOGRAPHY_HASH_TYPES[digest_algorithm]()))
    verifier.update(message)
    return verifier.verify()


def verify_vectors(vectors):
    for vector in vectors:
        assert verify_one_vector(vector)


vector_path = os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt")

secp256k1_vectors = load_vectors_from_file(vector_path,
                                           load_fips_ecdsa_signing_vectors)

verify_vectors(secp256k1_vectors)
Example #3
0
from __future__ import absolute_import, division, print_function

import binascii
import os

import pytest

from cryptography.exceptions import (AlreadyFinalized, InvalidKey,
                                     UnsupportedAlgorithm)
from cryptography.hazmat.backends.interfaces import ScryptBackend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt, _MEM_LIMIT

from tests.utils import load_nist_vectors, load_vectors_from_file

vectors = load_vectors_from_file(os.path.join("KDF", "scrypt.txt"),
                                 load_nist_vectors)


def _skip_if_memory_limited(memory_limit, params):
    # Memory calc adapted from OpenSSL (URL split over 2 lines, thanks PEP8)
    # https://github.com/openssl/openssl/blob/6286757141a8c6e14d647ec733634a
    # e0c83d9887/crypto/evp/scrypt.c#L189-L221
    blen = int(params["p"]) * 128 * int(params["r"])
    vlen = 32 * int(params["r"]) * (int(params["n"]) + 2) * 4
    memory_required = blen + vlen
    if memory_limit < memory_required:
        pytest.skip("Test exceeds Scrypt memory limit. "
                    "This is likely a 32-bit platform.")


def test_memory_limit_skip():
Example #4
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import pytest

from cryptography.exceptions import InvalidToken, UnsupportedAlgorithm
from cryptography.hazmat.primitives.twofactor.hotp import HOTP
from cryptography.hazmat.primitives import hashes
from tests.utils import load_vectors_from_file, load_nist_vectors
from cryptography.hazmat.primitives.hashes import MD5, SHA1

vectors = load_vectors_from_file("twofactor/rfc-4226.txt", load_nist_vectors)


@pytest.mark.supported(
    only_if=lambda backend: backend.hmac_supported(hashes.SHA1()),
    skip_message="Does not support HMAC-SHA1.")
@pytest.mark.hmac
class TestHOTP(object):
    def test_invalid_key_length(self, backend):
        secret = os.urandom(10)

        with pytest.raises(ValueError):
            HOTP(secret, 6, SHA1(), backend)

    def test_invalid_hotp_length(self, backend):
        secret = os.urandom(16)
Example #5
0
import pretend

import pytest

import six

from cryptography import utils
from cryptography.exceptions import AlreadyFinalized, InvalidSignature, _Reasons
from cryptography.hazmat.backends.interfaces import CMACBackend
from cryptography.hazmat.primitives.ciphers.algorithms import AES, ARC4, TripleDES
from cryptography.hazmat.primitives.cmac import CMAC

from tests.utils import load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm

vectors_aes128 = load_vectors_from_file("CMAC/nist-800-38b-aes128.txt", load_nist_vectors)

vectors_aes192 = load_vectors_from_file("CMAC/nist-800-38b-aes192.txt", load_nist_vectors)

vectors_aes256 = load_vectors_from_file("CMAC/nist-800-38b-aes256.txt", load_nist_vectors)

vectors_aes = vectors_aes128 + vectors_aes192 + vectors_aes256

vectors_3des = load_vectors_from_file("CMAC/nist-800-38b-3des.txt", load_nist_vectors)

fake_key = b"\x00" * 16


@pytest.mark.cmac
class TestCMAC(object):
    @pytest.mark.supported(
Example #6
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import pytest

from cryptography.exceptions import InvalidToken
from cryptography.hazmat.primitives.twofactor.hotp import HOTP
from cryptography.hazmat.primitives import hashes
from tests.utils import load_vectors_from_file, load_nist_vectors
from cryptography.hazmat.primitives.hashes import MD5, SHA1

vectors = load_vectors_from_file(
    "twofactor/rfc-4226.txt", load_nist_vectors)


@pytest.mark.supported(
    only_if=lambda backend: backend.hmac_supported(hashes.SHA1()),
    skip_message="Does not support HMAC-SHA1."
)
@pytest.mark.hmac
class TestHOTP(object):
    def test_invalid_key_length(self, backend):
        secret = os.urandom(10)

        with pytest.raises(ValueError):
            HOTP(secret, 6, SHA1(), backend)

    def test_invalid_hotp_length(self, backend):
Example #7
0
            signature = secret_key.sign(
                message, hashfunc=hash_func, sigencode=sigencode_der
            )

            r, s = sigdecode_der(signature, None)

            yield "Msg = {0}".format(hexlify(message))
            yield "d = {0:x}".format(secret_key.privkey.secret_multiplier)
            yield "Qx = {0:x}".format(public_key.pubkey.point.x())
            yield "Qy = {0:x}".format(public_key.pubkey.point.y())
            yield "R = {0:x}".format(r)
            yield "S = {0:x}".format(s)
            yield ""


def write_file(lines, dest):
    for line in lines:
        print(line)
        print(line, file=dest)


source_path = os.path.join("asymmetric", "ECDSA", "FIPS_186-3", "SigGen.txt")
dest_path = os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt")

fips_vectors = load_vectors_from_file(
    source_path, load_fips_ecdsa_signing_vectors
)

with open_vector_file(dest_path, "w") as dest_file:
    write_file(build_vectors(fips_vectors), dest_file)
Example #8
0
    signature = encode_rfc6979_signature(vector['r'], vector['s'])

    numbers = ec.EllipticCurvePublicNumbers(
        x, y,
        ec.SECP256K1()
    )

    key = numbers.public_key(default_backend())

    verifier = key.verifier(
        signature,
        ec.ECDSA(CRYPTOGRAPHY_HASH_TYPES[digest_algorithm]())
    )
    verifier.update(message)
    return verifier.verify()


def verify_vectors(vectors):
    for vector in vectors:
        assert verify_one_vector(vector)


vector_path = os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt")

secp256k1_vectors = load_vectors_from_file(
    vector_path,
    load_fips_ecdsa_signing_vectors
)

verify_vectors(secp256k1_vectors)
Example #9
0
            r, s = sigdecode_der(signature, None)

            yield "Msg = {0}".format(hexlify(message))
            yield "d = {0:x}".format(secret_key.privkey.secret_multiplier)
            yield "Qx = {0:x}".format(public_key.pubkey.point.x())
            yield "Qy = {0:x}".format(public_key.pubkey.point.y())
            yield "R = {0:x}".format(r)
            yield "S = {0:x}".format(s)
            yield ""


def write_file(lines, dest):
    for line in lines:
        print(line)
        print(line, file=dest)

source_path = os.path.join("asymmetric", "ECDSA", "FIPS_186-3", "SigGen.txt")
dest_path = os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt")

fips_vectors = load_vectors_from_file(
    source_path,
    load_fips_ecdsa_signing_vectors
)

with open_vector_file(dest_path, "w") as dest_file:
    write_file(
        build_vectors(fips_vectors),
        dest_file
    )
Example #10
0
from __future__ import absolute_import, division, print_function

import binascii

import os

import pytest

from cryptography.exceptions import AlreadyFinalized, InvalidKey, UnsupportedAlgorithm
from cryptography.hazmat.backends.interfaces import ScryptBackend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt

from tests.utils import load_nist_vectors, load_vectors_from_file

vectors = load_vectors_from_file(os.path.join("KDF", "scrypt.txt"), load_nist_vectors)


@pytest.mark.requires_backend_interface(interface=ScryptBackend)
class TestScrypt(object):
    @pytest.mark.parametrize("params", vectors)
    def test_derive(self, backend, params):
        password = params["password"]
        work_factor = int(params["n"])
        block_size = int(params["r"])
        parallelization_factor = int(params["p"])
        length = int(params["length"])
        salt = params["salt"]
        derived_key = params["derived_key"]

        scrypt = Scrypt(salt, length, work_factor, block_size, parallelization_factor, backend)
Example #11
0
import pytest

import six

from cryptography import utils
from cryptography.exceptions import (AlreadyFinalized, InvalidSignature,
                                     _Reasons)
from cryptography.hazmat.backends.interfaces import CMACBackend
from cryptography.hazmat.primitives.ciphers.algorithms import (AES, ARC4,
                                                               TripleDES)
from cryptography.hazmat.primitives.cmac import CMAC

from tests.utils import (load_nist_vectors, load_vectors_from_file,
                         raises_unsupported_algorithm)

vectors_aes128 = load_vectors_from_file("CMAC/nist-800-38b-aes128.txt",
                                        load_nist_vectors)

vectors_aes192 = load_vectors_from_file("CMAC/nist-800-38b-aes192.txt",
                                        load_nist_vectors)

vectors_aes256 = load_vectors_from_file("CMAC/nist-800-38b-aes256.txt",
                                        load_nist_vectors)

vectors_aes = vectors_aes128 + vectors_aes192 + vectors_aes256

vectors_3des = load_vectors_from_file("CMAC/nist-800-38b-3des.txt",
                                      load_nist_vectors)

fake_key = b"\x00" * 16