def verify_signed_data(signature: bytes, data: bytes, public_key: ec.EllipticCurvePublicKey, algorithm: ec.ECDSA = None) -> bool: """ Verify the received data with the public key and the signature of the source :param public_key: public key from the other party :param signature: the signature that has been send along the data :param data: data that belongs to the signature :param algorithm: algorithm used by the other party :return: bool """ __assure_public_key(public_key) result = False # set the result to False if not bool(algorithm) and algorithm is None: # if algorithm is None algorithm = ec.ECDSA(hashes.SHA256()) try: # with suppress(InvalidSignature): public_key.verify(signature, data, algorithm) except InvalidSignature: pass # result = False else: result = True # no invalid signature, thus verified (True) finally: return result # -> False if signature is invalid, True if signature is valid
def _verify(self, key: ec.EllipticCurvePublicKey, msg: bytes, asn1sig: bytes) -> bool: try: key.verify(asn1sig, msg, ec.ECDSA(self.hash)) except cryptography.exceptions.InvalidSignature as error: logger.debug(error, exc_info=True) return False else: return True
def verify_signature(public_key: EllipticCurvePublicKey, signature: bytes, data: bytes) -> None: """Verfies the supplied signature. Args: public_key: ECDSA public key with which the verification is done. signature: The signature to verify. data: The message that was signed. Raises: InvalidSignature if signature is not valid. """ public_key.verify(signature, data, ec.ECDSA(hashes.SHA256()))
def jwk(key: EllipticCurvePublicKey) -> dict: return { 'kty': 'EC', 'crv': 'P-256', 'x': b64url(key.public_numbers().x.to_bytes(32, 'big')), 'y': b64url(key.public_numbers().y.to_bytes(32, 'big')), }
def encode_public(self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList) -> None: """Write ECDSA public key""" point = public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) f_pub.put_sshstr(self.ssh_curve_name) f_pub.put_sshstr(point)
def __fetch_cage_key(self, fetch): if self.team_ecdh_key is None: resp = fetch.get("cages/key") decoded_team_cage_key = base64.b64decode(resp["ecdhKey"]) self.team_ecdh_key = EllipticCurvePublicKey.from_encoded_point( ec.SECP256K1(), decoded_team_cage_key)
def calculate_secret(self, slot: SLOT, peer_public_key: ec.EllipticCurvePublicKey) -> bytes: key_type = KEY_TYPE.from_public_key(peer_public_key) if key_type.algorithm != ALGORITHM.EC: raise ValueError("Unsupported key type") data = peer_public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) return self._use_private_key(slot, key_type, data, True)
def get_public_key_bytes_compressed( public_key: ec.EllipticCurvePublicKey) -> bytes: """ Returns the bytes from a cryptography ec.EllipticCurvePublicKey in a compressed format :param public_key: Public key object :type public_key: ec.EllipticCurvePublicKey :rtype: bytes """ return public_key.public_bytes(Encoding.X962, PublicFormat.CompressedPoint)
def derive_ecdh(self, public_key: ec.EllipticCurvePublicKey) -> bytes: """Perform an ECDH key exchange as specified in SP 800-56A. :param public_key: The public key to use for the key exchange. :return: The resulting shared key. """ point = public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) msg = struct.pack("!H", self.id) + point return self.session.send_secure_cmd(COMMAND.DERIVE_ECDH, msg)
def generate_public_pem(public_key: ec.EllipticCurvePublicKey) -> bytes: """ Generates a Privacy Enhanced Mail (pem) from the public key This may be send to the other party :param public_key: ec.EllipticCurvePublicKey :return: Privacy Enhanced Mail message :rtype: bytes """ __assure_public_key(public_key) pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) return pem
def is_valid(self): if self.sender == 'System': return True if self.signature is None or len(self.signature) == 0: print('ERROR: No signature found in the transaction') return False # generate a pub key obj from the sender info pub_key_obj = EllipticCurvePublicKey.from_encoded_point( ec.SECP256K1(), bytes.fromhex(self.sender)) data = self.get_data_bytes() try: pub_key_obj.verify(self.signature, data, ec.ECDSA(hashes.SHA256())) except cryptography.exceptions.InvalidSignature as exp: print(exp) return False return True
def _generate_ecc_seed(key: ec.EllipticCurvePublicKey, hashAlg: int, label: bytes) -> Tuple[bytes, bytes]: halg = _get_digest(hashAlg) if halg is None: raise ValueError(f"unsupported digest algorithm {hashAlg}") ekey = ec.generate_private_key(key.curve, default_backend()) epubnum = ekey.public_key().public_numbers() plength = int(key.curve.key_size / 8) # FIXME ceiling here exbytes = epubnum.x.to_bytes(plength, "big") eybytes = epubnum.y.to_bytes(plength, "big") # workaround marshal of TPMS_ECC_POINT secret = (len(exbytes).to_bytes(length=2, byteorder="big") + exbytes + len(eybytes).to_bytes(length=2, byteorder="big") + eybytes) shared_key = ekey.exchange(ec.ECDH(), key) pubnum = key.public_numbers() xbytes = pubnum.x.to_bytes(plength, "big") seed = kdfe(hashAlg, shared_key, label, exbytes, xbytes, halg.digest_size * 8) return (seed, secret)
def compress_pubkey(public_key: EllipticCurvePublicKey): uncompressed = public_key.public_numbers().encode_point() key_size = public_key.curve.key_size return bytes([2 + (uncompressed[-1] & 1)]) + uncompressed[1:key_size // 8 + 1]
def get_dsa_verifier(pub_key: ecc.EllipticCurvePublicKey): return Verifier( lambda: pub_key.verify(signature, message, hash_algo))
def get_public_key_bytes_compressed( public_key: ec.EllipticCurvePublicKey) -> bytes: """Return the bytes of a pubkey in the compressed format.""" return public_key.public_bytes(Encoding.X962, PublicFormat.CompressedPoint)