def generate_signer_certificate():
    """Generates a x.509 certificate signed by ECDSA key
    This signer certificate is used to generate the device manifest file and helps 
    ensure the validity/ownership of the manifest contents. This signer certificate's
    Distinguished Name (DN) includes the AWS IoT registration code (FDQN)as the 
    common name and can be helpful for fleet provisioning.

    Signer certificate and key is saved in ./output_files/

    Certificate is set to expire in 1 year.
    """
    print("Generating ECDSA 256-bit prime field key...")
    signer_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                         backend=default_backend())

    signer_key_pem = signer_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    with open(
            os.path.join(os.path.dirname(__file__), "output_files",
                         "signer_key.pem"), "wb") as signer_key_file:
        signer_key_file.write(signer_key_pem)

    print("Generating self-signed x.509 certificate...")
    try:
        aws_iot_reg_code = iot.get_registration_code()
    except ClientError:
        print(ClientError.response['Error']['Code'])
        print(
            "Error with the AWS CLI when running the command 'aws iot get-registration-code'."
        )
        exit(0)

    signer_public_key = signer_key.public_key()
    time_now = datetime.utcnow()
    days_to_expire = 365
    x509_cert = (
        x509.CertificateBuilder().issuer_name(
            x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME,
                                   aws_iot_reg_code['registrationCode']),
            ])).subject_name(
                x509.Name([
                    x509.NameAttribute(NameOID.COMMON_NAME,
                                       aws_iot_reg_code['registrationCode']),
                ])).serial_number(
                    x509.random_serial_number()).public_key(signer_public_key).
        not_valid_before(time_now).not_valid_after(time_now + timedelta(
            days=days_to_expire)).add_extension(
                x509.SubjectKeyIdentifier.from_public_key(signer_public_key),
                False).add_extension(
                    x509.AuthorityKeyIdentifier.from_issuer_public_key(
                        signer_public_key), False).add_extension(
                            x509.BasicConstraints(ca=True, path_length=None),
                            True).sign(signer_key, hashes.SHA256(),
                                       default_backend()))

    signer_cert_pem = x509_cert.public_bytes(
        encoding=serialization.Encoding.PEM)

    with open(
            os.path.join(os.path.dirname(__file__), "output_files",
                         "signer_cert.crt"), "wb") as signer_cert_file:
        signer_cert_file.write(signer_cert_pem)
    print(
        f"Successfully created x.509 certificate with expiration in {days_to_expire} days..."
    )
    assert msg == plain


def test_rsa_with_kid():
    encryption_keys = [RSAKey(use="enc", key=pub_key, kid="some-key-id")]
    jwe = JWE("some content", alg="RSA-OAEP", enc="A256CBC-HS512")
    jwe.encrypt(keys=encryption_keys, kid="some-key-id")


if __name__ == "__main__":
    test_rsa_with_kid()

# Test ECDH-ES

alice = ec.generate_private_key(ec.SECP256R1(), default_backend())
eck_alice = ECKey(key=alice)
bob = ec.generate_private_key(ec.SECP256R1(), default_backend())
eck_bob = ECKey(key=bob)


