How to use the cryptography.hazmat.primitives.serialization.Encoding 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 dcos / dcos / packages / dcos-integration-test / extra / test_iam.py View on Github external
"""
    Generate an RSA keypair. Serialize the public key in the the X.509
    SubjectPublicKeyInfo/OpenSSL PEM public key format (RFC 5280). Serialize the
    private key in the PKCS#8 (RFC 3447) format.

    Returns:
        (private key, public key) 2-tuple, both unicode
        objects holding the serialized keys.
    """
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=cryptography.hazmat.backends.default_backend())

    privkey_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    public_key = private_key.public_key()
    pubkey_pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)

    return privkey_pem.decode('ascii'), pubkey_pem.decode('ascii')
github Remmeauth / remme-core / remme / rest_api / pub_key_api_decorator.py View on Github external
def pub_key_already_exist(cert):
    account_client = AccountClient()
    address = account_client.make_address_from_data(cert.public_bytes(serialization.Encoding.DER).hex())
    try:
        account_client.get_value(address)
    except KeyNotFound:
        return False
    return True
github komlog-io / komlogd / lib / komlogd / api / common / crypto.py View on Github external
def store_keys(privkey, privkey_file, pubkey_file):
    privkey_serial = privkey.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    pubkey = privkey.public_key()
    pubkey_serial = pubkey.public_bytes(
        encoding=serialization.Encoding.OpenSSH,
        format=serialization.PublicFormat.OpenSSH
    )
    with os.fdopen(os.open(privkey_file, os.O_WRONLY | os.O_CREAT, 0o600), 'wb') as privkey_out:
        privkey_out.write(privkey_serial)
    try:
        with os.fdopen(os.open(pubkey_file, os.O_WRONLY | os.O_CREAT, 0o644), 'wb') as pubkey_out:
            pubkey_out.write(pubkey_serial)
    except:
        os.remove(privkey_file)
        raise
github pyca / cryptography / src / cryptography / hazmat / backends / openssl / ocsp.py View on Github external
def public_bytes(self, encoding):
        if encoding is not serialization.Encoding.DER:
            raise ValueError(
                "The only allowed encoding value is Encoding.DER"
            )

        bio = self._backend._create_mem_bio_gc()
        res = self._backend._lib.i2d_OCSP_RESPONSE_bio(
            bio, self._ocsp_response
        )
        self._backend.openssl_assert(res > 0)
        return self._backend._read_mem_bio(bio)
github Yubico / u2fval / u2fval / model.py View on Github external
def get_pem(self):
        cert = x509.load_der_x509_certificate(self.der, default_backend())
        return cert.public_bytes(Encoding.PEM)
github BankingofThings / BoT-Python-SDK / bot_python_sdk / key_generator.py View on Github external
def _public_key(key):
        return key.public_key().public_bytes(Encoding.PEM, PublicFormat.PKCS1).decode("utf-8")
github MicrochipTech / aws-iot-zero-touch-secure-provisioning-kit / aws_register_signer.py View on Github external
builder = x509.CertificateBuilder()
    builder = builder.serial_number(random_cert_sn(16))
    builder = builder.issuer_name(signer_ca_cert.subject)
    builder = builder.not_valid_before(datetime.utcnow().replace(tzinfo=timezone.utc))
    builder = builder.not_valid_after(builder._not_valid_before + timedelta(days=1))
    builder = builder.subject_name(x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, reg_code)]))
    builder = builder.public_key(signer_ca_cert.public_key())
    signer_ca_ver_cert = builder.sign(
        private_key=signer_ca_priv_key,
        algorithm=hashes.SHA256(),
        backend=crypto_be)

    # Write signer CA certificate to file for reference
    with open(SIGNER_CA_VER_CERT_FILENAME, 'wb') as f:
        print('    Saved to ' + f.name)
        f.write(signer_ca_ver_cert.public_bytes(encoding=serialization.Encoding.PEM))

    print('\nRegistering signer CA with AWS IoT')
    try:
        # TODO: Provide options when this fails (already exists, too many CAs with same name, etc...)
        response = aws_iot.register_ca_certificate(
            caCertificate=signer_ca_cert.public_bytes(encoding=serialization.Encoding.PEM).decode('ascii'),
            verificationCertificate=signer_ca_ver_cert.public_bytes(encoding=serialization.Encoding.PEM).decode('ascii'),
            setAsActive=True,
            allowAutoRegistration=True)
        ca_id = response['certificateId']
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == 'ResourceAlreadyExistsException':
            print('    This CA certificate already exists in AWS IoT')
            ca_id = re.search('ID:([0-9a-zA-Z]+)', e.response['Error']['Message']).group(1)
        else:
            raise
github paramiko / paramiko / paramiko / kex_curve25519.py View on Github external
def start_kex(self):
        self.key = X25519PrivateKey.generate()
        if self.transport.server_mode:
            self.transport._expect_packet(_MSG_KEXECDH_INIT)
            return

        m = Message()
        m.add_byte(c_MSG_KEXECDH_INIT)
        m.add_string(
            self.key.public_key().public_bytes(
                serialization.Encoding.Raw, serialization.PublicFormat.Raw
            )
        )
        self.transport._send_message(m)
        self.transport._expect_packet(_MSG_KEXECDH_REPLY)
github CPChain / pdash / cpchain / crypto.py View on Github external
def load_public_key():
        """
        load RSA public key bytes from private key
        Returns:
            public key bytes

        """
        public_bytes = RSACipher.load_private_key().public_key().public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        return public_bytes
github crgwbr / asymmetric-jwt-auth / src / asymmetric_jwt_auth / __init__.py View on Github external
def decrypt_key(key, password):
    """
    Decrypt an encrypted private key.

    :param key: Encrypted private key as a string.
    :param password: Key pass-phrase.
    :return: Decrypted private key as a string.
    """
    private = serialization.load_pem_private_key(key, password=password, backend=default_backend())
    return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())