示例#1
0
 def set_passwd(self, sign, xchg, password: bytes):
     """
     Set or replace the password by encrypting the private keys and storing
     the results.
     :param sign: The signature key.
     :param xchg: The encryption key.
     :param password: The password for encrypting the keys.
     """
     # Verify key if key has been set
     if self.sign_priv:
         try:
             Ed25519PublicKey.from_public_bytes(self.sign).verify(
                 self.sign_sig, sign)
             Ed25519PublicKey.from_public_bytes(self.sign).verify(
                 self.xchg_sig, xchg)
         except cryptography.exceptions.InvalidSignature as e:
             raise SignatureMismatch(self.xchg_sig) from e
     # Do the actual encryption
     session = _gen_login_key(password, self.identity)
     self.sign_iv = urandom(16)
     context = Cipher(algorithms.ChaCha20(session, self.sign_iv), None,
                      default_backend()).encryptor()
     self.sign_priv = context.update(sign) + context.finalize()
     self.xchg_iv = urandom(16)
     context = Cipher(algorithms.ChaCha20(session, self.xchg_iv), None,
                      default_backend()).encryptor(
                      )  # Nonce reuse is considered bad practice
     self.xchg_priv = context.update(xchg) + context.finalize()
示例#2
0
  def validate(self, descriptor):
    """
    Validate our descriptor content matches its ed25519 signature. Supported
    descriptor types include...

      * :class:`~stem.descriptor.server_descriptor.RelayDescriptor`
      * :class:`~stem.descriptor.hidden_service.HiddenServiceDescriptorV3`

    :param stem.descriptor.__init__.Descriptor descriptor: descriptor to validate

    :raises:
      * **ValueError** if signing key or descriptor are invalid
      * **TypeError** if descriptor type is unsupported
      * **ImportError** if cryptography module with ed25519 support is unavailable
    """

    import stem.descriptor.server_descriptor

    try:
      from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
      from cryptography.exceptions import InvalidSignature
    except ImportError:
      raise ImportError('Certificate validation requires cryptography 2.6 or later')

    if isinstance(descriptor, stem.descriptor.server_descriptor.RelayDescriptor):
      signed_content = hashlib.sha256(Ed25519CertificateV1._signed_content(descriptor)).digest()
      signature = stem.util.str_tools._decode_b64(descriptor.ed25519_signature)

      # verify that we're created from this descriptor's signing key

      if descriptor.ed25519_master_key:
        signing_key = base64.b64decode(stem.util.str_tools._to_bytes(descriptor.ed25519_master_key) + b'=')
      else:
        signing_key = self.signing_key()

      if not signing_key:
        raise ValueError('Server descriptor missing an ed25519 signing key')

      try:
        key = Ed25519PublicKey.from_public_bytes(signing_key)
        key.verify(self.signature, base64.b64decode(stem.util.str_tools._to_bytes(self.to_base64()))[:-ED25519_SIGNATURE_LENGTH])
      except InvalidSignature:
        raise ValueError('Ed25519KeyCertificate signing key is invalid (signature forged or corrupt)')
    elif isinstance(descriptor, stem.descriptor.hidden_service.HiddenServiceDescriptorV3):
      signed_content = Ed25519CertificateV1._signed_content(descriptor)
      signature = stem.util.str_tools._decode_b64(descriptor.signature)
    else:
      raise TypeError('Certificate validation only supported for server and hidden service descriptors, not %s' % type(descriptor).__name__)

    try:
      key = Ed25519PublicKey.from_public_bytes(self.key)
      key.verify(signature, signed_content)
    except InvalidSignature:
      raise ValueError('Descriptor Ed25519 certificate signature invalid (signature forged or corrupt)')
