示例#1
0
def test_ed448_unsupported(backend):
    with raises_unsupported_algorithm(
            _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
        Ed448PublicKey.from_public_bytes(b"0" * 57)

    with raises_unsupported_algorithm(
            _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
        Ed448PrivateKey.from_private_bytes(b"0" * 57)

    with raises_unsupported_algorithm(
            _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
        Ed448PrivateKey.generate()
示例#2
0
def test_ed448_unsupported(backend):
    with raises_unsupported_algorithm(
        _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
    ):
        Ed448PublicKey.from_public_bytes(b"0" * 57)

    with raises_unsupported_algorithm(
        _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
    ):
        Ed448PrivateKey.from_private_bytes(b"0" * 57)

    with raises_unsupported_algorithm(
        _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
    ):
        Ed448PrivateKey.generate()
示例#3
0
    def sign(self,
             to_be_signed: bytes,
             alg: Optional[CoseAlgorithms] = None,
             curve: CoseEllipticCurves = None) -> bytes:
        """
        Computes a digital signature over 'to_be_signed'. The parameter 'alg' and 'curve' parameters are optional in
        case they are already provided by the key object self.

        :param to_be_signed: Data over which the signature is calculated.
        :param alg: An optional algorithm parameter.
        :param curve: An optional curve parameter.
        :return: the signature over the COSE object.
        """

        self._check_key_conf(algorithm=alg,
                             key_operation=KeyOps.SIGN,
                             curve=curve)

        if self.crv == CoseEllipticCurves.ED25519:
            sk = Ed25519PrivateKey.from_private_bytes(self.d)
        elif self._crv == CoseEllipticCurves.ED448:
            sk = Ed448PrivateKey.from_private_bytes(self.d)
        else:
            raise CoseIllegalCurve(
                f"Illegal curve for OKP singing: {self.crv}")

        return sk.sign(to_be_signed)
示例#4
0
 def test_round_trip_private_serialization(
     self, encoding, fmt, encryption, passwd, load_func, backend
 ):
     key = Ed448PrivateKey.generate()
     serialized = key.private_bytes(encoding, fmt, encryption)
     loaded_key = load_func(serialized, passwd, backend)
     assert isinstance(loaded_key, Ed448PrivateKey)
示例#5
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") != "OKP":
                raise InvalidKeyError("Not an Octet Key Pair")

            curve = obj.get("crv")
            if curve != "Ed25519" and curve != "Ed448":
                raise InvalidKeyError(f"Invalid curve: {curve}")

            if "x" not in obj:
                raise InvalidKeyError('OKP should have "x" parameter')
            x = base64url_decode(obj.get("x"))

            try:
                if "d" not in obj:
                    if curve == "Ed25519":
                        return Ed25519PublicKey.from_public_bytes(x)
                    return Ed448PublicKey.from_public_bytes(x)
                d = base64url_decode(obj.get("d"))
                if curve == "Ed25519":
                    return Ed25519PrivateKey.from_private_bytes(d)
                return Ed448PrivateKey.from_private_bytes(d)
            except ValueError as err:
                raise InvalidKeyError("Invalid key parameter") from err
示例#6
0
 def test_pub_priv_bytes_raw(self, vector, backend):
     sk = binascii.unhexlify(vector["secret"])
     pk = binascii.unhexlify(vector["public"])
     private_key = Ed448PrivateKey.from_private_bytes(sk)
     assert (
         private_key.private_bytes(
             serialization.Encoding.Raw,
             serialization.PrivateFormat.Raw,
             serialization.NoEncryption(),
         )
         == sk
     )
     assert (
         private_key.public_key().public_bytes(
             serialization.Encoding.Raw, serialization.PublicFormat.Raw
         )
         == pk
     )
     public_key = Ed448PublicKey.from_public_bytes(pk)
     assert (
         public_key.public_bytes(
             serialization.Encoding.Raw, serialization.PublicFormat.Raw
         )
         == pk
     )
示例#7
0
    def test_invalid_signature(self, backend):
        key = Ed448PrivateKey.generate()
        signature = key.sign(b"test data")
        with pytest.raises(InvalidSignature):
            key.public_key().verify(signature, b"wrong data")

        with pytest.raises(InvalidSignature):
            key.public_key().verify(b"0" * 64, b"test data")
示例#8
0
 def test_buffer_protocol(self, backend):
     private_bytes = os.urandom(57)
     key = Ed448PrivateKey.from_private_bytes(bytearray(private_bytes))
     assert (key.private_bytes(
         serialization.Encoding.Raw,
         serialization.PrivateFormat.Raw,
         serialization.NoEncryption(),
     ) == private_bytes)
示例#9
0
 def test_buffer_protocol(self, backend):
     private_bytes = os.urandom(57)
     key = Ed448PrivateKey.from_private_bytes(bytearray(private_bytes))
     assert key.private_bytes(
         serialization.Encoding.Raw,
         serialization.PrivateFormat.Raw,
         serialization.NoEncryption()
     ) == private_bytes
示例#10
0
    def test_invalid_signature(self, backend):
        key = Ed448PrivateKey.generate()
        signature = key.sign(b"test data")
        with pytest.raises(InvalidSignature):
            key.public_key().verify(signature, b"wrong data")

        with pytest.raises(InvalidSignature):
            key.public_key().verify(b"0" * 64, b"test data")
示例#11
0
    def sign(cls, key: 'OKP', data: bytes) -> bytes:
        if key.crv.fullname == 'ED25519':
            sk = Ed25519PrivateKey.from_private_bytes(key.d)
        elif key.crv.fullname == 'ED448':
            sk = Ed448PrivateKey.from_private_bytes(key.d)
        else:
            raise CoseException(f"Illegal curve for OKP singing: {key.crv}")

        return sk.sign(data)
示例#12
0
    def test_invalid_public_bytes(self, backend):
        key = Ed448PrivateKey.generate().public_key()
        with pytest.raises(ValueError):
            key.public_bytes(
                serialization.Encoding.Raw,
                serialization.PublicFormat.SubjectPublicKeyInfo,
            )

        with pytest.raises(ValueError):
            key.public_bytes(serialization.Encoding.PEM,
                             serialization.PublicFormat.PKCS1)

        with pytest.raises(ValueError):
            key.public_bytes(serialization.Encoding.PEM,
                             serialization.PublicFormat.Raw)
示例#13
0
    def test_sign_input(self, vector, backend):
        if vector.get("context") is not None:
            pytest.skip("ed448 contexts are not currently supported")

        sk = binascii.unhexlify(vector["secret"])
        pk = binascii.unhexlify(vector["public"])
        message = binascii.unhexlify(vector["message"])
        signature = binascii.unhexlify(vector["signature"])
        private_key = Ed448PrivateKey.from_private_bytes(sk)
        computed_sig = private_key.sign(message)
        assert computed_sig == signature
        public_key = private_key.public_key()
        assert (public_key.public_bytes(serialization.Encoding.Raw,
                                        serialization.PublicFormat.Raw) == pk)
        public_key.verify(signature, message)
示例#14
0
 def test_pub_priv_bytes_raw(self, vector, backend):
     sk = binascii.unhexlify(vector["secret"])
     pk = binascii.unhexlify(vector["public"])
     private_key = Ed448PrivateKey.from_private_bytes(sk)
     assert private_key.private_bytes(
         serialization.Encoding.Raw,
         serialization.PrivateFormat.Raw,
         serialization.NoEncryption()
     ) == sk
     assert private_key.public_key().public_bytes(
         serialization.Encoding.Raw, serialization.PublicFormat.Raw
     ) == pk
     public_key = Ed448PublicKey.from_public_bytes(pk)
     assert public_key.public_bytes(
         serialization.Encoding.Raw, serialization.PublicFormat.Raw
     ) == pk
示例#15
0
    def test_sign_input(self, vector, backend):
        if vector.get("context") is not None:
            pytest.skip("ed448 contexts are not currently supported")

        sk = binascii.unhexlify(vector["secret"])
        pk = binascii.unhexlify(vector["public"])
        message = binascii.unhexlify(vector["message"])
        signature = binascii.unhexlify(vector["signature"])
        private_key = Ed448PrivateKey.from_private_bytes(sk)
        computed_sig = private_key.sign(message)
        assert computed_sig == signature
        public_key = private_key.public_key()
        assert public_key.public_bytes(
            serialization.Encoding.Raw, serialization.PublicFormat.Raw
        ) == pk
        public_key.verify(signature, message)
示例#16
0
def test_cryptography_okp_public_key_ed448():
  ed448_private_key = Ed448PrivateKey.generate()
  ed448_public_number = ed448_private_key.public_key().public_bytes(
      Encoding.Raw, PublicFormat.Raw)

  okp_key = OKPCredentialPublicKey(
      kty=COSEKeyType.Value.OKP,
      crv=OKPKeyType.Value.ED448,
      x=ed448_public_number,
  )

  converted_public_key = cryptography_okp_public_key(okp_key)
  converted_public_number = converted_public_key.public_bytes(
      Encoding.Raw, PublicFormat.Raw)

  assert ed448_public_number == converted_public_number
示例#17
0
    def test_invalid_public_bytes(self, backend):
        key = Ed448PrivateKey.generate().public_key()
        with pytest.raises(ValueError):
            key.public_bytes(
                serialization.Encoding.Raw,
                serialization.PublicFormat.SubjectPublicKeyInfo
            )

        with pytest.raises(ValueError):
            key.public_bytes(
                serialization.Encoding.PEM,
                serialization.PublicFormat.PKCS1
            )

        with pytest.raises(ValueError):
            key.public_bytes(
                serialization.Encoding.PEM,
                serialization.PublicFormat.Raw
            )
示例#18
0
    def test_invalid_private_bytes(self, backend):
        key = Ed448PrivateKey.generate()
        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.Raw,
                serialization.PrivateFormat.Raw,
                None,
            )

        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.Raw,
                serialization.PrivateFormat.PKCS8,
                None,
            )

        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.PEM,
                serialization.PrivateFormat.Raw,
                serialization.NoEncryption(),
            )
