当前位置: 首页>>代码示例>>Python>>正文


Python serialization.BestAvailableEncryption方法代码示例

本文整理汇总了Python中cryptography.hazmat.primitives.serialization.BestAvailableEncryption方法的典型用法代码示例。如果您正苦于以下问题:Python serialization.BestAvailableEncryption方法的具体用法?Python serialization.BestAvailableEncryption怎么用?Python serialization.BestAvailableEncryption使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cryptography.hazmat.primitives.serialization的用法示例。


在下文中一共展示了serialization.BestAvailableEncryption方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_encryption_algorithm

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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 
开发者ID:openstack,项目名称:barbican,代码行数:19,代码来源:simple_crypto.py

示例2: generate_key_pair

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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) 
开发者ID:martenjacobs,项目名称:ToonRooter,代码行数:33,代码来源:sshkeys.py

示例3: test_bad_private_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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) 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:38,代码来源:test_key_pair_authentication.py

示例4: export_to_pem

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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) 
开发者ID:latchset,项目名称:jwcrypto,代码行数:36,代码来源:jwk.py

示例5: _generate_private_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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,
        ) 
开发者ID:openstack,项目名称:octavia,代码行数:17,代码来源:local.py

示例6: setUp

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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() 
开发者ID:openstack,项目名称:octavia,代码行数:34,代码来源:local_csr.py

示例7: serialize_private_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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) 
开发者ID:icon-project,项目名称:loopchain,代码行数:11,代码来源:serializer.py

示例8: create_private_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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 
开发者ID:Azure,项目名称:azure-iot-sdk-python,代码行数:29,代码来源:create_x509_chain_crypto.py

示例9: test_rsa

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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))) 
开发者ID:pyauth,项目名称:requests-http-signature,代码行数:23,代码来源:test.py

示例10: saveKeyPair

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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 
开发者ID:Ultimaker,项目名称:Uranium,代码行数:37,代码来源:Trust.py

示例11: write_ca

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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) 
开发者ID:mathiasertl,项目名称:django-ca,代码行数:34,代码来源:recreate-fixtures.py

示例12: rsa_private_key_bytes

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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,
    ) 
开发者ID:box,项目名称:box-python-sdk,代码行数:9,代码来源:test_jwt_auth.py

示例13: serialize_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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
        ) 
开发者ID:aws,项目名称:aws-ec2-instance-connect-cli,代码行数:58,代码来源:key_utils.py

示例14: setUp

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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) 
开发者ID:apache,项目名称:airflow,代码行数:57,代码来源:test_snowflake.py

示例15: _generate_certificate

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import BestAvailableEncryption [as 别名]
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 
开发者ID:openstack,项目名称:magnum,代码行数:60,代码来源:operations.py


注:本文中的cryptography.hazmat.primitives.serialization.BestAvailableEncryption方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。