コード例 #1
0
def solve_hnp(samples):
    d = len(samples)
    q = order

    B = IntegerMatrix(d + 2, d + 2)
    for i in range(d):
        t, u, v = samples[i]
        scale = q / v
        B[i, i] = q * scale
        B[d, i] = t * scale
        B[d + 1, i] = u * scale
    B[d, d] = 1
    B[d + 1, d + 1] = q

    M = GSO.Mat(B)
    L_red = LLL.Reduction(M)
    bkzparam = BKZ.Param(block_size=20)
    B_red = BKZ.Reduction(M, L_red, bkzparam)
    B_red()

    if B[1, d + 1] > 0:
        x = -1 * B[1, d]
    else:
        x = B[1, d]
    if x < 0:
        x += q

    private_value = 834818473318008049647448379209460658614088501345180055220225408308906924726
    print x == private_value
    priv = ec.derive_private_key(x, pub.curve, OSSL)
    original = ec.derive_private_key(private_value, pub.curve, OSSL)
    return priv, original
コード例 #2
0
ファイル: test_ec.py プロジェクト: simo5/cryptography
def test_derive_point_at_infinity(backend):
    curve = ec.SECP256R1()
    _skip_curve_unsupported(backend, curve)
    # order of the curve
    q = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
    with pytest.raises(ValueError, match="Unable to derive"):
        ec.derive_private_key(q, ec.SECP256R1())
コード例 #3
0
 def get_shared_secret_secpr1(client_private_key, server_public_key,
                              curve_class):
     client_private_key_int = int.from_bytes(client_private_key,
                                             Crypto_Helper.ENDINESS)
     private_key = derive_private_key(client_private_key_int, curve_class(),
                                      default_backend())
     server_public_key_int = int.from_bytes(client_private_key,
                                            Crypto_Helper.ENDINESS)
     public_key = derive_private_key(server_public_key_int, curve_class(),
                                     default_backend())
     return private_key.exchange(ECDH(), public_key)
コード例 #4
0
    def __init__(self):
        self.neighbors = set()

        # Keep this safe!
        self._wallet_seed = int.from_bytes(urandom(16), byteorder='big')
        self._private_key = ec.derive_private_key(self._wallet_seed,
                                                  ec.SECP384R1())
コード例 #5
0
    def _derive_key(secret: bytes, index: int, key_len: int) -> bytes:
        retry = 0

        # secp256k1 curve order
        curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
        while True:
            digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
            digest.update(struct.pack(">IB", index, retry))
            digest.update(secret)
            md = digest.finalize()

            private_value = int.from_bytes(md, "big")
            if private_value < curve_order and private_value != 0:
                break
            retry += 1

        key = ec.derive_private_key(private_value, ec.SECP256K1(),
                                    default_backend())
        public_key = key.public_key()

        digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
        digest.update(
            public_key.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint,
            ))
        return digest.finalize()[:key_len]
コード例 #6
0
    def __msg2_sign(self, msg2, blob):
        priv_sig_key_bytes = bytes().fromhex(
            AttestationContext.common_ec_private_key_hex)
        priv_sig_key_int = int.from_bytes(priv_sig_key_bytes,
                                          byteorder='little',
                                          signed=False)
        common_ec_key = ec.derive_private_key(priv_sig_key_int, P_256,
                                              OPENSSL_BACKEND)

        sig_material = bytearray()
        sig_material += self.gb_x
        sig_material += self.gb_y
        sig_material += self.ga_x
        sig_material += self.ga_y

        # generate signature
        signature_der = common_ec_key.sign(bytes(sig_material),
                                           ec.ECDSA(SHA256()))
        r, s = decode_dss_signature(signature_der)
        sig_x = r.to_bytes(32, byteorder='little')
        sig_y = s.to_bytes(32, byteorder='little')
        # append to the binary blob to me CMACed
        blob += sig_x
        blob += sig_y
        # append to msg2
        sig_sp = {}
        sig_sp['x_coord'] = base64.b64encode(sig_x).decode('utf-8')
        sig_sp['y_coord'] = base64.b64encode(sig_y).decode('utf-8')
        msg2['sig_sp'] = sig_sp