def test_ecdh_encrypt_decrypt_direct_key():
    # Alice starts of
    jwenc = JWE_EC(plain, alg="ECDH-ES", enc="A128GCM")
    cek, encrypted_key, iv, params, ret_epk = jwenc.enc_setup(plain,
                                                              key=eck_bob)

    kwargs = {
        'params': params,
        'cek': cek,
        'iv': iv,
Beispiel #3
0
def test_ec_public_numbers_repr():
    pn = ec.EllipticCurvePublicNumbers(2, 3, ec.SECP256R1())
    assert repr(pn) == "<EllipticCurvePublicNumbers(curve=secp256r1, x=2, y=3>"
Beispiel #4
0
def generate_key():
    key = ec.generate_private_key(ec.SECP256R1(), default_backend())
    key_pem = key.private_bytes(encoding=Encoding.PEM,
                                format=PrivateFormat.TraditionalOpenSSL,
                                encryption_algorithm=NoEncryption())
    return crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
Beispiel #5
0
l = listen(4433)
r = l.wait_for_connection()

client_hello = r.recv()
client_hello = TlsRecordParser.parse_bytes(client_hello)[0]
client_random = client_hello.subprotocol_messages[0].handshake_data[2:2+4+28]

server_hello = bytes.fromhex("03030c885a93e1648a284b891c7ab5aa4778d691c9a5b8aae125ad6aa3ad317c09cb00c030000015ff01000100000b0004030001020023000000170000")
server_random = bytes.fromhex("0c885a93e1648a284b891c7ab5aa4778d691c9a5b8aae125ad6aa3ad317c09cb")
certs = bytes.fromhex("0003670003643082036030820248a003020102020900c74d63b60e7ac448300d06092a864886f70d01010b05003045310b30090603550406130241553113301106035504080c0a536f6d652d53746174653121301f060355040a0c18496e7465726e6574205769646769747320507479204c7464301e170d3138303731373139343732385a170d3139303731373139343732385a3045310b30090603550406130241553113301106035504080c0a536f6d652d53746174653121301f060355040a0c18496e7465726e6574205769646769747320507479204c746430820122300d06092a864886f70d01010105000382010f003082010a0282010100d04457e8382e43a8b2c9368fd3a0aa841cd98c52d848de3951111772b47e933edc7c61493780a962d87de4541777b700edd5c701b3e9cbd6133f4beea78bfb8e66264adca3d4b115bae86ad913fe520bd3a9ebbc58a32c6baae917440be5ff855c6b61dab162eaf247c52e58085fe3ae7b0dd925b407486a2e017e59671c93e917cdea2b88e76f386864084101c26c4755c2a04ea16b13ac99de2698f188e5276d91b0d10da936be8d350745530c52ae566a6f39abe026b20eb456ff7545932ce0a5a9ca77fbac90f81be99ac7a55716254571b9a6bf218365c20109529b357e7b9d8cad0593a8a40d628c238177ddf65768e30dc89ef4f4765944313290aa510203010001a3533051301d0603551d0e04160414318c23a9cd6c383b8a4beb056c2d342493466776301f0603551d23041830168014318c23a9cd6c383b8a4beb056c2d342493466776300f0603551d130101ff040530030101ff300d06092a864886f70d01010b050003820101000fdfc19b4615666803b65e6a1930980193e4f110f8f384756aac5242871964434a45904b4574501bd8456e134dcc12f3cc395d09078acf4e1c591de07fe015f41b05fd0930492dcb83b2dfcca03bdb589775f274b9379eab317bc473f75aaff7708219a33546bc44c149e55b640436f0d9879eb003df046e50cf01759c10290cd8d200c79ba50adbe8850647c49c040c0137a5136925ff41f78793cfeca7fed3d858b31c2d89182d30dd9641b0a2ddbbd80bf6e1e633a8fe2213ee1d27687f0b2a4241bca615ded6fd821276114be47cd331eaa640aeaf370b966b3e8a2ab9be4b1039e6a8a28decb8613585d8109f47971f3d5406c1b3defff65b14fd5282c0")

r.send(to_record(TlsHandshakeMessage(TlsHandshakeTypeByte.SERVER_HELLO, server_hello)).to_bytes())
r.send(to_record(TlsHandshakeMessage(TlsHandshakeTypeByte.CERTIFICATE, certs)).to_bytes())


privkey = ec.generate_private_key(ec.SECP256R1(), default_backend())

pubkey = privkey.public_key()

def curveparams():
  type = b"\x03" # named_curve
  name = b"\x00\x17" # secp256r1
  keylen = bytes([65])
  pkey = b"\x04" + bytes.fromhex(hex(pubkey.public_numbers().x)[2:].zfill(64) + hex(pubkey.public_numbers().y)[2:].zfill(64))
  sigalgo = b"\x04\x01"
  return type + name + keylen + pkey + sigalgo

to_hash = client_random + server_random + curveparams()[:-2]
hash = sha256(to_hash).digest()

from asn1crypto import algos
Beispiel #6
0
 def test_import_secp256r1(self):
     priv = ec.generate_private_key(ec.SECP256R1(), default_backend())
     self.controller.verify_admin(DEFAULT_ADMIN_PIN)
     self.controller.import_key(KEY_SLOT.SIG, priv)
Beispiel #7
0
 def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
     _skip_curve_unsupported(backend, ec.SECP256R1())
     key = ec.generate_private_key(ec.SECP256R1(), backend)
     with pytest.raises(ValueError):
         key.private_bytes(encoding, fmt, serialization.NoEncryption())
Beispiel #8
0
 def from_raw_public(cls, public_raw):
     key = ec.EllipticCurvePublicKey.from_encoded_point(
         curve=ec.SECP256R1(), data=b64urldecode(public_raw))
     ss = cls()
     ss._public_key = key
     return ss
Beispiel #9
0
import binascii

import pytest

from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends.interfaces import EllipticCurveBackend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec

from .utils import wycheproof_tests
from ..hazmat.primitives.test_ec import _skip_exchange_algorithm_unsupported

_CURVES = {
    "secp224r1": ec.SECP224R1(),
    "secp256r1": ec.SECP256R1(),
    "secp384r1": ec.SECP384R1(),
    "secp521r1": ec.SECP521R1(),
    "secp224k1": None,
    "secp256k1": ec.SECP256K1(),
    "brainpoolP224r1": None,
    "brainpoolP256r1": ec.BrainpoolP256R1(),
    "brainpoolP320r1": None,
    "brainpoolP384r1": ec.BrainpoolP384R1(),
    "brainpoolP512r1": ec.BrainpoolP512R1(),
    "brainpoolP224t1": None,
    "brainpoolP256t1": None,
    "brainpoolP320t1": None,
    "brainpoolP384t1": None,
    "brainpoolP512t1": None,
}
 def test_elliptic_curve_exchange_algorithm_supported(self, monkeypatch):
     monkeypatch.setattr(backend, "_lib", DummyLibrary())
     assert not backend.elliptic_curve_exchange_algorithm_supported(
         ec.ECDH(), ec.SECP256R1()
     )
from time import process_time_ns

from cryptography.hazmat.primitives.asymmetric import ec

# Recommended curves from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
CURVE_MAP = {
    'P-192': ec.SECP192R1(),
    'P-224': ec.SECP224R1(),
    'P-256': ec.SECP256R1(),
    'P-384': ec.SECP384R1()
}


def current_milli_time():
    return process_time_ns()
    def test_unsupported_ec_keys(self):
        _skip_curve_unsupported(backend, ec.SECP256R1())
        private_key = ec.generate_private_key(ec.SECP256R1(), backend)

        with pytest.raises(NotImplementedError):
            backend.create_x509_csr(object(), private_key, hashes.SHA1())
Beispiel #13
0
        "35787109896602102090002196616273211495718603965098"),
    public_numbers=ec.EllipticCurvePublicNumbers(
        curve=ec.SECP384R1(),
        x=int("10036914308591746758780165503819213553101287571902957054148542"
              "504671046744460374996612408381962208627004841444205030"),
        y=int("17337335659928075994560513699823544906448896792102247714689323"
              "575406618073069185107088229463828921069465902299522926"),
    ),
)

