Python cryptography.hazmat.primitives.serialization.BestAvailableEncryption() Examples

The following are 16 code examples of cryptography.hazmat.primitives.serialization.BestAvailableEncryption(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.hazmat.primitives.serialization , or try the search function .
Example #1
Source File: simple_crypto.py    From barbican with Apache License 2.0 6 votes vote down vote up
def _get_encryption_algorithm(self, passphrase):
        """Choose whether to use encryption or not based on passphrase

        serialization.BestAvailableEncryption fails if passphrase is not
        given or if less than one byte therefore we need to check if it is
        valid or not
        """
        if passphrase:
            # encryption requires password in bytes format
            algorithm = serialization.BestAvailableEncryption(
                # default encoding is utf-8
                encodeutils.safe_encode(passphrase)
            )
        else:
            algorithm = serialization.NoEncryption()

        return algorithm 
Example #2
Source File: sshkeys.py    From ToonRooter with MIT License 5 votes vote down vote up
def generate_key_pair(password=None):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa

    from cryptography.hazmat.primitives import serialization

    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )

    key_encryption_algorithm = serialization.NoEncryption()
    if password:
        key_encryption_algorithm = serialization.BestAvailableEncryption(password)

    private_pem = private_key.private_bytes(
       encoding=serialization.Encoding.PEM,
       format=serialization.PrivateFormat.PKCS8,
       encryption_algorithm=key_encryption_algorithm
    )


    public_key = private_key.public_key()

    public_openssh = public_key.public_bytes(
       encoding=serialization.Encoding.OpenSSH,
       format=serialization.PublicFormat.OpenSSH
    )

    return (public_openssh, private_pem) 
Example #3
Source File: test_key_pair_authentication.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_bad_private_key(db_parameters):
    db_config = {
        'protocol': db_parameters['protocol'],
        'account': db_parameters['account'],
        'user': db_parameters['user'],
        'host': db_parameters['host'],
        'port': db_parameters['port'],
        'database': db_parameters['database'],
        'schema': db_parameters['schema'],
        'timezone': 'UTC',
    }

    dsa_private_key = dsa.generate_private_key(key_size=2048,
                                               backend=default_backend())
    dsa_private_key_der = dsa_private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    encrypted_rsa_private_key_der = rsa.generate_private_key(key_size=2048,
                                                             public_exponent=65537,
                                                             backend=default_backend()) \
        .private_bytes(encoding=serialization.Encoding.DER,
                       format=serialization.PrivateFormat.PKCS8,
                       encryption_algorithm=serialization.BestAvailableEncryption(
                           b'abcd'))

    bad_private_key_test_cases = ["abcd", 1234, b'abcd', dsa_private_key_der,
                                  encrypted_rsa_private_key_der]

    for private_key in bad_private_key_test_cases:
        db_config['private_key'] = private_key
        with pytest.raises(
                snowflake.connector.errors.ProgrammingError) as exec_info:
            snowflake.connector.connect(**db_config)
        assert (exec_info.value.errno == 251008) 
Example #4
Source File: test_key_pair_authentication.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_bad_private_key(db_parameters):
    db_config = {
        'protocol': db_parameters['protocol'],
        'account': db_parameters['account'],
        'user': db_parameters['user'],
        'host': db_parameters['host'],
        'port': db_parameters['port'],
        'database': db_parameters['database'],
        'schema': db_parameters['schema'],
        'timezone': 'UTC',
    }

    dsa_private_key = dsa.generate_private_key(key_size=2048,
                                               backend=default_backend())
    dsa_private_key_der = dsa_private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    encrypted_rsa_private_key_der = rsa.generate_private_key(key_size=2048,
                                                             public_exponent=65537,
                                                             backend=default_backend()) \
        .private_bytes(encoding=serialization.Encoding.DER,
                       format=serialization.PrivateFormat.PKCS8,
                       encryption_algorithm=serialization.BestAvailableEncryption(
                           b'abcd'))

    bad_private_key_test_cases = ["abcd", 1234, b'abcd', dsa_private_key_der,
                                  encrypted_rsa_private_key_der]

    for private_key in bad_private_key_test_cases:
        db_config['private_key'] = private_key
        with pytest.raises(
                snowflake.connector.errors.ProgrammingError) as exec_info:
            snowflake.connector.connect(**db_config)
        assert (exec_info.value.errno == 251008) 
