def test_load_invalid_ec_key_from_numbers(self, backend):
        _skip_curve_unsupported(backend, ec.SECP256R1())

        numbers = ec.EllipticCurvePrivateNumbers(
            357646505660320080863666618182642070958081774038609089496899025506,
            ec.EllipticCurvePublicNumbers(
                47250808410327023131573602008345894927686381772325561185532964,
                1120253292479243545483756778742719537373113335231773536789915,
                ec.SECP256R1(),
            ),
        )
        with pytest.raises(ValueError):
            numbers.private_key(backend)

        numbers = ec.EllipticCurvePrivateNumbers(
            357646505660320080863666618182642070958081774038609089496899025506,
            ec.EllipticCurvePublicNumbers(
                -4725080841032702313157360200834589492768638177232556118553296,
                1120253292479243545483756778742719537373113335231773536789915,
                ec.SECP256R1(),
            ),
        )
        with pytest.raises(ValueError):
            numbers.private_key(backend)

        numbers = ec.EllipticCurvePrivateNumbers(
            357646505660320080863666618182642070958081774038609089496899025506,
            ec.EllipticCurvePublicNumbers(
                47250808410327023131573602008345894927686381772325561185532964,
                -1120253292479243545483756778742719537373113335231773536789915,
                ec.SECP256R1(),
            ),
        )
        with pytest.raises(ValueError):
            numbers.private_key(backend)
    def test_elliptic_curve(self):
        backend = MultiBackend([DummyEllipticCurveBackend([ec.SECT283K1])])

        assert backend.elliptic_curve_supported(ec.SECT283K1()) is True

        assert backend.elliptic_curve_signature_algorithm_supported(
            ec.ECDSA(hashes.SHA256()), ec.SECT283K1()) is True

        backend.generate_elliptic_curve_private_key(ec.SECT283K1())

        backend.load_elliptic_curve_private_numbers(
            ec.EllipticCurvePrivateNumbers(
                1, ec.EllipticCurvePublicNumbers(2, 3, ec.SECT283K1())))

        backend.load_elliptic_curve_public_numbers(
            ec.EllipticCurvePublicNumbers(2, 3, ec.SECT283K1()))

        assert backend.elliptic_curve_supported(ec.SECT163K1()) is False

        assert backend.elliptic_curve_signature_algorithm_supported(
            ec.ECDSA(hashes.SHA256()), ec.SECT163K1()) is False

        with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_ELLIPTIC_CURVE):
            backend.generate_elliptic_curve_private_key(ec.SECT163K1())

        with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_ELLIPTIC_CURVE):
            backend.load_elliptic_curve_private_numbers(
                ec.EllipticCurvePrivateNumbers(
                    1, ec.EllipticCurvePublicNumbers(2, 3, ec.SECT163K1())))

        with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_ELLIPTIC_CURVE):
            backend.load_elliptic_curve_public_numbers(
                ec.EllipticCurvePublicNumbers(2, 3, ec.SECT163K1()))
def test_ec_private_numbers_hash():
    numbers1 = ec.EllipticCurvePrivateNumbers(
        1, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve()))
    numbers2 = ec.EllipticCurvePrivateNumbers(
        1, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve()))
    numbers3 = ec.EllipticCurvePrivateNumbers(
        2, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve()))

    assert hash(numbers1) == hash(numbers2)
    assert hash(numbers1) != hash(numbers3)
 def test_private_numbers_ne(self):
     pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1())
     priv = ec.EllipticCurvePrivateNumbers(1, pub)
     assert priv != ec.EllipticCurvePrivateNumbers(
         2, ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1()))
     assert priv != ec.EllipticCurvePrivateNumbers(
         1, ec.EllipticCurvePublicNumbers(2, 2, ec.SECP192R1()))
     assert priv != ec.EllipticCurvePrivateNumbers(
         1, ec.EllipticCurvePublicNumbers(1, 3, ec.SECP192R1()))
     assert priv != ec.EllipticCurvePrivateNumbers(
         1, ec.EllipticCurvePublicNumbers(1, 2, ec.SECP521R1()))
     assert priv != object()
    def load_ec_key():
        with open(os.path.join(BASE_PATH, 'jwk_ec_key.json'), 'r') as infile:
            keyobj = json.load(infile)

        return ec.EllipticCurvePrivateNumbers(
            private_value=decode_value(keyobj['d']),
            public_numbers=load_ec_pub_key().public_numbers())