EC_KEY_SECP256R1 = ec.EllipticCurvePrivateNumbers(
    private_value=int(
        "271032978511595617649844168316234344656921218699414461240502635010"
        "25776962849"),
    public_numbers=ec.EllipticCurvePublicNumbers(
        curve=ec.SECP256R1(),
        x=int("49325986169170464532722748935508337546545346352733747948730305"
              "442770101441241"),
        y=int("51709162888529903487188595007092772817469799707382623884187518"
              "455962250433661"),
    ),
)

EC_KEY_SECP256K1 = ec.EllipticCurvePrivateNumbers(
    private_value=int(
        "683341569008473593765879222774207677458810362976327530563215318048"
        "64380736732"),
    public_numbers=ec.EllipticCurvePublicNumbers(
        curve=ec.SECP256K1(),
        x=int("59251322975795306609293064274738085741081547489119277536110995"
              "120127593127884"),
class SECP256R1(ECCurves):
    code = b'\x00\x17'
    name = 'secp256r1'

    curve = ec.SECP256R1()
Beispiel #15
0
def generate_ecdsa_private_key():
    return ec.generate_private_key(ec.SECP256R1(), backend=default_backend())
Beispiel #16
0
 def test_prehashed_unsupported_in_signer_ctx(self, backend):
     _skip_curve_unsupported(backend, ec.SECP256R1())
     private_key = ec.generate_private_key(ec.SECP256R1(), backend)
     with pytest.raises(TypeError):
         private_key.signer(ec.ECDSA(Prehashed(hashes.SHA1())))
Beispiel #17
0
def ECDH(slot, iface='hid'):
    ATCA_SUCCESS = 0x00

    # Loading cryptoauthlib(python specific)
    load_cryptoauthlib()

    # Get the target default config
    cfg = eval('cfg_ateccx08a_{}_default()'.format(atca_names_map.get(iface)))

    # Basic Raspberry Pi I2C check
    if 'i2c' == iface and check_if_rpi():
        cfg.cfg.atcai2c.bus = 1

    # Initialize the stack
    assert atcab_init(cfg) == ATCA_SUCCESS

    # Get the device type from the info command
    info = bytearray(4)
    assert atcab_info(info) == ATCA_SUCCESS
    dev_type = get_device_type_id(get_device_name(info))

    # Check device type
    if dev_type in [0, 0x20]:
        raise ValueError('Device does not support ECDH operations')
    elif dev_type != cfg.devtype:
        cfg.dev_type = dev_type
        assert atcab_release() == ATCA_SUCCESS
        time.sleep(1)
        assert atcab_init(cfg) == ATCA_SUCCESS

    # Create a host private key
    host_key = ec.generate_private_key(ec.SECP256R1(), default_backend())

    # Convert host's public key into ATECCx08 format
    host_pub = host_key.public_key().public_numbers().encode_point()[1:]

    # Display the host's public key
    print("\nHost Public Key:")
    print(pretty_print_hex(host_pub, indent='    '))

    # Buffers for device public key and shared secret
    device_pub = bytearray(64)
    device_shared = bytearray(32)

    # Generate a device private key and perform the ECDH operation
    # This step is using the unencrypted form of the ECDH calls due to configuration details that will be specific
    # for the use case. See atcab_ecdh_enc and atcab_ecdh_tempkey_ioenc functions.
    if dev_type == get_device_type_id('ATECC508A'):
        assert atcab_genkey(slot, device_pub) == ATCA_SUCCESS
        assert atcab_ecdh(slot, host_pub, device_shared) == ATCA_SUCCESS
    else:
        assert atcab_genkey(0xFFFF, device_pub) == ATCA_SUCCESS
        assert atcab_ecdh_tempkey(host_pub, device_shared) == ATCA_SUCCESS

    # Display the device's public key
    print("\nDevice public key:")
    print(pretty_print_hex(device_pub, indent='    '))

    # Convert device public key to a cryptography public key object
    device_pub = ec.EllipticCurvePublicNumbers.from_encoded_point(
        ec.SECP256R1(), b'\04' + device_pub).public_key(default_backend())

    # Perform the host side ECDH computation
    host_shared = host_key.exchange(ec.ECDH(), device_pub)

    # Display the host side computed symmetric key
    print('\nHost Calculated Shared Secret:')
    print(pretty_print_hex(host_shared, indent='    '))

    # Display the device side computed symmetric key
    print('\nDevice Calculated Shared Secret:')
    print(pretty_print_hex(device_shared, indent='    '))

    # Compare both independently calculated
    print('\nComparing host and device generated secrets:')
    if host_shared == device_shared:
        print("    Success - Generated secrets match!")
    else:
        print("    Error in calculation")

    assert atcab_release() == ATCA_SUCCESS
Beispiel #18
0
 def test_prehashed_unsupported_in_verifier_ctx(self, backend):
     _skip_curve_unsupported(backend, ec.SECP256R1())
     private_key = ec.generate_private_key(ec.SECP256R1(), backend)
     public_key = private_key.public_key()
     with pytest.raises(TypeError):
         public_key.verifier(b"0" * 64, ec.ECDSA(Prehashed(hashes.SHA1())))
Beispiel #19
0
 def test_public_bytes_rejects_invalid(self, encoding, fmt, backend):
     _skip_curve_unsupported(backend, ec.SECP256R1())
     key = ec.generate_private_key(ec.SECP256R1(), backend).public_key()
     with pytest.raises(ValueError):
         key.public_bytes(encoding, fmt)
Beispiel #20
0
def generate_vectors_file(params):
    """
    Generate and store a .h-file with test vectors for one test.

    params -- Dictionary with parameters for test vector generation for the desired test.
    """

    cases = import_testvector(os.path.join(script_dir, params['source_dir'] + params['source_file']))

    base_vectors = ""
    if 'base' in params:
        with open(os.path.join(script_dir, params['base'])) as base:
            base_vectors = base.read()
        base_vectors += "\n\n"

    header = standard_params['license']
    header += "\n"
    header += standard_params['top_comment']
    header += "\n"
    header += "#ifndef " + params['section'] + "\n"
    header += "#define " + params['section'] + "\n"
    header += "\n"

    for include in standard_params['includes']:
        header += "#include " + include + "\n"

    header += "\n"

    if 'includes' in params:
        for include in params['includes']:
            header += "#include " + include + "\n"
        header += "\n"

    shared_defs = []
    vectors_file = base_vectors + params['array_init']

    for group in cases['testGroups']:
        for test in group['tests']:
            if 'key' in group:
                if 'curve' in group['key'] and group['key']['curve'] not in ['secp256r1', 'secp384r1', 'secp521r1']:
                    continue
                vectors_file += params['formatter'].format_testcase(test, group['keyDer'], getSha(group['sha']), group['key']['keySize'], shared_defs)
            elif 'type' in group and group['type'] == 'RsassaPssVerify':
                sLen = group['sLen'] if 'sLen' in group else 0
                vectors_file += params['formatter'].format_testcase(test, group['keyDer'], getSha(group['sha']), getMgfSha(group['mgfSha']), sLen, shared_defs)
            elif 'type' in group and group['type'] == 'RsaesOaepDecrypt':
                vectors_file += params['formatter'].format_testcase(test, group['privateKeyPkcs8'], getSha(group['sha']), getMgfSha(group['mgfSha']), shared_defs)
            elif 'keyDer' in group:
                vectors_file += params['formatter'].format_testcase(test, group['keyDer'], group['keysize'], getSha(group['sha']), shared_defs)
            elif 'privateKeyPkcs8' in group:
                vectors_file += params['formatter'].format_testcase(test, group['privateKeyPkcs8'], group['keysize'], shared_defs)
            elif 'curve' in group:
                if group['curve'] == 'secp256r1':
                    curve = ec.SECP256R1()
                elif group['curve'] == 'secp384r1':
                    curve = ec.SECP384R1()
                elif group['curve'] == 'secp521r1':
                    curve = ec.SECP521R1()
                elif group['curve'] == 'curve25519':
                    curve = "curve25519"
                else:
                    continue
                vectors_file += params['formatter'].format_testcase(test, curve)
            else:
                vectors_file += params['formatter'].format_testcase(test)

    vectors_file = vectors_file[:params['crop_size_end']] + '\n};\n\n'
    vectors_file += "#endif // " + params['section'] + '\n'

    with open(os.path.join(script_dir, params['target']), 'w') as target:
        target.write(header)
        for definition in shared_defs:
            target.write(definition)
        target.write(vectors_file)
Beispiel #21
0
 def generate():
     pk = ec.generate_private_key(ec.SECP256R1(), backend=default_backend())
     return ECDSA256P1(pk)
Beispiel #22
0
import base64
import re
import secrets

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization

EC = ec.SECP256R1()


class Crypto:
    def _modular_inverse(self, a, b):
        _b = b
        x1, x2, y1, y2 = 0, 1, 1, 0
        while b != 0:
            q, r = a // b, a % b
            x, y = x2 - x1 * q, y2 - y1 * q
            a, b, x2, x1, y2, y1 = b, r, x1, x, y1, y
        if x2 != 0: x2 = x2 + _b
        return x2

    def _modular_exponentiation(self, b, n, m):
        n = bin(n)
        x = 1
        power = b % m
        for i in range(len(n) - 1, 1, -1):
            if n[i] == '1': x = (x * power) % m
Beispiel #23
0
        raw_private_key = private_key.private_bytes(Encoding.Raw,
                                                    PrivateFormat.Raw,
                                                    NoEncryption())
        raw_public_key = public_key.public_bytes(Encoding.Raw,
                                                 PublicFormat.Raw)
        f_keypair = _FragList([raw_private_key, raw_public_key])

        self.encode_public(public_key, f_priv)
        f_priv.put_sshstr(f_keypair)


_KEY_FORMATS = {
    _SSH_RSA: _SSHFormatRSA(),
    _SSH_DSA: _SSHFormatDSA(),
    _SSH_ED25519: _SSHFormatEd25519(),
    _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()),
    _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()),
    _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()),
}