コード例 #7
0
 def __init__(self, secret, algorithm=None):
     if algorithm is None:
         algorithm = DEFAULT_SIGN_ALGORITHM
     
     assert algorithm in ALGORITHMS, "Unknown algorithm"
     if isinstance(secret, six.string_types): secret = secret.encode("ascii")
     
     self._ecdsa = None
     self._rsa = None
     self._hash = None
     self.sign_algorithm, self.hash_algorithm = algorithm.split('-')
     
     if self.sign_algorithm == 'rsa':
         try:
             rsa_key = RSA.importKey(secret)
             self._rsa = PKCS1_v1_5.new(rsa_key)
             self._hash = HASHES[self.hash_algorithm]
         except ValueError:
           raise HttpSigException("Invalid key.")
     elif self.sign_algorithm == 'ecdsa':
         try:
             curve = ec.SECP256K1()
             self._ecdsa = ec.derive_private_key(long(secret, 16), curve, default_backend())
             self._hash = HASHES[self.hash_algorithm]
         except ValueError:
           raise HttpSigException("Invalid key.")
     elif self.sign_algorithm == 'hmac':
         self._hash = HMAC.new(secret, digestmod=HASHES[self.hash_algorithm])
コード例 #8
0
def create_key_signature(private_key: bytes,
                         challenger_public_key: bytes,
                         enclave_public_key: bytes):

    logging.info("Creating key signature")

    assert len(challenger_public_key) == 64
    assert len(enclave_public_key) == 64

    # Reverse public key byte order
    g_b = challenger_public_key[:32][::-1] + challenger_public_key[32:][::-1]
    g_a = enclave_public_key[:32][::-1] + enclave_public_key[32:][::-1]

    gb_ga = g_b + g_a
    logging.debug("gb_ga: %r | %r\n", g_b.hex(), g_a.hex())

    private_value = int.from_bytes(private_key, byteorder='big')
    ec_private_key = ec.derive_private_key(private_value, EC_CURVE, default_backend())

    der_signature = ec_private_key.sign(gb_ga, ec.ECDSA(hashes.SHA256()))
    r, s = utils.decode_dss_signature(der_signature)
    signature = r.to_bytes(32, byteorder='big') + s.to_bytes(32, byteorder='big')

    logging.debug("challenger_public_key (g_b): %r | %r\n", challenger_public_key[:32].hex(), challenger_public_key[32:].hex())
    logging.debug("enclave_public_key (g_a): %r | %r\n", enclave_public_key[:32].hex(), enclave_public_key[32:].hex())
    logging.debug("signature: %r | %r\n", signature[:32].hex(), signature[32:].hex())

    assert len(signature) == 64
    return signature
コード例 #9
0
    def shared_secret(private_key: 'CK', public_key: 'CK') -> bytes:
        """ Compute the shared secret. """

        if public_key.crv == X25519:
            d = X25519PrivateKey.from_private_bytes(private_key.d)
            x = X25519PublicKey.from_public_bytes(public_key.x)
            secret = d.exchange(x)
        elif public_key.crv == X448:
            d = X448PrivateKey.from_private_bytes(private_key.d)

            x = X448PublicKey.from_public_bytes(public_key.x)
            secret = d.exchange(x)
        elif public_key.crv == P256:
            d = ec.derive_private_key(int(hexlify(private_key.d), 16),
                                      SECP256R1(), default_backend())

            x = ec.EllipticCurvePublicNumbers(int(hexlify(public_key.x), 16),
                                              int(hexlify(public_key.y), 16),
                                              SECP256R1())
            x = x.public_key()
            secret = d.exchange(ec.ECDH(), x)
        else:
            raise CoseIllegalCurve(f"{public_key.crv} is unsupported")

        return secret