示例#3
0
def test_ed25519_unsupported(backend):
    with raises_unsupported_algorithm(
            _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
        Ed25519PublicKey.from_public_bytes(b"0" * 32)

    with raises_unsupported_algorithm(
            _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
        Ed25519PrivateKey.from_private_bytes(b"0" * 32)

    with raises_unsupported_algorithm(
            _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
        Ed25519PrivateKey.generate()
示例#4
0
def test_ed25519_unsupported(backend):
    with raises_unsupported_algorithm(
        _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
    ):
        Ed25519PublicKey.from_public_bytes(b"0" * 32)

    with raises_unsupported_algorithm(
        _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
    ):
        Ed25519PrivateKey.from_private_bytes(b"0" * 32)

    with raises_unsupported_algorithm(
        _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
    ):
        Ed25519PrivateKey.generate()
示例#5
0
    def _validate_server_desc_signing_key(self, descriptor):
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        from cryptography.exceptions import InvalidSignature

        if descriptor.ed25519_master_key:
            signing_key = base64.b64decode(
                stem.util.str_tools._to_bytes(descriptor.ed25519_master_key) +
                b'=')
        else:
            signing_key = self.signing_key()

        if not signing_key:
            raise ValueError(
                'Server descriptor missing an ed25519 signing key')

        try:
            key = Ed25519PublicKey.from_public_bytes(signing_key)
            key.verify(
                self.signature,
                base64.b64decode(stem.util.str_tools._to_bytes(
                    self.encoded))[:-ED25519_SIGNATURE_LENGTH])
        except InvalidSignature:
            raise ValueError(
                'Ed25519KeyCertificate signing key is invalid (signature forged or corrupt)'
            )
示例#6
0
def cryptography_okp_public_key(
        credential_public_key: OKPCredentialPublicKey) -> OKPPublicKey:
    """Convert an `OKPCredentialPublicKey` into a cryptography `OKPPublicKey`.

    Args:
      credential_public_key (EC2CredentialPublicKey): The key to convert.

    Returns:
      A cryptography `EC2PublicKey`.

    Raises:
      UnimplementedError: If the conversion logic for the given type of
        CredentialPublicKey has not been implemented.
      PublicKeyConversionError: If the provided key could not be converted
        into a valid cryptography `EC2PublicKey`.
    """
    try:
        if credential_public_key.crv.name == 'ED25519':
            return Ed25519PublicKey.from_public_bytes(credential_public_key.x)
        elif credential_public_key.crv.name == 'ED448':
            return Ed448PublicKey.from_public_bytes(credential_public_key.x)
        else:
            raise UnimplementedError(
                'Unsupported cryptography OKP curve {}'.format(
                    credential_public_key.crv.name))
    except ValueError:
        raise PublicKeyConversionError('Invalid OKP public key')
示例#7
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":
                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:
                    return Ed25519PublicKey.from_public_bytes(x)
                d = base64url_decode(obj.get("d"))
                return Ed25519PrivateKey.from_private_bytes(d)
            except ValueError as err:
                raise InvalidKeyError("Invalid key parameter") from err
示例#8
0
 def test_load_public_bytes(self, backend):
     public_key = Ed25519PrivateKey.generate().public_key()
     public_bytes = public_key.public_bytes(serialization.Encoding.Raw,
                                            serialization.PublicFormat.Raw)
     public_key2 = Ed25519PublicKey.from_public_bytes(public_bytes)
     assert public_bytes == public_key2.public_bytes(
         serialization.Encoding.Raw, serialization.PublicFormat.Raw)
示例#9
0
    def verify(self,
               to_be_verified: bytes,
               signature: bytes,
               alg: Optional[CoseAlgorithms] = None,
               curve: Optional[CoseEllipticCurves] = None) -> bool:
        """
        Verifies the digital signature over 'to_be_verified'. The parameter 'alg' and 'curve' parameters are optional in
        case they are already provided by the key object self.

        :param to_be_verified: Data that was signed.
        :param signature: Signature to verify.
        :param alg: An optional algorithm parameter.
        :param curve: An optional curve
        :return: True when the signature is valid and False if the signature is invalid.
        """

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

        if self.crv == CoseEllipticCurves.ED25519:
            vk = Ed25519PublicKey.from_public_bytes(self.x)
        elif self._crv == CoseEllipticCurves.ED448:
            vk = Ed448PublicKey.from_public_bytes(self.x)
        else:
            raise CoseIllegalCurve(
                f"Illegal curve for OKP singing: {self.crv}")

        try:
            vk.verify(signature, to_be_verified)
            return True
        except InvalidSignature:
            return False
def test_new_auth_key_from_public_key():
    key_bytes = bytes.fromhex("447fc3be296803c2303951c7816624c7566730a5cc6860a4a1bd3c04731569f5")
    public_key = Ed25519PublicKey.from_public_bytes(key_bytes)
    auth_key = AuthKey.from_public_key(public_key)
    assert auth_key.hex() == "459c77a38803bd53f3adee52703810e3a74fd7c46952c497e75afb0a7932586d"
    assert auth_key.prefix().hex() == "459c77a38803bd53f3adee52703810e3"
    assert auth_key.account_address().to_hex() == "a74fd7c46952c497e75afb0a7932586d"
示例#11
0
def test_decode_example_jws():
    example = "eyJhbGciOiJFZERTQSJ9.U2FtcGxlIHNpZ25lZCBwYXlsb2FkLg.dZvbycl2Jkl3H7NmQzL6P0_lDEW42s9FrZ8z-hXkLqYyxNq8yOlDjlP9wh3wyop5MU2sIOYvay-laBmpdW6OBQ"
    public_key = "bd47e3e7afb94debbd82e10ab7d410a885b589db49138628562ac2ec85726129"
    key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(public_key))

    headers, body = jws.decode(example.encode("utf-8"), key.verify)
    assert body == "Sample signed payload."
    assert headers == {"alg": "EdDSA"}
def checkSignature(message, signature, public_key_bytes):
    public_key = Ed25519PublicKey.from_public_bytes(public_key_bytes)
    try:
        public_key.verify(signature, message)
    except InvalidSignature:
        return False
    finally:
        return True
示例#13
0
def test_deserialize_example_jws():
    example = "eyJhbGciOiJFZERTQSJ9.U2FtcGxlIHNpZ25lZCBwYXlsb2FkLg.dZvbycl2Jkl3H7NmQzL6P0_lDEW42s9FrZ8z-hXkLqYyxNq8yOlDjlP9wh3wyop5MU2sIOYvay-laBmpdW6OBQ"
    public_key = "bd47e3e7afb94debbd82e10ab7d410a885b589db49138628562ac2ec85726129"

    body, sig, msg = offchain.jws.deserialize_string(example.encode("utf-8"))
    assert body == "Sample signed payload."

    key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(public_key))
    key.verify(sig, msg)
示例#14
0
 def test_load_public_bytes(self, backend):
     public_key = Ed25519PrivateKey.generate().public_key()
     public_bytes = public_key.public_bytes(
         serialization.Encoding.Raw, serialization.PublicFormat.Raw
     )
     public_key2 = Ed25519PublicKey.from_public_bytes(public_bytes)
     assert public_bytes == public_key2.public_bytes(
         serialization.Encoding.Raw, serialization.PublicFormat.Raw
     )
示例#15
0
def valid_signature_raw(sig, pub, text):
    public_key = Ed25519PublicKey.from_public_bytes(
        bytearray.fromhex(pub).decode())
    try:
        public_key.verify(bytearray.fromhex(
            sig).decode(), text.encode('utf-8'))
        return True
    except:
        return False
 def loadKey(self, data):
     self.private_key = Ed25519PrivateKey.from_private_bytes(
         bytes.fromhex(data['private_key']))
     self.public_key_bytes = bytes.fromhex(data['public_key'])
     self.public_key = Ed25519PublicKey.from_public_bytes(
         self.public_key_bytes)
     self.nid = bytes.fromhex(data['myNID'])
     self.rsa_private_key = rsa.generate_private_key(public_exponent=65537,
                                                     key_size=2048)
示例#17
0
def cryptography_okp_public_key(
        credential_public_key: OKPCredentialPublicKey) -> PublicKey:
    if credential_public_key.crv.name == 'ED25519':
        return Ed25519PublicKey.from_public_bytes(credential_public_key.x)
    elif credential_public_key.crv.name == 'ED448':
        return Ed448PublicKey.from_public_bytes(credential_public_key.x)
    else:
        raise UnimplementedError(
            'Unsupported cryptography OKP curve {}'.format(
                credential_public_key.crv.name))
示例#18
0
    def load_peer(self, peer_pub_bytes, peer_sig_pub_bytes):
        self.peer_pub_bytes = peer_pub_bytes
        self.peer_pub = X25519PublicKey.from_public_bytes(self.peer_pub_bytes)

        self.peer_sig_pub_bytes = peer_sig_pub_bytes
        self.peer_sig_pub = Ed25519PublicKey.from_public_bytes(
            self.peer_sig_pub_bytes)

        if not hasattr(self.peer_pub, "curve"):
            self.peer_pub.curve = Link.CURVE
示例#19
0
def verifying_key_from_string(public_key_bytes):
    """
    Load a verifying key from a string of bytes (which includes the
    PUBLIC_KEY_PREFIX)

    :returns: a public_key
    """
    if not isinstance(public_key_bytes, six.binary_type):
        raise ValueError('public_key_bytes must be bytes')

    return Ed25519PublicKey.from_public_bytes(
        a2b(remove_prefix(public_key_bytes, PUBLIC_KEY_PREFIX)))
示例#20
0
 def valid_sig(self):
     if (self.sender == 'coinbase'):
         return True
     else:
         # all nicknames end with .coof, if the sender ends with .coof then we need to get the pubkey from the db
         if (self.sender.endswith('.coof')):
             read = get(key=self.sender, collection_name='nicknames.db')
             if (read == None):
                 return False
             else:
                 public_key = Ed25519PublicKey.from_public_bytes(
                     bytearray.fromhex(read).decode())
         else:
             public_key = Ed25519PublicKey.from_public_bytes(
                 bytearray.fromhex(self.sender).decode())
         try:
             public_key.verify(bytearray.fromhex(
                 self.signature).decode(), self.hash.encode('utf-8'))
             return True
         except:
             return False
示例#21
0
def loadKey(data):
    private_bytes = data['private']
    private_key = Ed25519PrivateKey.from_private_bytes(
        bytes.fromhex(data['private']))
    public_bytes = data['public']
    public_key = Ed25519PublicKey.from_public_bytes(
        bytes.fromhex(data['public']))
    nid = data['nid']
    print('私钥', private_bytes)
    print('公钥', public_bytes)
    print('nid ', nid)
    return private_key, public_key, nid
示例#22
0
    def verify(cls, key: 'OKP', data: bytes, signature: bytes) -> bool:
        if key.crv.fullname == 'ED25519':
            vk = Ed25519PublicKey.from_public_bytes(key.x)
        elif key.crv.fullname == 'ED448':
            vk = Ed448PublicKey.from_public_bytes(key.x)
        else:
            raise CoseException(f"Illegal curve for OKP singing: {key.crv}")

        try:
            vk.verify(signature, data)
            return True
        except InvalidSignature:
            return False
示例#23
0
def ed25519_public_key_from_string(string):
    """Create an ed25519 public key from ``string``, which is a seed.

    Args:
        string (str): the string to use as a seed.

    Returns:
        Ed25519PublicKey: the public key

    """
    try:
        return Ed25519PublicKey.from_public_bytes(base64.b64decode(string))
    except (UnsupportedAlgorithm, Base64Error) as exc:
        raise ScriptWorkerEd25519Error("Can't create Ed25519PublicKey: {}!".format(str(exc)))
def decoded_public_key_to_cryptography(
    public_key: Union[DecodedOKPPublicKey, DecodedEC2PublicKey,
                      DecodedRSAPublicKey]
) -> Union[Ed25519PublicKey, EllipticCurvePublicKey, RSAPublicKey]:
    """Convert raw decoded public key parameters (crv, x, y, n, e, etc...) into
    public keys using primitives from the cryptography.io library
    """
    if isinstance(public_key, DecodedEC2PublicKey):
        """
        alg is -7 (ES256), where kty is 2 (with uncompressed points) and
        crv is 1 (P-256).
        https://www.w3.org/TR/webauthn-2/#sctn-public-key-easy
        """
        x = int(codecs.encode(public_key.x, "hex"), 16)
        y = int(codecs.encode(public_key.y, "hex"), 16)
        curve = get_ec2_curve(public_key.crv)

        ecc_pub_key = EllipticCurvePublicNumbers(x, y, curve).public_key(
            default_backend())

        return ecc_pub_key
    elif isinstance(public_key, DecodedRSAPublicKey):
        """
        alg is -257 (RS256)
        https://www.w3.org/TR/webauthn-2/#sctn-public-key-easy
        """
        e = int(codecs.encode(public_key.e, "hex"), 16)
        n = int(codecs.encode(public_key.n, "hex"), 16)

        rsa_pub_key = RSAPublicNumbers(e, n).public_key(default_backend())

        return rsa_pub_key
    elif isinstance(public_key, DecodedOKPPublicKey):
        """
        -8 (EdDSA), where crv is 6 (Ed25519).
        https://www.w3.org/TR/webauthn-2/#sctn-public-key-easy
        """
        if (public_key.alg != COSEAlgorithmIdentifier.EDDSA
                or public_key.crv != COSECRV.ED25519):
            raise UnsupportedPublicKey(
                f"OKP public key with alg {public_key.alg} and crv {public_key.crv} is not supported"
            )

        okp_pub_key = Ed25519PublicKey.from_public_bytes(public_key.x)

        return okp_pub_key
    else:
        raise UnsupportedPublicKey(
            f"Unrecognized decoded public key: {public_key}")
示例#25
0
    def validate(self, descriptor):
        """
    Validate our descriptor content matches its ed25519 signature. Supported
    descriptor types include...

      * :class:`~stem.descriptor.server_descriptor.RelayDescriptor`
      * :class:`~stem.descriptor.hidden_service.HiddenServiceDescriptorV3`

    :param stem.descriptor.__init__.Descriptor descriptor: descriptor to validate

    :raises:
      * **ValueError** if signing key or descriptor are invalid
      * **TypeError** if descriptor type is unsupported
      * **ImportError** if cryptography module or ed25519 support unavailable
    """

        if not stem.prereq.is_crypto_available(ed25519=True):
            raise ImportError(
                'Certificate validation requires the cryptography module and ed25519 support'
            )

        if isinstance(descriptor,
                      stem.descriptor.server_descriptor.RelayDescriptor):
            signed_content = hashlib.sha256(
                Ed25519CertificateV1._signed_content(descriptor)).digest()
            signature = stem.util.str_tools._decode_b64(
                descriptor.ed25519_signature)

            self._validate_server_desc_signing_key(descriptor)
        elif isinstance(
                descriptor,
                stem.descriptor.hidden_service.HiddenServiceDescriptorV3):
            signed_content = Ed25519CertificateV1._signed_content(descriptor)
            signature = stem.util.str_tools._decode_b64(descriptor.signature)
        else:
            raise TypeError(
                'Certificate validation only supported for server and hidden service descriptors, not %s'
                % type(descriptor).__name__)

        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        from cryptography.exceptions import InvalidSignature

        try:
            key = Ed25519PublicKey.from_public_bytes(self.key)
            key.verify(signature, signed_content)
        except InvalidSignature:
            raise ValueError(
                'Descriptor Ed25519 certificate signature invalid (signature forged or corrupt)'
            )
示例#26
0
def ed25519_public_key_from_string(string):
    """Create an ed25519 public key from ``string``, which is a seed.

    Args:
        string (str): the string to use as a seed.

    Returns:
        Ed25519PublicKey: the public key

    """
    try:
        return Ed25519PublicKey.from_public_bytes(
            base64.b64decode(string)
        )
    except (UnsupportedAlgorithm, Base64Error) as exc:
        raise ScriptWorkerEd25519Error("Can't create Ed25519PublicKey: {}!".format(str(exc)))
示例#27
0
 def verify_tx(self, tx, timestamp=None):
     global Ed25519PublicKey
     logging.debug(tx)
     if tx in self.mempool:
         logging.debug("tx True already have")
         return "already"
     elif tx in self.valid_tx:
         logging.debug("tx already in valid_tx")
         if timestamp:  #ak vola turo funkciu verify_block
             return False  #aby v blockchaine nemohli byt dve tie iste tx
         return "already"
     tx_type = tx[:2]
     if not tx_type in ["00", "01", "02"]:
         logging.debug(f"invalid tx type: {tx_type}")
         return False
     if tx_type == "00":
         msg_size = 64 - 4
     elif tx_type == "01":
         msg_size = int(tx[34:38], 16) * 2
         msg_size += 32
     else:
         msg_size = int(tx[2:6], 16) * 2
     print(f"msg_size: {msg_size}")
     if msg_size > 2000:
         logging.debug("msg size je moc velka")
         return False
     sig = bytes.fromhex(tx[-128:])
     sender_pub_key = Ed25519PublicKey.from_public_bytes(
         bytes.fromhex(tx[-192:-128]))
     try:
         sender_pub_key.verify(sig, bytes.fromhex(tx[:-128]))
     except:
         logging.debug("tx sig False")
         return False
     tx_timestamp = int(tx[-264:-256], 16)
     if timestamp:
         timestamp = int(timestamp, 16)
         if not -1800 <= timestamp - tx_timestamp <= 1800:
             logging.debug("tx timestamp is old in block")
             return False
         #ked bude temp fork a dojdu dva bloky s tymi istymi tx tak ich budem ma t dva krat v db
     elif not -1800 <= int(time()) - tx_timestamp <= 1800:
         logging.debug("tx timestamp is old")
         return False
     logging.debug("tx True")
     return True
示例#28
0
    def get_base_url_and_compliance_key(
        self, account_address: typing.Union[diem_types.AccountAddress, str]
    ) -> typing.Tuple[str, Ed25519PublicKey]:
        """get base_url and compliance key

        ParentVASP or Designated Dealer account role has base_url and compliance key setup, which
        are used for offchain API communication.
        """
        account = self.must_get_account(account_address)

        if account.role.compliance_key and account.role.base_url:
            key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(account.role.compliance_key))
            return (account.role.base_url, key)
        if account.role.parent_vasp_address:
            return self.get_base_url_and_compliance_key(account.role.parent_vasp_address)

        raise ValueError(f"could not find base_url and compliance_key from account: {account}")