示例#19
0
    def test_invalid_private_bytes(self, backend):
        key = Ed448PrivateKey.generate()
        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.Raw,
                serialization.PrivateFormat.Raw,
                None
            )

        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.Raw,
                serialization.PrivateFormat.PKCS8,
                None
            )

        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.PEM,
                serialization.PrivateFormat.Raw,
                serialization.NoEncryption()
            )
示例#20
0
    def generate_key(crv: Union[Type['CoseCurve'], str, int],
                     optional_params: dict = None) -> 'OKPKey':
        """
        Generate a random OKPKey COSE key object.

        :param crv: Specify an elliptic curve.
        :param optional_params: Optional key attributes for the :class:`~cose.keys.okp.OKPKey` object, e.g., \
        :class:`~cose.keys.keyparam.KpAlg` or  :class:`~cose.keys.keyparam.KpKid`.

        :returns: A COSE `OKPKey` key.
        """

        if type(crv) == str or type(crv) == int:
            crv = CoseCurve.from_id(crv)

        if crv == X25519:
            private_key = X25519PrivateKey.generate()
        elif crv == Ed25519:
            private_key = Ed25519PrivateKey.generate()
        elif crv == Ed448:
            private_key = Ed448PrivateKey.generate()
        elif crv == X448:
            private_key = X448PrivateKey.generate()
        else:
            raise CoseIllegalCurve(
                f"Curve must be of type {X25519}, {X448}, {Ed25519}, or {Ed448}"
            )

        encoding = Encoding(serialization.Encoding.Raw)
        private_format = PrivateFormat(serialization.PrivateFormat.Raw)
        public_format = PublicFormat(serialization.PublicFormat.Raw)
        encryption = serialization.NoEncryption()

        return OKPKey(crv=crv,
                      x=private_key.public_key().public_bytes(
                          encoding, public_format),
                      d=private_key.private_bytes(encoding, private_format,
                                                  encryption),
                      optional_params=optional_params)