Beispiel #6
0
def private_to_key(private: "types.TPMT_SENSITIVE",
                   public: "types.TPMT_PUBLIC"):
    key = None
    if private.sensitiveType == TPM2_ALG.RSA:

        p = int.from_bytes(bytes(private.sensitive.rsa), byteorder="big")
        n = int.from_bytes(bytes(public.unique.rsa), byteorder="big")
        e = (public.parameters.rsaDetail.exponent
             if public.parameters.rsaDetail.exponent != 0 else 65537)

        key = _MyRSAPrivateNumbers(p, n, e, rsa.RSAPublicNumbers(
            e, n)).private_key(backend=default_backend())
    elif private.sensitiveType == TPM2_ALG.ECC:

        curve = _get_curve(public.parameters.eccDetail.curveID)
        if curve is None:
            raise ValueError(
                f"unsupported curve: {public.parameters.eccDetail.curveID}")

        p = int.from_bytes(bytes(private.sensitive.ecc), byteorder="big")
        x = int.from_bytes(bytes(public.unique.ecc.x), byteorder="big")
        y = int.from_bytes(bytes(public.unique.ecc.y), byteorder="big")

        key = ec.EllipticCurvePrivateNumbers(
            p, ec.EllipticCurvePublicNumbers(
                x, y, curve())).private_key(backend=default_backend())
    else:
        raise ValueError(f"unsupported key type: {private.sensitiveType}")

    return key
Beispiel #7
0
    def _process_jwk(self, jwk_dict):
        if not jwk_dict.get('kty') == 'EC':
            raise JWKError(
                "Incorrect key type.  Expected: 'EC', Received: %s" %
                jwk_dict.get('kty'))

        if not all(k in jwk_dict for k in ['x', 'y', 'crv']):
            raise JWKError('Mandatory parameters are missing')

        x = base64_to_long(jwk_dict.get('x'))
        y = base64_to_long(jwk_dict.get('y'))
        curve = {
            'P-256': ec.SECP256R1,
            'P-384': ec.SECP384R1,
            'P-521': ec.SECP521R1,
        }[jwk_dict['crv']]

        public = ec.EllipticCurvePublicNumbers(x, y, curve())

        if 'd' in jwk_dict:
            d = base64_to_long(jwk_dict.get('d'))
            private = ec.EllipticCurvePrivateNumbers(d, public)

            return private.private_key(self.cryptography_backend())
        else:
            return public.public_key(self.cryptography_backend())
Beispiel #8
0
    def test_signing_with_example_keys(self, backend, vector, hash_type):
        curve_type = ec._CURVE_TYPES[vector['curve']]

        _skip_ecdsa_vector(backend, curve_type, hash_type)

        key = ec.EllipticCurvePrivateNumbers(
            vector['d'],
            ec.EllipticCurvePublicNumbers(
                vector['x'],
                vector['y'],
                curve_type()
            )
        ).private_key(backend)
        assert key

        pkey = key.public_key()
        assert pkey

        with pytest.warns(CryptographyDeprecationWarning):
            signer = key.signer(ec.ECDSA(hash_type()))
        signer.update(b"YELLOW SUBMARINE")
        signature = signer.finalize()

        with pytest.warns(CryptographyDeprecationWarning):
            verifier = pkey.verifier(signature, ec.ECDSA(hash_type()))
        verifier.update(b"YELLOW SUBMARINE")
        verifier.verify()
Beispiel #9
0
 def private_numbers(self):
     bn = self._backend._lib.EC_KEY_get0_private_key(self._ec_key)
     private_value = self._backend._bn_to_int(bn)
     return ec.EllipticCurvePrivateNumbers(
         private_value=private_value,
         public_numbers=self.public_key().public_numbers()
     )