コード例 #10
0
def test_ecdh_ecpoint(backend, wycheproof):
    curve = _CURVES[wycheproof.testgroup["curve"]]
    _skip_exchange_algorithm_unsupported(backend, ec.ECDH(), curve)

    private_key = ec.derive_private_key(
        int(wycheproof.testcase["private"], 16), curve, backend)
    # We don't support compressed points
    if (wycheproof.has_flag("CompressedPoint")
            or not wycheproof.testcase["public"]):
        with pytest.raises(ValueError):
            ec.EllipticCurvePublicNumbers.from_encoded_point(
                curve, binascii.unhexlify(wycheproof.testcase["public"]))
        return

    public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(
        curve, binascii.unhexlify(wycheproof.testcase["public"]))
    if wycheproof.testcase["comment"] == "point is not on curve":
        assert wycheproof.invalid
        with pytest.raises(ValueError):
            public_numbers.public_key(backend)
        return

    assert wycheproof.valid or wycheproof.acceptable
    public_key = public_numbers.public_key(backend)
    computed_shared = private_key.exchange(ec.ECDH(), public_key)
    expected_shared = binascii.unhexlify(wycheproof.testcase["shared"])
    assert computed_shared == expected_shared
コード例 #11
0
ファイル: ecdsalib.py プロジェクト: mofei168888/virtualchain
def get_pubkey_hex(privatekey_hex):
    """
    Get the uncompressed hex form of a private key
    """
    if not isinstance(privatekey_hex, (str, unicode)):
        raise ValueError("private key is not a hex string but {}".format(
            str(type(privatekey_hex))))

    # remove 'compressed' hint
    if len(privatekey_hex) > 64:
        if privatekey_hex[-2:] != '01':
            raise ValueError("private key does not end in 01")

        privatekey_hex = privatekey_hex[:64]

    # get hex public key
    privatekey_int = int(privatekey_hex, 16)
    privk = ec.derive_private_key(privatekey_int, ec.SECP256K1(),
                                  default_backend())
    pubk = privk.public_key()
    x = pubk.public_numbers().x
    y = pubk.public_numbers().y

    pubkey_hex = "04{:064x}{:064x}".format(x, y)
    return pubkey_hex
コード例 #12
0
    def get_private_key_ecc(params: KeeperParams):

        if 'private_key' not in params.config:
            encryption_key_bytes = CommonHelperMethods.generate_encryption_key_bytes(
            )
            private_key_str = CommonHelperMethods.bytes_to_url_safe_str(
                encryption_key_bytes)

            params.config['private_key'] = private_key_str

            with open(params.config_filename, 'r') as json_file:
                config_data = json.load(json_file)

            config_data['private_key'] = private_key_str

            with open(params.config_filename, 'w') as json_file:
                json.dump(config_data, json_file, sort_keys=False, indent=4)
                json_file.close()
        else:
            private_key_str = params.config['private_key']

        encryption_key_int = CommonHelperMethods.url_safe_str_to_int(
            private_key_str)

        private_key = ec.derive_private_key(encryption_key_int, ec.SECP256R1(),
                                            default_backend())

        return private_key
コード例 #13
0
ファイル: utils.py プロジェクト: ncgreene/python-fido2
    def __init__(self, credential_id, app_id):
        if not hasattr(serialization.Encoding, "X962"):
            raise unittest.SkipTest("Requires Cryptography >= 2.5")

        assert isinstance(credential_id, six.binary_type)
        assert isinstance(app_id, six.binary_type)

        # Note: do not use in production, no garantees is provided this is
        # cryptographically safe to use.
        priv_key_params = ConcatKDFHash(
            algorithm=hashes.SHA256(),
            length=32,
            otherinfo=credential_id + app_id,
            backend=default_backend(),
        ).derive(self._priv_key_bytes)
        self.app_id = app_id

        self.priv_key = ec.derive_private_key(bytes2int(priv_key_params),
                                              ec.SECP256R1(),
                                              default_backend())
        self.pub_key = self.priv_key.public_key()
        self.public_key_bytes = self.pub_key.public_bytes(
            serialization.Encoding.X962,
            serialization.PublicFormat.UncompressedPoint)

        self.credential_id = self.key_handle = credential_id