def _lookup_kformat(key_type):
    """Return valid format or throw error
    """
    if not isinstance(key_type, bytes):
        key_type = memoryview(key_type).tobytes()
    if key_type in _KEY_FORMATS:
        return _KEY_FORMATS[key_type]
    raise UnsupportedAlgorithm("Unsupported key type: %r" % key_type)

Beispiel #24
0
def make_key():
    return ec.generate_private_key(ec.SECP256R1(), default_backend())
Beispiel #25
0
class KexNistp256:

    name = "ecdh-sha2-nistp256"
    hash_algo = sha256
    curve = ec.SECP256R1()

    def __init__(self, transport):
        self.transport = transport
        # private key, client public and server public keys
        self.P = long(0)
        self.Q_C = None
        self.Q_S = None

    def start_kex(self):
        self._generate_key_pair()
        if self.transport.server_mode:
            self.transport._expect_packet(_MSG_KEXECDH_INIT)
            return
        m = Message()
        m.add_byte(c_MSG_KEXECDH_INIT)
        # SEC1: V2.0  2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion
        m.add_string(
            self.Q_C.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint,
            )
        )
        self.transport._send_message(m)
        self.transport._expect_packet(_MSG_KEXECDH_REPLY)

    def parse_next(self, ptype, m):
        if self.transport.server_mode and (ptype == _MSG_KEXECDH_INIT):
            return self._parse_kexecdh_init(m)
        elif not self.transport.server_mode and (ptype == _MSG_KEXECDH_REPLY):
            return self._parse_kexecdh_reply(m)
        raise SSHException(
            "KexECDH asked to handle packet type {:d}".format(ptype)
        )

    def _generate_key_pair(self):
        self.P = ec.generate_private_key(self.curve, default_backend())
        if self.transport.server_mode:
            self.Q_S = self.P.public_key()
            return
        self.Q_C = self.P.public_key()

    def _parse_kexecdh_init(self, m):
        Q_C_bytes = m.get_string()
        self.Q_C = ec.EllipticCurvePublicKey.from_encoded_point(
            self.curve, Q_C_bytes
        )
        K_S = self.transport.get_server_key().asbytes()
        K = self.P.exchange(ec.ECDH(), self.Q_C)
        K = long(hexlify(K), 16)
        # compute exchange hash
        hm = Message()
        hm.add(
            self.transport.remote_version,
            self.transport.local_version,
            self.transport.remote_kex_init,
            self.transport.local_kex_init,
        )
        hm.add_string(K_S)
        hm.add_string(Q_C_bytes)
        # SEC1: V2.0  2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion
        hm.add_string(
            self.Q_S.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint,
            )
        )
        hm.add_mpint(long(K))
        H = self.hash_algo(hm.asbytes()).digest()
        self.transport._set_K_H(K, H)
        sig = self.transport.get_server_key().sign_ssh_data(H)
        # construct reply
        m = Message()
        m.add_byte(c_MSG_KEXECDH_REPLY)
        m.add_string(K_S)
        m.add_string(
            self.Q_S.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint,
            )
        )
        m.add_string(sig)
        self.transport._send_message(m)
        self.transport._activate_outbound()

    def _parse_kexecdh_reply(self, m):
        K_S = m.get_string()
        Q_S_bytes = m.get_string()
        self.Q_S = ec.EllipticCurvePublicKey.from_encoded_point(
            self.curve, Q_S_bytes
        )
        sig = m.get_binary()
        K = self.P.exchange(ec.ECDH(), self.Q_S)
        K = long(hexlify(K), 16)
        # compute exchange hash and verify signature
        hm = Message()
        hm.add(
            self.transport.local_version,
            self.transport.remote_version,
            self.transport.local_kex_init,
            self.transport.remote_kex_init,
        )
        hm.add_string(K_S)
        # SEC1: V2.0  2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion
        hm.add_string(
            self.Q_C.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint,
            )
        )
        hm.add_string(Q_S_bytes)
        hm.add_mpint(K)
        self.transport._set_K_H(K, self.hash_algo(hm.asbytes()).digest())
        self.transport._verify_key(K_S, sig)
        self.transport._activate_outbound()
