Ejemplo n.º 1
0
def _build_extensions_ca(subject_key: ec.EllipticCurvePrivateKey,
                         issuer_key: ec.EllipticCurvePrivateKey) -> Extensions:
    """
    Returns a list of Extension with the extension and its criticality
    """
    return [
        Extension(x509.BasicConstraints(ca=True, path_length=0),
                  critical=True),
        Extension(x509.KeyUsage(digital_signature=False,
                                content_commitment=False,
                                key_encipherment=False,
                                data_encipherment=False,
                                key_agreement=False,
                                key_cert_sign=True,
                                crl_sign=True,
                                encipher_only=False,
                                decipher_only=False),
                  critical=True),
        Extension(x509.SubjectKeyIdentifier.from_public_key(
            subject_key.public_key()),
                  critical=False),
        Extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(
            issuer_key.public_key()),
                  critical=False)
    ]
Ejemplo n.º 2
0
def _build_extensions_as(subject_key: ec.EllipticCurvePrivateKey,
                         issuer_key: ec.EllipticCurvePrivateKey) -> Extensions:
    """
    Returns a list of Extension with the extension and its criticality
    """
    return [
        Extension(x509.KeyUsage(digital_signature=True,
                                content_commitment=False,
                                key_encipherment=False,
                                data_encipherment=False,
                                key_agreement=False,
                                key_cert_sign=False,
                                crl_sign=False,
                                encipher_only=False,
                                decipher_only=False),
                  critical=True),
        Extension(x509.SubjectKeyIdentifier.from_public_key(
            subject_key.public_key()),
                  critical=False),
        Extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(
            issuer_key.public_key()),
                  critical=False),
        Extension(x509.ExtendedKeyUsage([
            x509.ExtendedKeyUsageOID.SERVER_AUTH,
            x509.ExtendedKeyUsageOID.CLIENT_AUTH,
            x509.ExtendedKeyUsageOID.TIME_STAMPING
        ]),
                  critical=False)
    ]
Ejemplo n.º 3
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.º 4
0
    def encode_private(self, private_key: ec.EllipticCurvePrivateKey,
                       f_priv: _FragList) -> None:
        """Write ECDSA private key"""
        public_key = private_key.public_key()
        private_numbers = private_key.private_numbers()

        self.encode_public(public_key, f_priv)
        f_priv.put_mpint(private_numbers.private_value)
 def ready(self, private_key: ec.EllipticCurvePrivateKey):
     self.public_key = private_key.public_key()
     self.timestamp = time.time()
     self.signature = Transaction.__sign(struct.pack('=f', self.timestamp) + self.ipt.b + self.opt.b, private_key)
     self.txid, content = self.__hash_trans()
     self.b = self.__tobin(content)
     self.length = len(self.b)
Ejemplo n.º 6
0
def _build_extensions_voting(key: ec.EllipticCurvePrivateKey,
                             issuer_key_type: ObjectIdentifier) -> Extensions:
    return [
        Extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
                  critical=False),
        Extension(x509.ExtendedKeyUsage(
            [issuer_key_type, x509.ExtendedKeyUsageOID.TIME_STAMPING]),
                  critical=False)
    ]
Ejemplo n.º 7
0
 def _sign(self, key: ec.EllipticCurvePrivateKey, msg: bytes) -> bytes:
     try:
         return key.sign(msg, ec.ECDSA(self.hash))
     except AttributeError as error:
         logger.debug(error, exc_info=True)
         raise errors.Error('Public key cannot be used for signing')
     except ValueError as error:  # digest too large
         logger.debug(error, exc_info=True)
         raise errors.Error(str(error))
Ejemplo n.º 8
0
def get_private_key_bytes(
    private_key: ec.EllipticCurvePrivateKey,
    encoding: Encoding = Encoding.DER,
    format: PrivateFormat = PrivateFormat.PKCS8,
    encryption_algorithm: KeySerializationEncryption = NoEncryption()
) -> bytes:
    """ Returns the bytes from a cryptography ec.EllipticCurvePrivateKey
    """
    return private_key.private_bytes(encoding=encoding,
                                     format=format,
                                     encryption_algorithm=encryption_algorithm)
Ejemplo n.º 9
0
def get_public_key(
        private_key: ec.EllipticCurvePrivateKey) -> ec.EllipticCurvePublicKey:
    """
    Helper function to generate a public key
    :param private_key: private key to get the public key from
    :type private_key: ec.EllipticCurvePrivateKey
    :return: public key
    :rtype: ec.EllipticCurvePublicKey
    """
    __assure_private_key(private_key)
    return private_key.public_key()
Ejemplo n.º 10
0
    def get_public_keys_from_private_ECDSA(
            private_key: ec.EllipticCurvePrivateKey) -> Tuple[bytes, str]:
        """
        Get public keys (bytes and base58) from private key (ECDSA)
        :param private_key: private key
        :return: public key bytes, public key base58
        """
        public_key = private_key.public_key()

        public_bytes = public_key.public_bytes(
            encoding=serialization.Encoding.X962,
            format=serialization.PublicFormat.UncompressedPoint)
        return public_bytes, base58.b58encode(public_bytes).decode('ascii')