コード例 #14
0
def ecies_decrypt(priv_key, message_parts):
    sender_public_key_obj = ec.EllipticCurvePublicKey.from_encoded_point(
        ec.SECP256K1(), message_parts["ephemPublicKey"])
    private_key_obj = ec.derive_private_key(eth_utils.to_int(priv_key),
                                            ec.SECP256K1(), default_backend())
    aes_shared_key = private_key_obj.exchange(ec.ECDH(), sender_public_key_obj)
    # Now let's do AES-CBC with this, including the hmac matching (modeled after eccrypto code).
    aes_keyhash = hashlib.sha512(aes_shared_key).digest()
    hmac_key = aes_keyhash[32:]
    test_hmac = hmac.new(
        hmac_key, message_parts["iv"] + message_parts["ephemPublicKey"] +
        message_parts["ciphertext"], hashlib.sha256).digest()
    if test_hmac != message_parts["mac"]:
        raise Exception("Mac does not match")
    aes_key = aes_keyhash[:32]
    # Actual decrypt is modeled after ecies.utils.aes_decrypt() - but with CBC mode to match eccrypto.
    aes_cipher = AES.new(aes_key, AES.MODE_CBC, iv=message_parts["iv"])
    try:
        decrypted_bytes = aes_cipher.decrypt(message_parts["ciphertext"])
        # Padding characters (unprintable) may be at the end to fit AES block size, so strip them.
        unprintable_chars = bytes(
            ''.join(map(chr, range(0, 32))).join(map(chr, range(127, 160))),
            'utf-8')
        decrypted_string = decrypted_bytes.rstrip(unprintable_chars).decode(
            "utf-8")
        return decrypted_string
    except:
        raise Exception("Could not decode ciphertext")
コード例 #15
0
ファイル: test_ecdh.py プロジェクト: amauryfa/cryptography
def test_ecdh(backend, wycheproof):
    curve = _CURVES[wycheproof.testcase["curve"]]
    if curve is None:
        pytest.skip(
            "Unsupported curve ({})".format(wycheproof.testcase["curve"])
        )
    _skip_exchange_algorithm_unsupported(backend, ec.ECDH(), curve)

    private_key = ec.derive_private_key(
        int(wycheproof.testcase["private"], 16), curve, backend
    )

    try:
        public_key = serialization.load_der_public_key(
            binascii.unhexlify(wycheproof.testcase["public"]), backend
        )
    except NotImplementedError:
        assert wycheproof.has_flag("UnnamedCurve")
        return
    except ValueError:
        assert wycheproof.invalid or wycheproof.acceptable
        return
    except UnsupportedAlgorithm:
        return

    if wycheproof.valid or wycheproof.acceptable:
        computed_shared = private_key.exchange(ec.ECDH(), public_key)
        expected_shared = binascii.unhexlify(wycheproof.testcase["shared"])
        assert computed_shared == expected_shared
    else:
        with pytest.raises(ValueError):
            private_key.exchange(ec.ECDH(), public_key)
