How to use the cryptography.hazmat.primitives.serialization function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github HENNGE / aapns / tests / fake_client_cert.py View on Github external
def create_client_cert() -> bytes:
    ca_key = gen_private_key()
    ca_cert = gen_certificate(ca_key, "certificate_authority")
    client_key = gen_private_key()
    client_cert = gen_certificate(
        client_key, "client", issuer="certificate_authority", sign_key=ca_key
    )
    return client_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    ) + client_cert.public_bytes(encoding=serialization.Encoding.PEM)
github nccgroup / BLESuite / scapy / scapy / layers / tls / cert.py View on Github external
def import_from_tuple(self, tup):
        # this is rarely used
        e, m, mLen = tup
        if isinstance(m, bytes):
            m = pkcs_os2ip(m)
        if isinstance(e, bytes):
            e = pkcs_os2ip(e)
        self.fill_and_store(modulus=m, pubExp=e)
        self.pem = self.pubkey.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo)
        self.der = pem2der(self.pem)
github google / rekall / rekall-agent / rekall_agent / crypto.py View on Github external
def from_primitive(cls, pem_string, session=None):
        result = cls(session=session)
        try:
            result.from_raw_key(serialization.load_pem_private_key(
                utils.SmartStr(pem_string), password=None,
                backend=openssl.backend))
            return result
        except (TypeError, ValueError, exceptions.UnsupportedAlgorithm) as e:
            raise CipherError("Private Key invalid: %s" % e)

        return result
github google / grr / grr / core / grr_response_core / lib / rdfvalues / crypto.py View on Github external
def AsPassphraseProtectedPEM(self, passphrase):
    if self._value is None:
      return ""
    return self._value.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.BestAvailableEncryption(passphrase))
github Remmeauth / remme-core / remme / rest_api / pub_key_api_decorator.py View on Github external
def get_encryption_algorithm(payload):
    encryption_algorithm = serialization.NoEncryption()
    if 'passphrase' in payload.keys():
        if payload['passphrase']:
            encryption_algorithm = serialization.BestAvailableEncryption(
                payload['passphrase'].encode('utf-8'))
    return encryption_algorithm
github twisted / twisted / src / twisted / conch / ssh / transport.py View on Github external
C{ecdh-sha2-nistp*}, or L{X25519PublicKey} for
            C{curve25519-sha256}.
        @param ecPub: The public key to encode.

        @rtype: L{bytes}
        @return: The encoded public key.
        """
        if self.kexAlg.startswith(b'ecdh-sha2-nistp'):
            return ecPub.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint
            )
        elif self.kexAlg in (
                b'curve25519-sha256', b'curve25519-sha256@libssh.org'):
            return ecPub.public_bytes(
                serialization.Encoding.Raw,
                serialization.PublicFormat.Raw
            )
        else:
            raise UnsupportedAlgorithm(
                'Cannot encode elliptic curve public key for %r' %
                (self.kexAlg,))
github demisto / content / Integrations / Snowflake / Snowflake.py View on Github external
returns:
        Snowflake connection params
    """
    params: dict = {}
    set_provided(params, 'user', USER)
    set_provided(params, 'password', PASSWORD)
    set_provided(params, 'account', ACCOUNT)
    set_provided(params, 'authenticator', AUTHENTICATOR)
    set_provided(params, 'region', REGION)
    set_provided(params, 'insecure_mode', INSECURE)
    set_provided(params, 'warehouse', args.get('warehouse'), WAREHOUSE)
    set_provided(params, 'database', args.get('database'), DATABASE)
    set_provided(params, 'schema', args.get('schema'), SCHEMA)
    set_provided(params, 'role', args.get('role'), ROLE)
    if CERTIFICATE:
        p_key = serialization.load_pem_private_key(CERTIFICATE, password=CERT_PASSWORD, backend=default_backend())
        pkb = p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )
        params['private_key'] = pkb
    return params
github EFForg / starttls-everywhere / certbot / acme / acme / jose / jwk.py View on Github external
def _load_cryptography_key(cls, data, password=None, backend=None):
        backend = default_backend() if backend is None else backend
        exceptions = {}

        # private key?
        for loader in (serialization.load_pem_private_key,
                       serialization.load_der_private_key):
            try:
                return loader(data, password, backend)
            except (ValueError, TypeError,
                    cryptography.exceptions.UnsupportedAlgorithm) as error:
                exceptions[loader] = error

        # public key?
        for loader in (serialization.load_pem_public_key,
                       serialization.load_der_public_key):
            try:
                return loader(data, backend)
            except (ValueError,
                    cryptography.exceptions.UnsupportedAlgorithm) as error:
                exceptions[loader] = error
github SatelliteQE / robottelo / robottelo / manifests.py View on Github external
def _download_manifest_info(self):
        """Download and cache the manifest information."""
        self.template = requests.get(settings.fake_manifest.url).content
        self.signing_key = requests.get(settings.fake_manifest.key_url).content
        self.private_key = serialization.load_pem_private_key(
            self.signing_key,
            password=None,
            backend=default_backend()
        )