Beispiel #10
0
    def _fromECComponents(cls, x, y, curve, privateValue=None):
        """
        Build a key from EC components.

        @param x: The affine x component of the public point used for verifying.
        @type x: L{int}

        @param y: The affine y component of the public point used for verifying.
        @type y: L{int}

        @param curve: NIST name of elliptic curve.
        @type curve: L{bytes}

        @param privateValue: The private value.
        @type privateValue: L{int}
        """

        publicNumbers = ec.EllipticCurvePublicNumbers(
            x=x, y=y, curve=_curveTable[curve])
        if privateValue is None:
            # We have public components.
            keyObject = publicNumbers.public_key(default_backend())
        else:
            privateNumbers = ec.EllipticCurvePrivateNumbers(
                private_value=privateValue, public_numbers=publicNumbers)
            keyObject = privateNumbers.private_key(default_backend())

        return cls(keyObject)
Beispiel #11
0
    def test_with_numbers(self, backend, subtests):
        vectors = itertools.product(
            load_vectors_from_file(
                os.path.join("asymmetric", "ECDSA", "FIPS_186-3",
                             "KeyPair.rsp"),
                load_fips_ecdsa_key_pair_vectors,
            ),
            _HASH_TYPES.values(),
        )
        for vector, hash_type in vectors:
            with subtests.test():
                curve_type: typing.Type[ec.EllipticCurve] = ec._CURVE_TYPES[
                    vector["curve"]]

                _skip_ecdsa_vector(backend, curve_type, hash_type)

                key = ec.EllipticCurvePrivateNumbers(
                    vector["d"],
                    ec.EllipticCurvePublicNumbers(vector["x"], vector["y"],
                                                  curve_type()),
                ).private_key(backend)
                assert key

                priv_num = key.private_numbers()
                assert priv_num.private_value == vector["d"]
                assert priv_num.public_numbers.x == vector["x"]
                assert priv_num.public_numbers.y == vector["y"]
                assert curve_type().name == priv_num.public_numbers.curve.name
Beispiel #12
0
    def test_signing_with_example_keys(self, backend, subtests):
        vectors = itertools.product(
            load_vectors_from_file(
                os.path.join("asymmetric", "ECDSA", "FIPS_186-3",
                             "KeyPair.rsp"),
                load_fips_ecdsa_key_pair_vectors,
            ),
            _HASH_TYPES.values(),
        )
        for vector, hash_type in vectors:
            with subtests.test():
                curve_type = ec._CURVE_TYPES[vector["curve"]]

                _skip_ecdsa_vector(backend, curve_type, hash_type)

                key = ec.EllipticCurvePrivateNumbers(
                    vector["d"],
                    ec.EllipticCurvePublicNumbers(vector["x"], vector["y"],
                                                  curve_type()),
                ).private_key(backend)
                assert key

                pkey = key.public_key()
                assert pkey

                with pytest.warns(CryptographyDeprecationWarning):
                    signer = key.signer(ec.ECDSA(hash_type()))
                signer.update(b"YELLOW SUBMARINE")
                signature = signer.finalize()

                with pytest.warns(CryptographyDeprecationWarning):
                    verifier = pkey.verifier(signature, ec.ECDSA(hash_type()))
                verifier.update(b"YELLOW SUBMARINE")
                verifier.verify()
    def from_jwk(cls, jwk):
        """
        Create a :py:class:`~oneid.keychain.Keypair` from a JWK

        :param jwk: oneID-standard JWK
        :return: :py:class:`~oneid.keychain.Keypair` instance
        :raises InvalidFormatError: if not a valid JWK
        """
        if jwk['kty'] != 'EC' or jwk['crv'] != 'P-256':
            raise exceptions.InvalidFormatError

        public_numbers = ec.EllipticCurvePublicNumbers(
            x=int_from_bytes(utils.base64url_decode(jwk['x']), 'big'),
            y=int_from_bytes(utils.base64url_decode(jwk['y']), 'big'),
            curve=ec.SECP256R1(),
        )

        ret = cls()
        ret._public_key = public_numbers.public_key(_BACKEND)

        if 'd' in jwk:
            private_numbers = ec.EllipticCurvePrivateNumbers(
                private_value=int_from_bytes(utils.base64url_decode(jwk['d']), 'big'),
                public_numbers=public_numbers,
            )
            ret._private_key = private_numbers.private_key(_BACKEND)

        if 'kid' in jwk:
            ret.identity = jwk['kid']

        return ret