Example #5
Source File: jwk.py    From jwcrypto with GNU Lesser General Public License v3.0 5 votes vote down vote up
def export_to_pem(self, private_key=False, password=False):
        """Exports keys to a data buffer suitable to be stored as a PEM file.
        Either the public or the private key can be exported to a PEM file.
        For private keys the PKCS#8 format is used. If a password is provided
        the best encryption method available as determined by the cryptography
        module is used to wrap the key.

        :param private_key: Whether the private key should be exported.
         Defaults to `False` which means the public key is exported by default.
        :param password(bytes): A password for wrapping the private key.
         Defaults to False which will cause the operation to fail. To avoid
         encryption the user must explicitly pass None, otherwise the user
         needs to provide a password in a bytes buffer.
        """
        e = serialization.Encoding.PEM
        if private_key:
            if not self.has_private:
                raise InvalidJWKType("No private key available")
            f = serialization.PrivateFormat.PKCS8
            if password is None:
                a = serialization.NoEncryption()
            elif isinstance(password, bytes):
                a = serialization.BestAvailableEncryption(password)
            elif password is False:
                raise ValueError("The password must be None or a bytes string")
            else:
                raise TypeError("The password string must be bytes")
            return self._get_private_key().private_bytes(
                encoding=e, format=f, encryption_algorithm=a)
        else:
            if not self.has_public:
                raise InvalidJWKType("No public key available")
            f = serialization.PublicFormat.SubjectPublicKeyInfo
            return self._get_public_key().public_bytes(encoding=e, format=f) 
Example #6
Source File: local.py    From octavia with Apache License 2.0 5 votes vote down vote up
def _generate_private_key(cls, bit_length=2048, passphrase=None):
        pk = rsa.generate_private_key(
            public_exponent=65537,
            key_size=bit_length,
            backend=backends.default_backend()
        )
        if passphrase:
            encryption = serialization.BestAvailableEncryption(passphrase)
        else:
            encryption = serialization.NoEncryption()
        return pk.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=encryption,
        ) 
Example #7
Source File: local_csr.py    From octavia with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.signing_digest = "sha256"

        # Set up CSR data
        csr_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=backends.default_backend()
        )
        csr = x509.CertificateSigningRequestBuilder().subject_name(
            x509.Name([
                x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"test"),
            ])).sign(csr_key, hashes.SHA256(), backends.default_backend())
        self.certificate_signing_request = csr.public_bytes(
            serialization.Encoding.PEM)

        # Set up keys
        self.ca_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=backends.default_backend()
        )

        self.ca_private_key_passphrase = b"Testing"
        self.ca_private_key = self.ca_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.BestAvailableEncryption(
                self.ca_private_key_passphrase),
        )

        super(BaseLocalCSRTestCase, self).setUp() 
Example #8
Source File: serializer.py    From loopchain with Apache License 2.0 5 votes vote down vote up
def serialize_private_key(cls, private_key: bytes, password=Optional[bytes]) -> bytes:
        pri_key = ec.derive_private_key(int.from_bytes(private_key, byteorder="big"),
                                        ec.SECP256K1,
                                        default_backend())
        algorithm = \
            serialization.BestAvailableEncryption(password) if password is not None else serialization.NoEncryption()
        return pri_key.private_bytes(encoding=cls.encoding,
                                     format=serialization.PrivateFormat.PKCS8,
                                     encryption_algorithm=algorithm) 
Example #9
Source File: create_x509_chain_crypto.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def create_private_key(key_file, password=None, key_size=4096):
    """
    Crate encrypted key for certificates.
    :param key_file: The file to store the key.
    :param password: Password for the key.
    :param key_size: The key size to use for encryption. The default is 4096.
    :return: The private key.
    """
    if password:
        encrypt_algo = serialization.BestAvailableEncryption(str.encode(password))
    else:
        encrypt_algo = serialization.NoEncryption()

    private_key = rsa.generate_private_key(
        public_exponent=PUBLIC_EXPONENT, key_size=key_size, backend=default_backend()
    )
    # Write our key to file
    with open(key_file, "wb") as f:
        f.write(
            private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=encrypt_algo,
            )
        )

    return private_key 
Example #10
Source File: test.py    From requests-http-signature with Apache License 2.0 5 votes vote down vote up
def test_rsa(self):
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.hazmat.primitives import serialization
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        private_key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.BestAvailableEncryption(passphrase)
        )
        public_key_pem = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        url = 'http://example.com/path?query#fragment'
        auth = HTTPSignatureAuth(algorithm="rsa-sha256", key=private_key_pem, key_id="sekret", passphrase=passphrase)
        self.session.get(url, auth=auth, headers=dict(pubkey=base64.b64encode(public_key_pem))) 
