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


Python backends.default_backend方法代码示例

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


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

示例1: rsa_encrypt

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def rsa_encrypt(data, pem, b64_encode=True):
    """
    rsa 加密
    :param data: 待加密字符串/binary
    :param pem: RSA public key 内容/binary
    :param b64_encode: 是否对输出进行 base64 encode
    :return: 如果 b64_encode=True 的话,返回加密并 base64 处理后的 string;否则返回加密后的 binary
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encoded_data = to_binary(data)
    pem = to_binary(pem)
    public_key = serialization.load_pem_public_key(pem, backend=default_backend())
    encrypted_data = public_key.encrypt(
        encoded_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
    )
    if b64_encode:
        encrypted_data = base64.b64encode(encrypted_data).decode("utf-8")
    return encrypted_data 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:24,代码来源:utils.py

示例2: rsa_decrypt

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def rsa_decrypt(encrypted_data, pem, password=None):
    """
    rsa 解密
    :param encrypted_data: 待解密 bytes
    :param pem: RSA private key 内容/binary
    :param password: RSA private key pass phrase
    :return: 解密后的 binary
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encrypted_data = to_binary(encrypted_data)
    pem = to_binary(pem)
    private_key = serialization.load_pem_private_key(pem, password, backend=default_backend())
    data = private_key.decrypt(
        encrypted_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
    )
    return data 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:22,代码来源:utils.py

示例3: encryption_step_5

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def encryption_step_5(self, module, message, additional_data, cm):
		client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):]

		c = module.lookup_client_pub(additional_data)

		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public)
		except:
			common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		client_ephemeral_public_key = public_numbers.public_key(default_backend())

		server_ephemeral_private_key = c.get_encryption().get_private_key()
		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		c.get_encryption().set_shared_key(hkdf.derive(server_ephemeral_private_key.exchange(ec.ECDH(), client_ephemeral_public_key)))

		module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data)

		common.internal_print("Encryption key agreed with the client.", 1)

		return module.cmh_struct[cm][3]

	# checking for the key file values in the config 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:26,代码来源:enc_advanced.py

示例4: decrypt

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def decrypt(self, shared_key, ciphertext):
		# the nonce should be 16 bytes long random data, but because of the 
		# small message size, we just get 4bytes and use it 4 times (extend).
		# This is ugly, makes the encryption more vulnerable, but if you need
		# something strong, please use the enhanced encryption module.
		nonce = ciphertext[0:4]
		extended_nonce = nonce*4
		algorithm = algorithms.ChaCha20(shared_key, extended_nonce)
		cipher = Cipher(algorithm, mode=None, backend=default_backend())
		decryptor = cipher.decryptor()

		return decryptor.update(ciphertext[4:])

	# server side.
	# Sending the pre-generated public key from the file to the client for 
	# verification purposes + key exchange 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:18,代码来源:enc_basic.py

示例5: encryption_step_5

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def encryption_step_5(self, module, message, additional_data, cm):
		client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):]

		c = module.lookup_client_pub(additional_data)

		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public)
		except:
			common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		client_ephemeral_public_key = public_numbers.public_key(default_backend())

		server_ephemeral_private_key = c.get_encryption().get_private_key()
		c.get_encryption().set_shared_key(server_ephemeral_private_key.exchange(ec.ECDH(), client_ephemeral_public_key))

		module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data)

		common.internal_print("Encryption key agreed with the client.", 1)

		return module.cmh_struct[cm][3]

	# checking for the key file values in the config 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:25,代码来源:enc_basic.py

示例6: _get_key

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
开发者ID:rtshome,项目名称:pgrepup,代码行数:22,代码来源:crypt.py

示例7: prepare_key

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def prepare_key(self, key):
            if isinstance(key, RSAPrivateKey) or \
               isinstance(key, RSAPublicKey):
                return key

            if isinstance(key, string_types):
                key = force_bytes(key)

                try:
                    if key.startswith(b'ssh-rsa'):
                        key = load_ssh_public_key(key, backend=default_backend())
                    else:
                        key = load_pem_private_key(key, password=None, backend=default_backend())
                except ValueError:
                    key = load_pem_public_key(key, backend=default_backend())
            else:
                raise TypeError('Expecting a PEM-formatted key.')

            return key 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:21,代码来源:algorithms.py

示例8: setup_method

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def setup_method(self, method):
        super(TestCustodiaIPACertRequests, self).setup_method(method)
        cert = x509.load_pem_x509_certificate(CERT_PEM, default_backend())
        cert_der = cert.public_bytes(serialization.Encoding.DER)
        cert_stripped = base64.b64encode(cert_der)
        ca = x509.load_pem_x509_certificate(CA_PEM, default_backend())
        ca_der = ca.public_bytes(serialization.Encoding.DER)
        self.m_api.Command.cert_request.return_value = {
            u'result': {
                u'subject': 'dummy subject',
                u'request_id': 1,
                u'serial_number': 1,
                u'certificate': cert_stripped,
                u'certificate_chain': (
                    cert_der,
                    ca_der,
                )
            }
        } 