示例#21
0
 def test_invalid_length_from_private_bytes(self, backend):
     with pytest.raises(ValueError):
         Ed448PrivateKey.from_private_bytes(b"a" * 56)
     with pytest.raises(ValueError):
         Ed448PrivateKey.from_private_bytes(b"a" * 58)
示例#22
0
 def test_invalid_length_from_private_bytes(self, backend):
     with pytest.raises(ValueError):
         Ed448PrivateKey.from_private_bytes(b"a" * 56)
     with pytest.raises(ValueError):
         Ed448PrivateKey.from_private_bytes(b"a" * 58)
示例#23
0
 def test_invalid_type_private_bytes(self, backend):
     with pytest.raises(TypeError):
         Ed448PrivateKey.from_private_bytes(object())
示例#24
0
 def test_invalid_type_private_bytes(self, backend):
     with pytest.raises(TypeError):
         Ed448PrivateKey.from_private_bytes(object())
示例#25
0
 def test_generate(self, backend):
     key = Ed448PrivateKey.generate()
     assert key
     assert key.public_key()
示例#26
0
 def test_generate(self, backend):
     key = Ed448PrivateKey.generate()
     assert key
     assert key.public_key()
示例#27
0
文件: okp.py 项目: dajiaji/python-cwt
    def __init__(self, params: Dict[int, Any]):
        super().__init__(params)
        self._public_key: Any = None
        self._private_key: Any = None
        self._hash_alg: Any = None
        self._x = None
        self._d = None

        # Validate kty.
        if params[1] != 1:
            raise ValueError("kty(1) should be OKP(1).")

        # Validate crv.
        if -1 not in params:
            raise ValueError("crv(-1) not found.")
        self._crv = params[-1]
        if not isinstance(self._crv, int):
            raise ValueError("crv(-1) should be int.")
        if self._crv not in [4, 5, 6, 7]:
            raise ValueError(
                f"Unsupported or unknown crv(-1) for OKP: {self._crv}.")
        if self._crv in [4, 5]:
            if not self._alg:
                raise ValueError("X25519/X448 needs alg explicitly.")
            if self._alg in [-25, -27]:
                self._hash_alg = hashes.SHA256
            elif self._alg in [-26, -28]:
                self._hash_alg = hashes.SHA512
            else:
                raise ValueError(
                    f"Unsupported or unknown alg used with X25519/X448: {self._alg}."
                )

        # Validate alg and key_ops.
        if self._key_ops:
            if set(self._key_ops) & set([3, 4, 5, 6, 9, 10]):
                raise ValueError(
                    "Unknown or not permissible key_ops(4) for OKP.")
        else:
            if self._crv in [4, 5]:
                self._key_ops = [7, 8] if -4 in params else []
            else:  # self._crv in [6, 7]
                self._key_ops = [1, 2] if -4 in params else [2]
        if self._alg:
            if self._alg in COSE_ALGORITHMS_SIG_OKP.values():
                if -4 in params:
                    # private key for signing.
                    if not (set(self._key_ops) & set([1, 2])):
                        raise ValueError("Invalid key_ops for signing key.")
                    if set(self._key_ops) & set([7, 8]):
                        raise ValueError(
                            "Signing key should not be used for key derivation."
                        )
                else:
                    # public key for signing.
                    if 2 not in self._key_ops or len(self._key_ops) != 1:
                        raise ValueError("Invalid key_ops for public key.")
            elif self._alg in COSE_ALGORITHMS_CKDM_KEY_AGREEMENT.values():
                if -4 in params:
                    # private key for key derivation.
                    if not (set(self._key_ops) & set([7, 8])):
                        raise ValueError("Invalid key_ops for key derivation.")
                    if set(self._key_ops) & set([1, 2]):
                        raise ValueError(
                            "Private key for ECDHE should not be used for signing."
                        )
                else:
                    # public key for key derivation.
                    if self._key_ops:
                        raise ValueError(
                            "Public key for ECDHE should not have key_ops.")
            else:
                raise ValueError(
                    f"Unsupported or unknown alg(3) for OKP: {self._alg}.")
        else:
            if -4 in params:
                # private key.
                if set(self._key_ops) & set([1, 2]):
                    # private key for signing.
                    if set(self._key_ops) & set([7, 8]):
                        raise ValueError(
                            "OKP private key should not be used for both signing and key derivation."
                        )
                    self._alg = -8  # EdDSA
            else:
                # public key.
                if 2 in self._key_ops:
                    if len(self._key_ops) > 1:
                        raise ValueError("Invalid key_ops for public key.")
                else:
                    raise ValueError("Invalid key_ops for public key.")

        if self._alg in COSE_ALGORITHMS_CKDM_KEY_AGREEMENT_ES.values():
            if -2 not in params:
                return

        # Validate x.
        if -2 not in params:
            raise ValueError("x(-2) not found.")
        if not isinstance(params[-2], bytes):
            raise ValueError("x(-2) should be bytes(bstr).")
        self._x = params[-2]
        try:
            if -4 not in params:
                if self._crv == 4:  # X25519
                    self._public_key = X25519PublicKey.from_public_bytes(
                        self._x)
                elif self._crv == 5:  # X448
                    self._public_key = X448PublicKey.from_public_bytes(self._x)
                elif self._crv == 6:  # Ed25519
                    self._public_key = Ed25519PublicKey.from_public_bytes(
                        self._x)
                else:  # self._crv == 7 (Ed448)
                    self._public_key = Ed448PublicKey.from_public_bytes(
                        self._x)
                self._key = self._public_key
                return
        except ValueError as err:
            raise ValueError("Invalid key parameter.") from err

        if not isinstance(params[-4], bytes):
            raise ValueError("d(-4) should be bytes(bstr).")

        try:
            self._d = params[-4]
            if self._crv == 4:  # X25519
                self._private_key = X25519PrivateKey.from_private_bytes(
                    self._d)
            elif self._crv == 5:  # X448
                self._private_key = X448PrivateKey.from_private_bytes(self._d)
            elif self._crv == 6:  # Ed25519
                self._private_key = Ed25519PrivateKey.from_private_bytes(
                    self._d)
            else:  # self._crv == 7 (Ed448)
                self._private_key = Ed448PrivateKey.from_private_bytes(self._d)
            self._key = self._private_key
        except ValueError as err:
            raise ValueError("Invalid key parameter.") from err
        return