Beispiel #26
0
def create_ec_key():
    return ec.generate_private_key(ec.SECP256R1())
Beispiel #27
0
 def test_signature_not_bytes(self, backend):
     _skip_curve_unsupported(backend, ec.SECP256R1())
     key = ec.generate_private_key(ec.SECP256R1(), backend)
     public_key = key.public_key()
     with pytest.raises(TypeError):
         public_key.verifier(1234, ec.ECDSA(hashes.SHA256()))
 def _create_ecds_key():  #type() -> EllipticCurvePrivateKey
     return ec.generate_private_key(ec.SECP256R1()).private_bytes(
         serialization.Encoding.DER, serialization.PrivateFormat.PKCS8,
         serialization.NoEncryption())
Beispiel #29
0
def test_ec_key_key_size(backend):
    curve = ec.SECP256R1()
    _skip_curve_unsupported(backend, curve)
    key = ec.generate_private_key(curve, backend)
    assert key.key_size == 256
    assert key.public_key().key_size == 256
Beispiel #30
0
            csr = csr_add_extension.sign(private_key, hashes.SHA1(),
                                         default_backend())
        return {
            'error': True,
            'csr': csr.public_bytes(serialization.Encoding.PEM),
            'priv_key': key
        }
    elif mysf == 'ECDSA':
        if myqd == 'P192':
            private_key = ec.generate_private_key(curve=ec.SECP192R1(),
                                                  backend=default_backend())
        elif myqd == 'P224':
            private_key = ec.generate_private_key(curve=ec.SECP224R1(),
                                                  backend=default_backend())
        elif myqd == 'P256':
            private_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                                  backend=default_backend())
        elif myqd == 'P384':
            private_key = ec.generate_private_key(curve=ec.SECP384R1(),
                                                  backend=default_backend())
        elif myqd == 'P521':
            private_key = ec.generate_private_key(curve=ec.SECP521R1(),
                                                  backend=default_backend())
        else:
            private_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                                  backend=default_backend())

        if key_pass:
            key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,