コード例 #16
0
ファイル: ECKeyPair.py プロジェクト: bitlogik/uniblow
 def __init__(self, pv_key_int, curve):
     """An EllipticCurvePrivateKey object"""
     self.curve = curve
     if self.curve == "K1":
         curveobj = K1_CURVE
     elif self.curve == "R1":
         curveobj = R1_CURVE
     if self.curve == "K1" or self.curve == "R1":
         # K1 or R1
         if pv_key_int < 0:
             # No private key provided, generating
             self.key_obj = ec.generate_private_key(
                 curveobj, backends.default_backend())
         else:
             # Create a key pair from the provided key integer
             self.key_obj = ec.derive_private_key(
                 pv_key_int, curveobj, backends.default_backend())
     elif self.curve == "ED":
         if pv_key_int < 0:
             # No private key provided, generating
             seed_bytes = random_generator()
         else:
             # Create a key pair from the provided key integer
             seed_bytes = pv_key_int.to_bytes(32, "big")
         self.key_obj = SigningKey(seed_bytes, RawEncoder)
     else:
         raise ValueError("ECkeypair must be K1, R1 or ED")
コード例 #17
0
ファイル: ecdsakey.py プロジェクト: ploxiln/paramiko-ng
    def _decode_key(self, _raw):
        pkformat, data = _raw
        if pkformat == self.FORMAT_ORIGINAL:
            try:
                key = serialization.load_der_private_key(
                    data, password=None, backend=default_backend()
                )
            except (ValueError, TypeError, AssertionError, UnsupportedAlgorithm) as e:
                raise SSHException(str(e))

        elif pkformat == self.FORMAT_OPENSSH:
            msg = Message(data)
            curve_name = msg.get_text()
            verkey = msg.get_binary()  # noqa: F841
            sigkey = msg.get_mpint()
            curve = self._ECDSA_CURVES.get_by_key_format_identifier("ecdsa-sha2-" + curve_name)
            if not curve:
                raise SSHException("Invalid key curve identifier")
            try:
                key = ec.derive_private_key(sigkey, curve.curve_class(), default_backend())
            except (AttributeError, TypeError) as e:
                raise SSHException(str(e))
        else:
            raise SSHException('unknown private key format.')

        if not isinstance(key, ec.EllipticCurvePrivateKey):
            raise SSHException("Invalid key type")

        self.signing_key = key
        self.verifying_key = key.public_key()
        curve_class = key.curve.__class__
        self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(curve_class)
コード例 #18
0
 def __init__(self, private_key=None):
     '''
     takes in a b64 encoded string or standard text private key and returns a PrivateKey object
     '''
     if private_key:
         base64_data = False
         if isinstance(private_key, str):
             private_key = private_key.encode()
         try:
             data = base64.b64encode(base64.b64decode(private_key))
             if data == private_key:
                 private_key = base64.b64decode(data)
                 base64_data = True
         except binascii.Error:
             pass
         if isinstance(private_key, bytes) and not base64_data:
             self.key = sz.load_pem_private_key(private_key, None,
                                                default_backend())
         elif isinstance(private_key, bytes) and base64_data:
             data = utils.int_from_bytes(private_key, 'big')
             self.key = ec.derive_private_key(data, ec.SECP256R1(),
                                              default_backend())
     else:
         self.key = ec.generate_private_key(ec.SECP256R1(),
                                            default_backend())
     self._pub_key = PEMPublicKey(self.key.public_key())
コード例 #19
0
ファイル: ecdsalib.py プロジェクト: mofei168888/virtualchain
 def __init__(self, privkey_hex):
     """
     Instantiate a signer with a hex-encoded ECDSA private key
     """
     pk_i = decode_privkey_hex(privkey_hex)
     privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())
     self.signer = privk.signer(ec.ECDSA(hashes.SHA256()))