示例#29
0
文件: hap_srp.py 项目: NebzHB/pyatv
    def verify1(self, credentials, session_pub_key, encrypted):
        """First verification step."""
        self._shared = self._verify_private.exchange(
            X25519PublicKey.from_public_bytes(session_pub_key)
        )

        session_key = hkdf_expand(
            "Pair-Verify-Encrypt-Salt", "Pair-Verify-Encrypt-Info", self._shared
        )

        chacha = chacha20.Chacha20Cipher(session_key, session_key)
        decrypted_tlv = hap_tlv8.read_tlv(
            chacha.decrypt(encrypted, nounce="PV-Msg02".encode())
        )

        identifier = decrypted_tlv[TlvValue.Identifier]
        signature = decrypted_tlv[TlvValue.Signature]

        if identifier != credentials.atv_id:
            raise exceptions.AuthenticationError("incorrect device response")

        info = session_pub_key + bytes(identifier) + self._public_bytes
        ltpk = Ed25519PublicKey.from_public_bytes(bytes(credentials.ltpk))

        try:
            ltpk.verify(bytes(signature), bytes(info))
        except InvalidSignature as ex:
            raise exceptions.AuthenticationError("signature error") from ex

        device_info = self._public_bytes + credentials.client_id + session_pub_key

        device_signature = Ed25519PrivateKey.from_private_bytes(credentials.ltsk).sign(
            device_info
        )

        tlv = hap_tlv8.write_tlv(
            {
                TlvValue.Identifier: credentials.client_id,
                TlvValue.Signature: device_signature,
            }
        )

        return chacha.encrypt(tlv, nounce="PV-Msg03".encode())