Beispiel #14
0
    def _process_jwk(self, jwk_dict):
        if not jwk_dict.get("kty") == "EC":
            raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" %
                           jwk_dict.get("kty"))

        if not all(k in jwk_dict for k in ["x", "y", "crv"]):
            raise JWKError("Mandatory parameters are missing")

        x = base64_to_long(jwk_dict.get("x"))
        y = base64_to_long(jwk_dict.get("y"))
        curve = {
            "P-256": ec.SECP256R1,
            "P-384": ec.SECP384R1,
            "P-521": ec.SECP521R1,
        }[jwk_dict["crv"]]

        public = ec.EllipticCurvePublicNumbers(x, y, curve())

        if "d" in jwk_dict:
            d = base64_to_long(jwk_dict.get("d"))
            private = ec.EllipticCurvePrivateNumbers(d, public)

            return private.private_key(self.cryptography_backend())
        else:
            return public.public_key(self.cryptography_backend())
Beispiel #15
0
        def from_jwk(jwk):
            try:
                if isinstance(jwk, str):
                    obj = json.loads(jwk)
                elif isinstance(jwk, dict):
                    obj = jwk
                else:
                    raise ValueError
            except ValueError:
                raise InvalidKeyError("Key is not valid JSON")

            if obj.get("kty") != "EC":
                raise InvalidKeyError("Not an Elliptic curve key")

            if "x" not in obj or "y" not in obj:
                raise InvalidKeyError("Not an Elliptic curve key")

            x = base64url_decode(obj.get("x"))
            y = base64url_decode(obj.get("y"))

            curve = obj.get("crv")
            if curve == "P-256":
                if len(x) == len(y) == 32:
                    curve_obj = ec.SECP256R1()
                else:
                    raise InvalidKeyError(
                        "Coords should be 32 bytes for curve P-256")
            elif curve == "P-384":
                if len(x) == len(y) == 48:
                    curve_obj = ec.SECP384R1()
                else:
                    raise InvalidKeyError(
                        "Coords should be 48 bytes for curve P-384")
            elif curve == "P-521":
                if len(x) == len(y) == 66:
                    curve_obj = ec.SECP521R1()
                else:
                    raise InvalidKeyError(
                        "Coords should be 66 bytes for curve P-521")
            else:
                raise InvalidKeyError(f"Invalid curve: {curve}")

            public_numbers = ec.EllipticCurvePublicNumbers(
                x=int.from_bytes(x, byteorder="big"),
                y=int.from_bytes(y, byteorder="big"),
                curve=curve_obj,
            )

            if "d" not in obj:
                return public_numbers.public_key()

            d = base64url_decode(obj.get("d"))
            if len(d) != len(x):
                raise InvalidKeyError("D should be {} bytes for curve {}",
                                      len(x), curve)

            return ec.EllipticCurvePrivateNumbers(
                int.from_bytes(d, byteorder="big"),
                public_numbers).private_key()
Beispiel #16
0
def _priv_to_private(privkey):
    assert len(privkey) == 32
    private_value = int.from_bytes(privkey, 'big')
    x, y = _point_multiply(private_value)
    public_numbers = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256K1())
    private_numbers = ec.EllipticCurvePrivateNumbers(private_value,
                                                     public_numbers)
    return private_numbers.private_key(openssl.backend)
Beispiel #17
0
def hextokeys(private_key_hex, public_key_hex):
  s = int(private_key_hex, 16)
  x = int(public_key_hex[2:66], 16)
  y = int(public_key_hex[66:], 16)

  keynums = ec.EllipticCurvePrivateNumbers(s, ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()))
  private_key = keynums.private_key(default_backend())
  return (private_key, private_key.public_key())