Example #11
Source File: Trust.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def saveKeyPair(private_key: "RSAPrivateKeyWithSerialization", private_path: str, public_path: str, optional_password: Optional[str] = None) -> bool:
        """Save a key-pair to two distinct files.

        :param private_key: The private key to save. The public one will be generated from it.
        :param private_path: Path to the filename where the private key will be saved.
        :param public_path: Path to the filename where the public key will be saved.
        :param optional_password: The private key can be signed with a password as well (or not).
        :return: True on success.
        """

        try:
            encrypt_method = serialization.NoEncryption()  # type: ignore
            if optional_password is not None:
                encrypt_method = serialization.BestAvailableEncryption(optional_password.encode())  # type: ignore
            private_pem = private_key.private_bytes(
                encoding = serialization.Encoding.PEM,
                format = serialization.PrivateFormat.PKCS8,
                encryption_algorithm = encrypt_method
            )
            with open(private_path, "wb") as private_file:
                private_file.write(private_pem)

            public_pem = private_key.public_key().public_bytes(
                encoding = serialization.Encoding.PEM,
                format = serialization.PublicFormat.PKCS1
            )
            with open(public_path, "wb") as public_file:
                public_file.write(public_pem)

            Logger.log("i", "Private/public key-pair saved to '{0}','{1}'.".format(private_path, public_path))
            return True

        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException("e", "Save private/public key to '{0}','{1}' failed.".format(private_path, public_path))
        return False 
Example #12
Source File: recreate-fixtures.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def write_ca(cert, data, password=None):
    key_dest = os.path.join(args.dest, data['key_filename'])
    pub_dest = os.path.join(args.dest, data['pub_filename'])
    key_der_dest = os.path.join(args.dest, data['key_der_filename'])
    pub_der_dest = os.path.join(args.dest, data['pub_der_filename'])

    # write files to dest
    shutil.copy(ca_storage.path(cert.private_key_path), key_dest)
    with open(pub_dest, 'w') as stream:
        stream.write(cert.pub)

    if password is None:
        encryption = NoEncryption()
    else:
        encryption = BestAvailableEncryption(password)

    key_der = cert.key(password=password).private_bytes(
        encoding=Encoding.DER, format=PrivateFormat.PKCS8, encryption_algorithm=encryption)
    with open(key_der_dest, 'wb') as stream:
        stream.write(key_der)
    with open(pub_der_dest, 'wb') as stream:
        stream.write(cert.dump_certificate(Encoding.DER))

    # These keys are only present in CAs:
    data['issuer_url'] = ca.issuer_url
    data['crl_url'] = ca.crl_url
    data['ca_crl_url'] = '%s%s' % (testserver, reverse('django_ca:ca-crl', kwargs={'serial': ca.serial}))
    data['ocsp_url'] = '%s%s' % (testserver, reverse('django_ca:ocsp-cert-post',
                                                     kwargs={'serial': ca.serial}))

    # Update common data for CAs and certs
    update_cert_data(cert, data) 
Example #13
Source File: test_jwt_auth.py    From box-python-sdk with Apache License 2.0 5 votes vote down vote up
def rsa_private_key_bytes(rsa_private_key_object, rsa_passphrase):
    encryption = serialization.BestAvailableEncryption(rsa_passphrase) if rsa_passphrase else serialization.NoEncryption()
    return rsa_private_key_object.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=encryption,
    ) 
Example #14
Source File: key_utils.py    From aws-ec2-instance-connect-cli with Apache License 2.0 4 votes vote down vote up
def serialize_key(key, encoding='PEM', return_private=False, password=None):
    """
    Given an RSA private key object, return the public or private key in the requested encoding.
    encoded in the requested formats.  Private keys will always use TraditionalOpenSSL format,
    because that's the format supported by Paramiko
    public keys will always use SubjectPublicKeyInfo format UNLESS
    the encoding is 'OpenSSH' (in which case, it will use OpenSSH format).

    :param key: An RSA private key object
    :type key: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
    :param encoding: The encoding to use for serializing the private key. Allowed: 'PEM', 'DER', 'OpenSSH'. Default: 'PEM'. \
       Note that if return_private is True then 'OpenSSH' is not allowed.
    :type encoding: basestring
    :param return_private: Whether to return the public or private key.  Default: False.
    :type return_private: bool
    :param password: In bytes, an optional password to use for encoding a private key. Ignored if return_private is False. \
       Default: None
    :type password: basestring
    :return: Encoded key as a byte array
    :rtype: bytearray
    """
    if return_private and encoding == 'OpenSSH':
        raise AssertionError('Private keys cannot be serialized in OpenSSH encoding')

    if encoding == 'OpenSSH':
        assert(not return_private)
        enc = crypto_serialization.Encoding.OpenSSH
    elif encoding == 'PEM':
        enc = crypto_serialization.Encoding.PEM
    elif encoding == 'DER':
        enc = crypto_serialization.Encoding.DER
    else:
        raise AssertionError('Unrecognized encoding {0}'.format(encoding))

    if return_private:
        if password:
            enc_alg = crypto_serialization.BestAvailableEncryption(password)
        else:
            enc_alg = crypto_serialization.NoEncryption()

        return key.private_bytes(
            encoding=enc,
            format=crypto_serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=enc_alg
        )

    else:
        if encoding == 'OpenSSH':
            format = crypto_serialization.PublicFormat.OpenSSH
        else:
            format = crypto_serialization.PublicFormat.SubjectPublicKeyInfo

        return key.public_key().public_bytes(
            encoding=enc,
            format=format
        ) 