コード例 #20
0
ファイル: ecdsakey.py プロジェクト: HucksApp/SSH_BRUTEFORCE
    def _decode_key(self, data):
        pkformat, data = data
        if pkformat == self._PRIVATE_KEY_FORMAT_ORIGINAL:
            try:
                key = serialization.load_der_private_key(
                    data, password=None, backend=default_backend())
            except (ValueError, AssertionError) as e:
                raise SSHException(str(e))
        elif pkformat == self._PRIVATE_KEY_FORMAT_OPENSSH:
            try:
                msg = Message(data)
                curve_name = msg.get_text()
                verkey = msg.get_binary()  # noqa: F841
                sigkey = msg.get_mpint()
                name = "ecdsa-sha2-" + curve_name
                curve = self._ECDSA_CURVES.get_by_key_format_identifier(name)
                if not curve:
                    raise SSHException("Invalid key curve identifier")
                key = ec.derive_private_key(sigkey, curve.curve_class(),
                                            default_backend())
            except Exception as e:
                # PKey._read_private_key_openssh() should check or return
                # keytype - parsing could fail for any reason due to wrong type
                raise SSHException(str(e))
        else:
            self._got_bad_key_format_id(pkformat)

        self.signing_key = key
        self.verifying_key = key.public_key()
        curve_class = key.curve.__class__
        self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(curve_class)
コード例 #21
0
ファイル: genTestVectors.py プロジェクト: ruturajv/gecko-dev
    def format_testcase(self, testcase, curve):

        result = '\n// Comment: {}'.format(testcase['comment'])
        result += '\n// tcID: {}'.format(testcase['tcId'])
        private_key = ec.derive_private_key(
                int(testcase["private"], 16),
                curve,
                default_backend()
            ).private_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption()
            )
        result += '\n{{{},\n'.format(testcase['tcId'])
        result += '{},\n'.format(string_to_hex_array(bytes.hex(private_key)))
        result += '{},\n'.format(string_to_hex_array(testcase['public']))
        result += '{},\n'.format(string_to_hex_array(testcase['shared']))
        invalid_asn = 'InvalidAsn' in testcase['flags']

        # Note: This classifies "Acceptable" tests cases as invalid.
        # As this represents a gray area, manual adjustments may be
        # necessary to match NSS' implementation.
        valid = testcase['result'] == 'valid'

        result += '{},\n'.format(str(invalid_asn).lower())
        result += '{}}},\n'.format(str(valid).lower())

        return result
コード例 #22
0
def generate_self_signed_certificate(
    host: str,
    private_key: SecretKey = None,
    days_valid: int = 365,
    curve: ClassVar[EllipticCurve] = _TLS_CURVE,
) -> Tuple[Certificate, _EllipticCurvePrivateKey]:

    if private_key:
        private_bn = int.from_bytes(private_key.to_secret_bytes(), 'big')
        private_key = ec.derive_private_key(private_value=private_bn,
                                            curve=curve())
    else:
        private_key = ec.generate_private_key(curve(), default_backend())
    public_key = private_key.public_key()

    now = datetime.datetime.utcnow()
    fields = [x509.NameAttribute(NameOID.COMMON_NAME, host)]

    subject = issuer = x509.Name(fields)
    cert = x509.CertificateBuilder().subject_name(subject)
    cert = cert.issuer_name(issuer)
    cert = cert.public_key(public_key)
    cert = cert.serial_number(x509.random_serial_number())
    cert = cert.not_valid_before(now)
    cert = cert.not_valid_after(now + datetime.timedelta(days=days_valid))
    cert = cert.add_extension(x509.SubjectAlternativeName(
        [x509.IPAddress(IPv4Address(host))]),
                              critical=False)
    cert = cert.sign(private_key, hashes.SHA512(), default_backend())

    return cert, private_key