Beispiel #18
0
def hex_to_priv_key(priv_key_hex, public_key_hex):
    priv_key_value = long(priv_key_hex, 16)
    public_key = hex_to_key(public_key_hex)
    public_numbers = public_key.public_numbers()
    private_numbers = ec.EllipticCurvePrivateNumbers(priv_key_value,
                                                     public_numbers)
    priv_key = private_numbers.private_key(backend)
    return priv_key
Beispiel #19
0
 def test_brainpool_kex(self, backend, vector):
     curve = ec._CURVE_TYPES[vector["curve"].decode("ascii")]
     _skip_exchange_algorithm_unsupported(backend, ec.ECDH(), curve)
     key = ec.EllipticCurvePrivateNumbers(
         int(vector["da"], 16),
         ec.EllipticCurvePublicNumbers(int(vector["x_qa"], 16),
                                       int(vector["y_qa"], 16), curve()),
     ).private_key(backend)
     peer = ec.EllipticCurvePrivateNumbers(
         int(vector["db"], 16),
         ec.EllipticCurvePublicNumbers(int(vector["x_qb"], 16),
                                       int(vector["y_qb"], 16), curve()),
     ).private_key(backend)
     shared_secret = key.exchange(ec.ECDH(), peer.public_key())
     assert shared_secret == binascii.unhexlify(vector["x_z"])
     shared_secret_2 = peer.exchange(ec.ECDH(), key.public_key())
     assert shared_secret_2 == binascii.unhexlify(vector["x_z"])
Beispiel #20
0
    def load_ec_key():
        with open(os.path.join(BASE_PATH, "jwk_ec_key.json"), "r") as infile:
            keyobj = json.load(infile)

        return ec.EllipticCurvePrivateNumbers(
            private_value=decode_value(keyobj["d"]),
            public_numbers=load_ec_pub_key_p_521().public_numbers(),
        )
Beispiel #21
0
def test_ec_numbers():
    numbers = ec.EllipticCurvePrivateNumbers(
        1, ec.EllipticCurvePublicNumbers(2, 3, DummyCurve()))

    assert numbers.private_value == 1
    assert numbers.public_numbers.x == 2
    assert numbers.public_numbers.y == 3
    assert isinstance(numbers.public_numbers.curve, DummyCurve)
Beispiel #22
0
 def _private_value_to_cryptography_private_numbers(self, private_value):
     """
     Return an instance of cryptography PrivateNumbers from the decimal private_value
     """
     public_value_x, public_value_y = self._private_value_to_public_values(private_value)
     public_numbers = PublicKey._public_values_to_cryptography_public_numbers(public_value_x, public_value_y)
     private_numbers = ec.EllipticCurvePrivateNumbers(private_value, public_numbers)
     return private_numbers
    def _run(self, mode):
        if mode == 'encrypt':
            func = ece.encrypt
            local = 'sender'
            remote = 'receiver'
            inp = 'input'
            outp = 'encrypted'
        else:
            func = ece.decrypt
            local = 'receiver'
            remote = 'sender'
            inp = 'encrypted'
            outp = 'input'

        for data in self.legacy_data:
            logmsg('%s: %s' % (mode, data['test']))
            p = data['params'][mode]

            if 'pad' in p and mode == 'encrypt':
                # This library doesn't pad in exactly the same way.
                continue

            if 'keys' in data:
                key = None
                decode_pub = ec.EllipticCurvePublicNumbers.from_encoded_point
                pubnum = decode_pub(ec.SECP256R1(),
                                    b64d(data['keys'][local]['public']))
                d = 0
                dbin = b64d(data['keys'][local]['private'])
                for i in range(0, len(dbin), 4):
                    d = (d << 32) + struct.unpack('!L', dbin[i:i + 4])[0]
                privnum = ec.EllipticCurvePrivateNumbers(d, pubnum)
                private_key = privnum.private_key(default_backend())
            else:
                key = b64d(p['key'])
                private_key = None

            if 'authSecret' in p:
                auth_secret = b64d(p['authSecret'])
            else:
                auth_secret = None
            if 'dh' in p:
                dh = b64d(p['dh'])
            else:
                dh = None

            result = func(
                b64d(data[inp]),
                salt=b64d(p['salt']),
                key=key,
                dh=dh,
                auth_secret=auth_secret,
                keyid=p.get('keyid'),
                private_key=private_key,
                rs=p.get('rs', 4096),
                version=p['version'],
            )
            eq_(b64d(data[outp]), result)
