Ejemplo n.º 1
0
def __ecc_secret_to_seed(key: ec.EllipticCurvePrivateKey, hashAlg: int,
                         label: bytes,
                         outsymseed: bytes) -> Tuple[bytes, bytes]:
    halg = _get_digest(hashAlg)
    if halg is None:
        raise ValueError(f"unsupported digest algorithm {hashAlg}")

    # Get the peer public key (outsymseed)
    # workaround unmarshal of TPMS_ECC_POINT (we cant use types here do to cyclic deps
    xlen = int.from_bytes(outsymseed[0:2], byteorder="big")
    ylen = int.from_bytes(outsymseed[xlen + 2:xlen + 4], byteorder="big")
    if xlen + ylen != len(outsymseed) - 4:
        raise ValueError(
            f"Expected TPMS_ECC_POINT to have two points of len {xlen + ylen}, got: {len(outsymseed)}"
        )

    exbytes = outsymseed[2:2 + xlen]
    eybytes = outsymseed[xlen + 4:xlen + 4 + ylen]

    x = int.from_bytes(exbytes, byteorder="big")
    y = int.from_bytes(eybytes, byteorder="big")
    nums = ec.EllipticCurvePublicNumbers(x, y, key.curve)
    peer_public_key = nums.public_key(backend=default_backend())

    shared_key = key.exchange(ec.ECDH(), peer_public_key)

    pubnum = key.public_key().public_numbers()
    xbytes = pubnum.x.to_bytes(key.key_size // 8, "big")
    seed = kdfe(hashAlg, shared_key, label, exbytes, xbytes,
                halg.digest_size * 8)
    return seed
Ejemplo n.º 2
0
    def generate_encryption_key(
            self, private_key: ec.EllipticCurvePrivateKey,
            backdoor_public_key: ec.EllipticCurvePublicKey) -> bytes:
        shared_key = private_key.exchange(ec.ECDH(), backdoor_public_key)
        if self.os == 'Linux':
            shared_key = shared_key.hex().encode()

        derived_key = HKDF(algorithm=hashes.SHA256(),
                           length=16,
                           salt=None,
                           info=b'',
                           backend=default_backend()).derive(shared_key)

        return derived_key
Ejemplo n.º 3
0
def get_shared_key(private_key: ec.EllipticCurvePrivateKey,
                   peer_public_key: ec.EllipticCurvePublicKey,
                   algorithm: ec.ECDH = None) -> bytes:
    """
    creates a shared key
    mostly used ot get the derived key

    :param private_key: a private key
    :type private_key:  ec.EllipticCurvePrivateKey
    :param peer_public_key: the public key of the other party
    :type: ec.EllipticCurvePublicKey
    :param algorithm: an algoritm agreed upon with the other party
    :type algorithm: ec.ECDH
    :return:
    :rtype: bytes
    """
    __assure_private_key(private_key)
    __assure_public_key(peer_public_key)
    if not bool(algorithm) and algorithm is None:
        algorithm = ec.ECDH()
    shared_key = private_key.exchange(algorithm=algorithm,
                                      peer_public_key=peer_public_key)
    return shared_key