コード例 #23
0
ファイル: test_ecdh.py プロジェクト: mercury0912/cryptography
def test_ecdh(backend, wycheproof):
    curve = _CURVES[wycheproof.testgroup["curve"]]
    if curve is None:
        pytest.skip("Unsupported curve ({})".format(
            wycheproof.testgroup["curve"]))
    _skip_exchange_algorithm_unsupported(backend, ec.ECDH(), curve)

    private_key = ec.derive_private_key(
        int(wycheproof.testcase["private"], 16), curve, backend)

    try:
        public_key = serialization.load_der_public_key(
            binascii.unhexlify(wycheproof.testcase["public"]), backend)
    except NotImplementedError:
        assert wycheproof.has_flag("UnnamedCurve")
        return
    except ValueError:
        assert wycheproof.invalid or wycheproof.acceptable
        return
    except UnsupportedAlgorithm:
        return

    if wycheproof.valid or wycheproof.acceptable:
        computed_shared = private_key.exchange(ec.ECDH(), public_key)
        expected_shared = binascii.unhexlify(wycheproof.testcase["shared"])
        assert computed_shared == expected_shared
    else:
        with pytest.raises(ValueError):
            private_key.exchange(ec.ECDH(), public_key)
コード例 #24
0
ファイル: ecies.py プロジェクト: divyanks/py-evm-1
def ecdh_agree(privkey: datatypes.PrivateKey, pubkey: datatypes.PublicKey) -> bytes:
    """Performs a key exchange operation using the ECDH algorithm."""
    privkey_as_int = int(cast(int, privkey))
    ec_privkey = ec.derive_private_key(privkey_as_int, CURVE, default_backend())
    pubkey_bytes = b'\x04' + pubkey.to_bytes()
    pubkey_nums = ec.EllipticCurvePublicNumbers.from_encoded_point(CURVE, pubkey_bytes)
    ec_pubkey = pubkey_nums.public_key(default_backend())
    return ec_privkey.exchange(ec.ECDH(), ec_pubkey)
コード例 #25
0
    def generate_ecc_keys():

        encryption_key_bytes = CommonHelperMethods.generate_encryption_key_bytes()
        private_key_str = CommonHelperMethods.bytes_to_url_safe_str(encryption_key_bytes)
        encryption_key_int = CommonHelperMethods.url_safe_str_to_int(private_key_str)
        private_key = ec.derive_private_key(encryption_key_int, ec.SECP256R1(), default_backend())

        return private_key
コード例 #26
0
ファイル: ecies.py プロジェクト: firefox0x/py-evm
def ecdh_agree(privkey: datatypes.PrivateKey, pubkey: datatypes.PublicKey) -> bytes:
    """Performs a key exchange operation using the ECDH algorithm."""
    privkey_as_int = int(cast(int, privkey))
    ec_privkey = ec.derive_private_key(privkey_as_int, CURVE, default_backend())
    pubkey_bytes = b'\x04' + pubkey.to_bytes()
    pubkey_nums = ec.EllipticCurvePublicNumbers.from_encoded_point(CURVE, pubkey_bytes)
    ec_pubkey = pubkey_nums.public_key(default_backend())
    return ec_privkey.exchange(ec.ECDH(), ec_pubkey)
コード例 #27
0
 def generateSignature(self, pri_key, msg):
     if self.__scheme == SignatureScheme.SHA224withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP224R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA224()))
     elif self.__scheme == SignatureScheme.SHA256withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP256R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA256()))
     elif self.__scheme == SignatureScheme.SHA384withECDSA:
         private_key = ec.derive_private_key(int(pri_key, 16),
                                             ec.SECP384R1(),
                                             default_backend())
         signature = private_key.sign(msg, ec.ECDSA(hashes.SHA384()))
     return signature
コード例 #28
0
def get_public_key(priv_key, curve=curve.P256, hashfunc=sha256, fmt='RAW'):
    if fmt in ['RAW', '04']:
        priv_key = int(priv_key, 16)
        priv_key = ec.derive_private_key(priv_key, curve, backend)
        return point_to_hex_str(priv_key.public_key().public_numbers(),
                                fmt=fmt)
    else:
        raise UnknownPublicKeyFormatError("fmt: '%s'" % fmt)