示例#30
0
def test_ed25519_signature(backend, wycheproof):
    # We want to fail if/when wycheproof adds more edwards curve tests
    # so we can add them as well.
    assert wycheproof.testgroup["key"]["curve"] == "edwards25519"

    key = Ed25519PublicKey.from_public_bytes(
        binascii.unhexlify(wycheproof.testgroup["key"]["pk"]))

    if wycheproof.valid or wycheproof.acceptable:
        key.verify(
            binascii.unhexlify(wycheproof.testcase["sig"]),
            binascii.unhexlify(wycheproof.testcase["msg"]),
        )
    else:
        with pytest.raises(InvalidSignature):
            key.verify(
                binascii.unhexlify(wycheproof.testcase["sig"]),
                binascii.unhexlify(wycheproof.testcase["msg"]),
            )
示例#31
0
    def load_public_key(self, pub_bytes):
        """
        Load a public key into the instance.

        :param pub_bytes: The public key as *bytes*.
        :returns: True if the key was loaded, otherwise False.
        """
        try:
            self.pub_bytes = pub_bytes[:Identity.KEYSIZE // 8 // 2]
            self.sig_pub_bytes = pub_bytes[Identity.KEYSIZE // 8 // 2:]

            self.pub = X25519PublicKey.from_public_bytes(self.pub_bytes)
            self.sig_pub = Ed25519PublicKey.from_public_bytes(
                self.sig_pub_bytes)

            self.update_hashes()
        except Exception as e:
            RNS.log(
                "Error while loading public key, the contained exception was: "
                + str(e), RNS.LOG_ERROR)
示例#32
0
def test_ed25519_signature(backend, wycheproof):
    # We want to fail if/when wycheproof adds more edwards curve tests
    # so we can add them as well.
    assert wycheproof.testgroup["key"]["curve"] == "edwards25519"

    key = Ed25519PublicKey.from_public_bytes(
        binascii.unhexlify(wycheproof.testgroup["key"]["pk"])
    )

    if wycheproof.valid or wycheproof.acceptable:
        key.verify(
            binascii.unhexlify(wycheproof.testcase["sig"]),
            binascii.unhexlify(wycheproof.testcase["msg"]),
        )
    else:
        with pytest.raises(InvalidSignature):
            key.verify(
                binascii.unhexlify(wycheproof.testcase["sig"]),
                binascii.unhexlify(wycheproof.testcase["msg"]),
            )
示例#33
0
 def auth_key(self) -> AuthKey:
     return AuthKey.from_public_key(
         Ed25519PublicKey.from_public_bytes(self.public_key_bytes()))
示例#34
0
 def __init__(self, store_id: str, store_key: str):
     self.store_id = store_id
     self.store_key = store_key
     self.public_key: Ed25519PublicKey = Ed25519PublicKey.from_public_bytes(
         bytes(bytearray.fromhex(config.PUBLIC_KEY)))
def public_key_from_string(key_str):
    """Create an Ed25519PublicKey from a base64-encoded string."""
    return Ed25519PublicKey.from_public_bytes(
        base64.b64decode(key_str)
    )
示例#36
0
 def test_invalid_length_from_public_bytes(self, backend):
     with pytest.raises(ValueError):
         Ed25519PublicKey.from_public_bytes(b"a" * 31)
     with pytest.raises(ValueError):
         Ed25519PublicKey.from_public_bytes(b"a" * 33)
示例#37
0
 def test_invalid_type_public_bytes(self, backend):
     with pytest.raises(TypeError):
         Ed25519PublicKey.from_public_bytes(object())