Beispiel #24
0
    def test_key_exchange_with_vectors(self, backend, subtests):
        vectors = load_vectors_from_file(
            os.path.join(
                "asymmetric",
                "ECDH",
                "KASValidityTest_ECCStaticUnified_NOKC_ZZOnly_init.fax",
            ),
            load_kasvs_ecdh_vectors,
        )
        for vector in vectors:
            with subtests.test():
                _skip_exchange_algorithm_unsupported(
                    backend, ec.ECDH(), ec._CURVE_TYPES[vector["curve"]]()
                )

                key_numbers = vector["IUT"]
                private_numbers = ec.EllipticCurvePrivateNumbers(
                    key_numbers["d"],
                    ec.EllipticCurvePublicNumbers(
                        key_numbers["x"],
                        key_numbers["y"],
                        ec._CURVE_TYPES[vector["curve"]](),
                    ),
                )
                # Errno 5-7 indicates a bad public or private key, this
                # doesn't test the ECDH code at all
                if vector["fail"] and vector["errno"] in [5, 6, 7]:
                    with pytest.raises(ValueError):
                        private_numbers.private_key(backend)
                    continue
                else:
                    private_key = private_numbers.private_key(backend)

                peer_numbers = vector["CAVS"]
                public_numbers = ec.EllipticCurvePublicNumbers(
                    peer_numbers["x"],
                    peer_numbers["y"],
                    ec._CURVE_TYPES[vector["curve"]](),
                )
                # Errno 1 and 2 indicates a bad public key, this doesn't test
                # the ECDH code at all
                if vector["fail"] and vector["errno"] in [1, 2]:
                    with pytest.raises(ValueError):
                        public_numbers.public_key(backend)
                    continue
                else:
                    peer_pubkey = public_numbers.public_key(backend)

                z = private_key.exchange(ec.ECDH(), peer_pubkey)
                zz = int(hexlify(z).decode("ascii"), 16)
                # At this point fail indicates that one of the underlying keys
                # was changed. This results in a non-matching derived key.
                if vector["fail"]:
                    # Errno 8 indicates Z should be changed.
                    assert vector["errno"] == 8
                    assert zz != vector["Z"]
                else:
                    assert zz == vector["Z"]
Beispiel #25
0
def dummy_generate_key_pair(obj):
    private_key_value = 94761803665136558137557783047955027733968423115106677159790289642479432803037
    public_key_numbers = "042bdab212fa8ba1b7c843301682a4db424d307246c7e1e6083c41d9ca7b098bf30b3d63e2ec6278488c135360456cc054b3444ecc45998c08894cbc1370f5f989"
    public_key_numbers_obj = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256R1(), unhexlify(public_key_numbers))
    obj.P = ec.EllipticCurvePrivateNumbers(private_value=private_key_value, public_numbers=public_key_numbers_obj).private_key(default_backend())
    if obj.transport.server_mode:
        obj.Q_S = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256R1(), unhexlify(public_key_numbers)).public_key(default_backend())
        return
    obj.Q_C = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256R1(), unhexlify(public_key_numbers)).public_key(default_backend())