Example #15
Source File: test_snowflake.py    From airflow with Apache License 2.0 4 votes vote down vote up
def setUp(self):
        super().setUp()

        self.cur = mock.MagicMock()
        self.conn = conn = mock.MagicMock()
        self.conn.cursor.return_value = self.cur

        self.conn.login = 'user'
        self.conn.password = 'pw'
        self.conn.schema = 'public'
        self.conn.extra_dejson = {'database': 'db',
                                  'account': 'airflow',
                                  'warehouse': 'af_wh',
                                  'region': 'af_region',
                                  'role': 'af_role'}

        class UnitTestSnowflakeHook(SnowflakeHook):
            conn_name_attr = 'snowflake_conn_id'

            def get_conn(self):
                return conn

            def get_connection(self, _):
                return conn

        self.db_hook = UnitTestSnowflakeHook()

        self.non_encrypted_private_key = "/tmp/test_key.pem"
        self.encrypted_private_key = "/tmp/test_key.p8"

        # Write some temporary private keys. First is not encrypted, second is with a passphrase.
        key = rsa.generate_private_key(
            backend=default_backend(),
            public_exponent=65537,
            key_size=2048
        )
        private_key = key.private_bytes(serialization.Encoding.PEM,
                                        serialization.PrivateFormat.PKCS8,
                                        serialization.NoEncryption())

        with open(self.non_encrypted_private_key, "wb") as file:
            file.write(private_key)

        key = rsa.generate_private_key(
            backend=default_backend(),
            public_exponent=65537,
            key_size=2048
        )
        private_key = key.private_bytes(serialization.Encoding.PEM,
                                        serialization.PrivateFormat.PKCS8,
                                        encryption_algorithm=serialization.BestAvailableEncryption(
                                            self.conn.password.encode()))

        with open(self.encrypted_private_key, "wb") as file:
            file.write(private_key) 
Example #16
Source File: operations.py    From magnum with Apache License 2.0 4 votes vote down vote up
def _generate_certificate(issuer_name, subject_name, extensions,
                          organization_name=None, ca_key=None,
                          encryption_password=None, ca_key_password=None):

    if not isinstance(subject_name, six.text_type):
        subject_name = six.text_type(subject_name.decode('utf-8'))
    if organization_name and not isinstance(organization_name, six.text_type):
        organization_name = six.text_type(organization_name.decode('utf-8'))

    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=CONF.x509.rsa_key_size,
        backend=default_backend()
    )

    # subject name is set as common name
    csr = x509.CertificateSigningRequestBuilder()
    name_attributes = [x509.NameAttribute(x509.OID_COMMON_NAME, subject_name)]
    if organization_name:
        name_attributes.append(x509.NameAttribute(x509.OID_ORGANIZATION_NAME,
                                                  organization_name))
    csr = csr.subject_name(x509.Name(name_attributes))

    for extention in extensions:
        csr = csr.add_extension(extention.value, critical=extention.critical)

    # if ca_key is not provided, it means self signed
    if not ca_key:
        ca_key = private_key
        ca_key_password = encryption_password

    csr = csr.sign(private_key, hashes.SHA256(), default_backend())

    if six.PY3 and isinstance(encryption_password, six.text_type):
        encryption_password = encryption_password.encode()

    if encryption_password:
        encryption_algorithm = serialization.BestAvailableEncryption(
            encryption_password)
    else:
        encryption_algorithm = serialization.NoEncryption()

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

    keypairs = {
        'private_key': private_key,
        'certificate': sign(
            csr,
            issuer_name,
            ca_key,
            ca_key_password=ca_key_password,
            skip_validation=True),
    }
    return keypairs