コード例 #29
0
ファイル: ssh.py プロジェクト: thomas545/cryptography
    def load_private(self, data, pubfields, backend):
        """Make ECDSA private key from data."""
        (curve_name, point), data = self.get_public(data)
        secret, data = _get_mpint(data)

        if (curve_name, point) != pubfields:
            raise ValueError("Corrupt data: ecdsa field mismatch")
        private_key = ec.derive_private_key(secret, self.curve, backend)
        return private_key, data
コード例 #30
0
def ecdh(ecdsa_curve, PrivateKey, PublicKey):
    curve = ec.get_curve_for_oid(get_curve_by_hex_oid(ecdsa_curve))
    assert not(curve is None)

    pub = ec.EllipticCurvePublicKey.from_encoded_point(curve(), PublicKey)
    prv = ec.derive_private_key(int(hexlify(PrivateKey), 16), curve(), default_backend())

    shared_secret = prv.exchange(ec.ECDH(), pub)
    return shared_secret
コード例 #31
0
ファイル: ec.py プロジェクト: ronf/asyncssh
    def construct(cls, curve_id, public_value, private_value):
        """Construct an ECDSA private key"""

        curve, hash_alg = cls.lookup_curve(curve_id)

        priv_key = ec.derive_private_key(private_value, curve(), backend)
        priv = priv_key.private_numbers()
        pub = priv.public_numbers

        return cls(priv_key, curve_id, hash_alg, pub, public_value, priv)
コード例 #32
0
def test_derive_private_key_success(backend):
    curve = ec.SECP256K1()
    _skip_curve_unsupported(backend, curve)

    private_numbers = ec.generate_private_key(curve, backend).private_numbers()

    derived_key = ec.derive_private_key(private_numbers.private_value, curve,
                                        backend)

    assert private_numbers == derived_key.private_numbers()
コード例 #33
0
    def construct(cls, curve_id, public_value, private_value):
        """Construct an ECDSA private key"""

        curve, hash_alg = cls.lookup_curve(curve_id)

        priv_key = ec.derive_private_key(private_value, curve(), backend)
        priv = priv_key.private_numbers()
        pub = priv.public_numbers

        return cls(priv_key, curve_id, hash_alg, pub, public_value, priv)
コード例 #34
0
def testInt(inp):
    try:
        privateKey = ec.derive_private_key(
                inp, pubnum.curve,default_backend())
        if pubnum.public_numbers()==privateKey.public_key().public_numbers():
            return True, privateKey
        else:
            return False, None
    except:
        return False, None
コード例 #35
0
ファイル: test_ec.py プロジェクト: cloudera/hue
def test_derive_private_key_success(backend):
    curve = ec.SECP256K1()
    _skip_curve_unsupported(backend, curve)

    private_numbers = ec.generate_private_key(curve, backend).private_numbers()

    derived_key = ec.derive_private_key(
        private_numbers.private_value, curve, backend
    )

    assert private_numbers == derived_key.private_numbers()
コード例 #36
0
ファイル: __init__.py プロジェクト: web-push-libs/vapid
    def from_raw(cls, private_raw):
        """Initialize VAPID using a private key point in "raw" or
        "uncompressed" form. Raw keys consist of a single, 32 octet
        encoded integer.

        :param private_raw: A private key point in uncompressed form.
        :type private_raw: bytes

        """
        key = ec.derive_private_key(
            int(binascii.hexlify(b64urldecode(private_raw)), 16),
            curve=ec.SECP256R1(),
            backend=default_backend())
        return cls(key)
コード例 #37
0
ファイル: test_ec.py プロジェクト: cloudera/hue
def test_derive_private_key_errors(backend):
    curve = ec.SECP256K1()
    _skip_curve_unsupported(backend, curve)

    with pytest.raises(TypeError):
        ec.derive_private_key('one', curve, backend)

    with pytest.raises(TypeError):
        ec.derive_private_key(10, 'five', backend)

    with pytest.raises(ValueError):
        ec.derive_private_key(-7, curve, backend)