示例#28
0
def test_attest_android_key():
    client_data_hash = b'client-data-hash'
    auth_data = b'auth-data'

    certificate, private_key, public_key = generate_elliptic_curve_x509_certificate_android(
        SECP256R1(), client_data_hash)
    public_numbers = private_key.private_numbers().public_numbers

    x = public_numbers.x.to_bytes(P_256_COORDINATE_BYTE_LENGTH, 'big')
    y = public_numbers.y.to_bytes(P_256_COORDINATE_BYTE_LENGTH, 'big')
    public_key_android = b'\x04' + x + y
    verification_data = auth_data + client_data_hash

    credential_public_key = EC2CredentialPublicKey(
        x=x,
        y=y,
        kty=COSEKeyType.Name.EC2,
        crv=EC2Curve.Name.P_256,
    )

    attested_credential_data = AttestedCredentialData(
        aaguid=TEST_AAGUID,
        credential_id_length=TEST_CREDENTIAL_ID_LENGTH,
        credential_id=TEST_CREDENTIAL_ID,
        credential_public_key=credential_public_key,
    )

    signature = generate_signature(private_key, verification_data)

    invalid_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256, sig=b'', x5c=[])

    att_obj = AttestationObject(
        auth_data=AuthenticatorData(
            rp_id_hash=TEST_RP_ID_HASH,
            flags=0,
            sign_count=0,
            attested_credential_data=attested_credential_data,
            extensions=None),
        fmt=AttestationStatementFormatIdentifier.FIDO_U2F,
        att_stmt=invalid_att_stmt)

    with pytest.raises(AttestationError):
        attest(invalid_att_stmt, att_obj, auth_data, client_data_hash)

    der_certificate = certificate.public_bytes(Encoding.DER)
    valid_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=signature,
        x5c=[der_certificate])

    att_obj.att_stmt = valid_att_stmt
    assert attest(valid_att_stmt, att_obj, auth_data,
                  client_data_hash) == (AttestationType.BASIC, [certificate])

    unverified_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=b'bad-signature',
        x5c=[der_certificate])
    att_obj.att_stmt = unverified_att_stmt
    with pytest.raises(AttestationError):
        attest(unverified_att_stmt, att_obj, auth_data, client_data_hash)

    invalid_pk = rsa.generate_private_key(65537, 4096, default_backend())
    invalid_pubk = invalid_pk.public_key()
    invalid_certificate = generate_x509_certificate(invalid_pubk, invalid_pk,
                                                    hashes.SHA256())

    invalid_signature = invalid_pk.sign(verification_data, PKCS1v15(),
                                        hashes.SHA256())
    invalid_der_certificate = invalid_certificate.public_bytes(Encoding.DER)

    invalid_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=invalid_signature,
        x5c=[invalid_der_certificate])
    att_obj.att_stmt = invalid_att_stmt
    with pytest.raises(AttestationError):
        attest(invalid_att_stmt, att_obj, auth_data, client_data_hash)

    att_obj.att_stmt = valid_att_stmt

    while True:
        random_pk = generate_private_key(SECP256R1(), default_backend())
        random_public_numbers = random_pk.private_numbers().public_numbers
        rx = random_public_numbers.x.to_bytes(P_256_COORDINATE_BYTE_LENGTH,
                                              'big')
        ry = random_public_numbers.y.to_bytes(P_256_COORDINATE_BYTE_LENGTH,
                                              'big')

        if rx != x or ry != y:
            break

    att_obj.auth_data.attested_credential_data.credential_public_key = (
        EC2CredentialPublicKey(
            x=rx,
            y=ry,
            kty=COSEKeyType.Name.EC2,
            crv=EC2Curve.Name.P_256,
        ))

    with pytest.raises(AttestationError):
        attest(valid_att_stmt, att_obj, auth_data, client_data_hash)

    invalid_certificate, invalid_pk, invalid_pubk = generate_elliptic_curve_x509_certificate(
        SECP256R1())
    invalid_public_numbers = invalid_pk.private_numbers().public_numbers

    x = invalid_public_numbers.x.to_bytes(P_256_COORDINATE_BYTE_LENGTH, 'big')
    y = invalid_public_numbers.y.to_bytes(P_256_COORDINATE_BYTE_LENGTH, 'big')

    att_obj.auth_data.attested_credential_data.credential_public_key = (
        EC2CredentialPublicKey(
            x=x,
            y=y,
            kty=COSEKeyType.Name.EC2,
            crv=EC2Curve.Name.P_256,
        ))

    invalid_signature = generate_signature(invalid_pk, verification_data)
    invalid_der_certificate = invalid_certificate.public_bytes(Encoding.DER)
    invalid_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=invalid_signature,
        x5c=[invalid_der_certificate])

    with pytest.raises(AttestationError):
        attest(invalid_att_stmt, att_obj, auth_data, client_data_hash)

    invalid_certificate, invalid_pk, invalid_pubk = generate_elliptic_curve_x509_certificate_android_raw(
        SECP256R1(), b'invalid')
    invalid_public_numbers = invalid_pk.private_numbers().public_numbers

    x = invalid_public_numbers.x.to_bytes(P_256_COORDINATE_BYTE_LENGTH, 'big')
    y = invalid_public_numbers.y.to_bytes(P_256_COORDINATE_BYTE_LENGTH, 'big')

    att_obj.auth_data.attested_credential_data.credential_public_key = (
        EC2CredentialPublicKey(
            x=x,
            y=y,
            kty=COSEKeyType.Name.EC2,
            crv=EC2Curve.Name.P_256,
        ))

    invalid_signature = generate_signature(invalid_pk, verification_data)
    invalid_der_certificate = invalid_certificate.public_bytes(Encoding.DER)
    invalid_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=invalid_signature,
        x5c=[invalid_der_certificate])

    with pytest.raises(AttestationError):
        attest(invalid_att_stmt, att_obj, auth_data, client_data_hash)

    okp_pk = Ed25519PrivateKey.generate()
    okp_pubk = okp_pk.public_key()

    okp_certificate = generate_x509_certificate(
        okp_pubk, okp_pk, None, generate_android_extensions(client_data_hash))

    x = okp_pubk.public_bytes(Encoding.Raw, PublicFormat.Raw)

    att_obj.auth_data.attested_credential_data.credential_public_key = (
        OKPCredentialPublicKey(
            x=x,
            kty=COSEKeyType.Name.OKP,
            crv=OKPCurve.Name.ED25519,
        ))

    okp_signature = okp_pk.sign(verification_data)
    okp_der_certificate = okp_certificate.public_bytes(Encoding.DER)
    okp_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=okp_signature,
        x5c=[okp_der_certificate])

    assert attest(okp_att_stmt, att_obj, auth_data,
                  client_data_hash) == (AttestationType.BASIC,
                                        [okp_certificate])

    okp_pk = Ed448PrivateKey.generate()
    okp_pubk = okp_pk.public_key()

    okp_certificate = generate_x509_certificate(
        okp_pubk, okp_pk, None, generate_android_extensions(client_data_hash))

    x = okp_pubk.public_bytes(Encoding.Raw, PublicFormat.Raw)

    att_obj.auth_data.attested_credential_data.credential_public_key = (
        OKPCredentialPublicKey(
            x=x,
            kty=COSEKeyType.Name.OKP,
            crv=OKPCurve.Name.ED448,
        ))

    okp_signature = okp_pk.sign(verification_data)
    okp_der_certificate = okp_certificate.public_bytes(Encoding.DER)
    okp_att_stmt = AndroidKeyAttestationStatement(
        alg=COSEAlgorithmIdentifier.Name.ES256,
        sig=okp_signature,
        x5c=[okp_der_certificate])

    assert attest(okp_att_stmt, att_obj, auth_data,
                  client_data_hash) == (AttestationType.BASIC,
                                        [okp_certificate])