Ejemplo n.º 11
0
 def _write_private_key_and_cert(
     self, key: ec.EllipticCurvePrivateKey, cert: x509.Certificate, disk_folder: str
 ) -> None:
     cert_file = os.path.join(disk_folder, self.private_cert_file_name)
     with open(cert_file, "w+") as file:
         file.write(
             key.private_bytes(
                 serialization.Encoding.PEM,
                 serialization.PrivateFormat.TraditionalOpenSSL,
                 serialization.NoEncryption(),
             ).decode("UTF-8")
         )
         file.write(cert.public_bytes(serialization.Encoding.PEM).decode("UTF-8"))
Ejemplo n.º 12
0
def generate_certificate(key: ec.EllipticCurvePrivateKey) -> x509.Certificate:
    name = x509.Name([
        x509.NameAttribute(
            x509.NameOID.COMMON_NAME,
            binascii.hexlify(os.urandom(16)).decode("ascii"),
        )
    ])
    builder = (x509.CertificateBuilder().subject_name(name).issuer_name(
        name).public_key(key.public_key()).serial_number(
            x509.random_serial_number()).not_valid_before(
                datetime.datetime.utcnow() - datetime.timedelta(
                    days=1)).not_valid_after(datetime.datetime.utcnow() +
                                             datetime.timedelta(days=30)))
    return builder.sign(key, hashes.SHA256(), default_backend())
Ejemplo n.º 13
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.º 14
0
def sign_data(data: bytes,
              private_key: ec.EllipticCurvePrivateKey,
              algorithm: ec.ECDSA = None) -> bytes:
    """
    Sign data with the private key to ensure te receiving party that it is your's
    The other party needs the public key to ensure the signed data is from the expected source.
    The signature should be send with the data that is given.

    :param private_key: the private key to sign the data with
    :param data: data to sign
    :param algorithm: algorithm agreed upon with the receiving party
    :return: signature based on the data
    """
    __assure_private_key(private_key)
    if not bool(algorithm):
        algorithm = ec.ECDSA(hashes.SHA256())
    signed_data = private_key.sign(data, algorithm)
    return signed_data
Ejemplo n.º 15
0
def generate_private_pem(private_key: ec.EllipticCurvePrivateKey,
                         pwd: bytes = None) -> bytes:
    """
    Private function to make generate a pem which can be saved to store the private key
    This should never been send to the other party

    :param private_key:  the private_key
    :param pwd: password: if not None, Best available encryption is chosen
                and the private key is encrypted with a the password
    :return:  bytes
    """
    __assure_private_key(private_key)
    encrypt_algo = serialization.NoEncryption()
    if bool(pwd):  # if password and length is greater of equal to 1.
        encrypt_algo = serialization.BestAvailableEncryption(pwd)

    pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.PKCS8,
                                    encryption_algorithm=encrypt_algo)
    return pem
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def _build_extensions_root(key: ec.EllipticCurvePrivateKey) -> Extensions:
    """
    Returns a list of Extension with the extension and its criticality
    """
    return [
        Extension(x509.BasicConstraints(ca=True, path_length=1),
                  critical=True),
        Extension(x509.KeyUsage(digital_signature=False,
                                content_commitment=False,
                                key_encipherment=False,
                                data_encipherment=False,
                                key_agreement=False,
                                key_cert_sign=True,
                                crl_sign=True,
                                encipher_only=False,
                                decipher_only=False),
                  critical=True),
        Extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
                  critical=False),
        Extension(x509.ExtendedKeyUsage(
            [OID_ROOT_KEY, x509.ExtendedKeyUsageOID.TIME_STAMPING]),
                  critical=False)
    ]
Ejemplo n.º 18
0
    def sign(self, key: ec.EllipticCurvePrivateKey):
        data = msgpack.packb(self.values(exclude={'signature'}))

        self.signature = key.sign(data, ec.ECDSA(hashes.SHA256()))
Ejemplo n.º 19
0
def get_payload(msg: str, priv_key: ec.EllipticCurvePrivateKey) -> bytes:
	compressed_msg = gzcompress(json.dumps(msg, separators=(',', ':'), ensure_ascii=True).encode('ascii'), 9)
	signature = priv_key.sign(compressed_msg, ec.ECDSA(SHA256()))
	return len(signature).to_bytes(2, 'big') + signature + compressed_msg
Ejemplo n.º 20
0
 def sign(private_key: EllipticCurvePrivateKey, data: bytes) -> bytes:
     """Sign one block of data which can be verified later by other using the public key."""
     return bytes(private_key.sign(data, ec.ECDSA(hashes.SHA256())))
Ejemplo n.º 21
0
 def __sign(data: bytes, private_key: ec.EllipticCurvePrivateKey) -> SIGNATURE:
     return private_key.sign(data, ec.ECDSA(hashes.SHA256()))