开发者ID:latchset,项目名称:custodia,代码行数:21,代码来源:test_ipa.py

示例9: _verify_certificate_chain

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def _verify_certificate_chain(server_certificate_chain: List[str], trust_store: TrustStore) -> PathValidationResult:
    server_chain_as_x509s = [X509(pem_cert) for pem_cert in server_certificate_chain]
    chain_verifier = CertificateChainVerifier.from_file(trust_store.path)

    verified_chain: Optional[List[Certificate]]
    try:
        openssl_verify_str = None
        verified_chain_as_509s = chain_verifier.verify(server_chain_as_x509s)
        verified_chain = [
            load_pem_x509_certificate(x509_cert.as_pem().encode("ascii"), backend=default_backend())
            for x509_cert in verified_chain_as_509s
        ]
    except CertificateChainVerificationFailed as e:
        verified_chain = None
        openssl_verify_str = e.openssl_error_string

    return PathValidationResult(
        trust_store=trust_store, verified_certificate_chain=verified_chain, openssl_error_string=openssl_verify_str
    ) 
开发者ID:nabla-c0d3,项目名称:sslyze,代码行数:21,代码来源:_cert_chain_analyzer.py

示例10: generate_key_pair

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def generate_key_pair(key_length):
    private_key = rsa.generate_private_key(backend=default_backend(),
                                           public_exponent=65537,
                                           key_size=key_length)

    private_key_der = private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    public_key_pem = private_key.public_key().public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo) \
        .decode("utf-8")

    # strip off header
    public_key_der_encoded = ''.join(public_key_pem.split('\n')[1:-2])

    return private_key_der, public_key_der_encoded 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:21,代码来源:test_key_pair_authentication.py

示例11: create

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def create(cls, client, password, cert_data):
        """Create a new certificate."""
        cert = x509.load_pem_x509_certificate(cert_data, default_backend())
        base64_cert = cert.public_bytes(Encoding.PEM).decode('utf-8')
        # STRIP OUT CERT META "-----BEGIN CERTIFICATE-----"
        base64_cert = '\n'.join(base64_cert.split('\n')[1:-2])
        data = {
            'type': 'client',
            'certificate': base64_cert,
            'password': password,
        }
        client.api.certificates.post(json=data)

        # XXX: rockstar (08 Jun 2016) - Please see the open lxd bug here:
        # https://github.com/lxc/lxd/issues/2092
        fingerprint = binascii.hexlify(
            cert.fingerprint(hashes.SHA256())).decode('utf-8')
        return cls.get(client, fingerprint) 
开发者ID:lxc,项目名称:pylxd,代码行数:20,代码来源:certificate.py

示例12: generate_ssh_keypair

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def generate_ssh_keypair():
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.TraditionalOpenSSL,
        crypto_serialization.NoEncryption()
    ).decode("utf-8")
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    ).decode("utf-8")
    return (public_key, private_key) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:18,代码来源:0262e50e90e0_add_ssh_keypair_into_keypair.py

示例13: generate_ssh_keypair

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def generate_ssh_keypair() -> Tuple[str, str]:
    '''
    Generate RSA keypair for SSH/SFTP connection.
    '''
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.TraditionalOpenSSL,
        crypto_serialization.NoEncryption()
    ).decode("utf-8")
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    ).decode("utf-8")
    return (public_key, private_key) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:21,代码来源:keypair.py

示例14: _derive_keys

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def _derive_keys(self, password=None):
        label = encode(self.encryption_oid) + encode(self.mac_oid)
        context = self.nonce.asOctets()
        backend = default_backend()

        kdf = KBKDFHMAC(
            algorithm=hashes.SHA256(),
            mode=Mode.CounterMode,
            length=48,
            rlen=4,
            llen=4,
            location=CounterLocation.BeforeFixed,
            label=label,
            context=context,
            fixed=None,
            backend=backend
        )

        key = kdf.derive(password)
        if self.DEBUG:
            sys.stderr.write("Derived key: {0}\n".format(key))

        self.encryption_key = key[0:16]
        self.mac_key = key[16:] 
开发者ID:fireeye,项目名称:ADFSpoof,代码行数:26,代码来源:EncryptedPfx.py

示例15: keygen

# 需要导入模块: from cryptography.hazmat import backends [as 别名]
# 或者: from cryptography.hazmat.backends import default_backend [as 别名]
def keygen():
        """
        Generates a keypair using the cryptography lib and returns a tuple (public, private)
        """
        key = rsa.generate_private_key(public_exponent=65537, key_size=2048,
                                       backend=default_backend())

        private = key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                                    encryption_algorithm=serialization.NoEncryption()
                                    ).decode()

        public = key.public_key().public_bytes(encoding=serialization.Encoding.OpenSSH,
                                               format=serialization.PublicFormat.OpenSSH
                                               ).decode()

        return (public, private) 
开发者ID:grycap,项目名称:im,代码行数:19,代码来源:CloudConnector.py


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