示例#29
0
def data():
    mensaje= b"89392679556575597635196565386081702718512260749406173579320076828061414488077821523722981888265393212848183094"

    #X25519 bench
    start_time= time()
    private_key = X25519PrivateKey.generate()
    peer_public_key = X25519PrivateKey.generate().public_key()
    k255=time()-start_time
    #print("Generación llave X25519 en: " + str(k255) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")
    private_key=0

    #25519 sign
    start_time= time()
    private_key = Ed25519PrivateKey.generate()
    signature = private_key.sign(mensaje)
    s255=time()-start_time
    #print("Generación firma X25519 en: " + str(s255) + " sec")

    start_time= time()
    public_key = private_key.public_key()
    public_key.verify(signature, mensaje)
    ver255=time()-start_time
    #print("Verificación firma X25519 en: " + str(ver255) + " sec")
    private_key=0
    #448 Key Exchange
    start_time=time()
    private_key = X448PrivateKey.generate()
    peer_public_key = X448PrivateKey.generate().public_key()
    k448=time()-start_time
    #print("Generación 448 llave en: " + str(k448) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")
    private_key=0
    #448 sign

    private_key = Ed448PrivateKey.generate()
    start_time= time()
    signature = private_key.sign(mensaje)
    s448=time()-start_time
    #print("Generación 448 firma en: " + str(s448) + " sec")
    start_time=time()
    public_key = private_key.public_key()
    public_key.verify(signature, mensaje)
    ver448=time()-start_time
    #print("Verificación 448 firma en: " + str(ver448) + " sec")
    private_key=0

    #RSA GENERATION
    start_time=time()
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )
    krsa=time()-start_time
    #print("Generación RSA llave en: " + str(krsa) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")

    #RSA SINGING
    start_time=time()
    signature = private_key.sign(
        mensaje,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    srsa=time()-start_time
    #print("Generación RSA firma en: " + str(srsa) + " sec")
    private_key=0
    #DSA SINGING
    start_time=time()
    private_key = dsa.generate_private_key(
        key_size=1024,
    )
    kdsa=time()-start_time
    #print("Generación DSA llave en: " + str(kdsa) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")
    start_time =time()
    signature = private_key.sign(
        mensaje,
        hashes.SHA256()
    )
    sdsa=time()-start_time
    #print("Generación DSA firma en: " + str(sdsa) + " sec")


    return [k255,s255,ver255,k448,s448,ver448,krsa,srsa,kdsa,sdsa]
示例#30
0
 def test_round_trip_private_serialization(self, encoding, fmt, encryption,
                                           passwd, load_func, backend):
     key = Ed448PrivateKey.generate()
     serialized = key.private_bytes(encoding, fmt, encryption)
     loaded_key = load_func(serialized, passwd, backend)
     assert isinstance(loaded_key, Ed448PrivateKey)