Beispiel #26
0
def load_jwks(jwks_obj):
    """
    Given a JWKS-formatted dictionary representing a private key,
    return a python-cryptography private key object
    """

    if jwks_obj['kty'] == "RSA":
        n = long_from_bytes(jwks_obj['n'])
        e = long_from_bytes(jwks_obj['e'])
        d = long_from_bytes(jwks_obj['d'])
        public_key_numbers = rsa.RSAPublicNumbers(
            e = e,
            n = n,
        )
        # If loading a partial key, we'll have to recalculate a
        # few of the relevant constants
        if ('p' not in jwks_obj) or ('q' not in jwks_obj):
            p, q = rsa.rsa_recover_prime_factors(n, e, d)
        else:
            p = long_from_bytes(jwks_obj['p'])
            q = long_from_bytes(jwks_obj['q'])
        if 'qi' not in jwks_obj:
            qi = rsa.rsa_crt_iqmp(p, q)
        else:
            qi = long_from_bytes(jwks_obj['qi'])
        if 'dp' not in jwks_obj:
            dmp1 = rsa.rsa_crt_dmp1(d, p)
        else:
            dmp1 = long_from_bytes(jwks_obj['dp'])
        if 'dq' not in jwks_obj:
            dmq1 = rsa.rsa_crt_dmq1(d, q)
        else:
            dmq1 = long_from_bytes(jwks_obj['dq'])
        private_key_numbers = rsa.RSAPrivateNumbers(
            p = p,
            q = q,
            d = d,
            dmp1 = dmp1,
            dmq1 = dmq1,
            iqmp = qi,
            public_numbers = public_key_numbers
        )
        return private_key_numbers.private_key(default_backend())
    elif jwks_obj['kty'] == 'EC':
        public_key_numbers = ec.EllipticCurvePublicNumbers(
            long_from_bytes(jwks_obj['x']),
            long_from_bytes(jwks_obj['y']),
            ec.SECP256R1()
        )
        private_key_numbers = ec.EllipticCurvePrivateNumbers(
            long_from_bytes(jwks_obj['d']),
            public_key_numbers
        )
        return private_key_numbers.private_key(default_backend())
    else:
        raise scitokens.scitokens.UnsupportedKeyException("Issuer public key not supported.")
Beispiel #27
0
    def construct(cls, curve_id, public_value, private_value):
        """Construct an ECDSA private key"""

        curve, hash_alg = cls.lookup_curve(curve_id)
        pub = ec.EllipticCurvePublicNumbers.from_encoded_point(
            curve(), public_value)
        priv = ec.EllipticCurvePrivateNumbers(private_value, pub)
        priv_key = priv.private_key(backend)

        return cls(curve_id, hash_alg, pub, priv, priv_key)
 def _test_ec_private_jwk(key):
     """
     Attempt to read in the key into a private key object
     """
     keys = json.loads(key.decode('utf-8'))
     public_key_numbers = ec.EllipticCurvePublicNumbers(
         long_from_bytes(keys['keys'][0]['x']),
         long_from_bytes(keys['keys'][0]['y']), ec.SECP256R1())
     private_key_numbers = ec.EllipticCurvePrivateNumbers(
         long_from_bytes(keys['keys'][0]['d']), public_key_numbers)
     return private_key_numbers.private_key(default_backend())
Beispiel #29
0
 def _load_raw_keypair(self, privkey, pubkey):
     """
     _load_raw_keypair - Initializes the priv key
     """
     self.PrivKey = ec.EllipticCurvePrivateNumbers(
         private_value=int_from_bytes(privkey),  # noqa: E126
         public_numbers=ec.EllipticCurvePublicKey.from_encoded_point(
             curve=ec.SECP256R1(),  # noqa: E122
             data=pubkey,  # noqa: E122
         ).public_numbers(),
     ).private_key(backend=_backend)
Beispiel #30
0
 def test_elliptic_curve_private_key_from_numbers(self):
     d = 5634846038258869671139984276180670841223409490498798721258
     y = 4131560123026307384858369684985976479488628761329758810693
     x = 3402090428547195623222463880060959356423657484435591627791
     curve = ec.SECP192R1()
     _skip_curve_unsupported(backend, curve)
     pub_numbers = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve)
     numbers = ec.EllipticCurvePrivateNumbers(private_value=d,
                                              public_numbers=pub_numbers)
     pytest.deprecated_call(backend.elliptic_curve_private_key_from_numbers,
                            numbers)