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


Python Fernet.generate_key方法代码示例

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


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

示例1: test_create_new_session_broken_by_format

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def test_create_new_session_broken_by_format(aiohttp_client,
                                                   fernet, key):

    async def handler(request):
        session = await get_session(request)
        assert isinstance(session, Session)
        assert session.new
        assert not session._changed
        assert {} == session
        return web.Response(body=b'OK')

    new_fernet = Fernet(Fernet.generate_key())
    client = await aiohttp_client(create_app(handler, key))
    make_cookie(client, new_fernet, {'a': 1, 'b': 12})
    resp = await client.get('/')
    assert resp.status == 200 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:18,代码来源:test_encrypted_cookie_storage.py

示例2: test_var_with_encryption_rotate_fernet_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def test_var_with_encryption_rotate_fernet_key(self, test_value):
        """
        Tests rotating encrypted variables.
        """
        key1 = Fernet.generate_key()
        key2 = Fernet.generate_key()

        with conf_vars({('core', 'fernet_key'): key1.decode()}):
            Variable.set('key', test_value)
            session = settings.Session()
            test_var = session.query(Variable).filter(Variable.key == 'key').one()
            self.assertTrue(test_var.is_encrypted)
            self.assertEqual(test_var.val, test_value)
            self.assertEqual(Fernet(key1).decrypt(test_var._val.encode()), test_value.encode())

        # Test decrypt of old value with new key
        with conf_vars({('core', 'fernet_key'): ','.join([key2.decode(), key1.decode()])}):
            crypto._fernet = None
            self.assertEqual(test_var.val, test_value)

            # Test decrypt of new value with new key
            test_var.rotate_fernet_key()
            self.assertTrue(test_var.is_encrypted)
            self.assertEqual(test_var.val, test_value)
            self.assertEqual(Fernet(key2).decrypt(test_var._val.encode()), test_value.encode()) 
开发者ID:apache,项目名称:airflow,代码行数:27,代码来源:test_variable.py

示例3: test_connection_extra_with_encryption_rotate_fernet_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def test_connection_extra_with_encryption_rotate_fernet_key(self):
        """
        Tests rotating encrypted extras.
        """
        key1 = Fernet.generate_key()
        key2 = Fernet.generate_key()

        with conf_vars({('core', 'fernet_key'): key1.decode()}):
            test_connection = Connection(extra='testextra')
            self.assertTrue(test_connection.is_extra_encrypted)
            self.assertEqual(test_connection.extra, 'testextra')
            self.assertEqual(Fernet(key1).decrypt(test_connection._extra.encode()), b'testextra')

        # Test decrypt of old value with new key
        with conf_vars({('core', 'fernet_key'): ','.join([key2.decode(), key1.decode()])}):
            crypto._fernet = None
            self.assertEqual(test_connection.extra, 'testextra')

            # Test decrypt of new value with new key
            test_connection.rotate_fernet_key()
            self.assertTrue(test_connection.is_extra_encrypted)
            self.assertEqual(test_connection.extra, 'testextra')
            self.assertEqual(Fernet(key2).decrypt(test_connection._extra.encode()), b'testextra') 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:test_connection.py

示例4: export

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def export(self, body, chain, key, options, **kwargs):
        """
        Generates a Java Truststore
        """

        if self.get_option("alias", options):
            alias = self.get_option("alias", options)
        else:
            alias = common_name(parse_certificate(body))

        if self.get_option("passphrase", options):
            passphrase = self.get_option("passphrase", options)
        else:
            passphrase = Fernet.generate_key().decode("utf-8")

        raw = create_truststore(body, chain, alias, passphrase)

        return "jks", passphrase, raw 
开发者ID:Netflix,项目名称:lemur,代码行数:20,代码来源:plugin.py

示例5: encrypt_to_file

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def encrypt_to_file(contents, filename):
    """
    Encrypts ``contents`` and writes it to ``filename``.

    ``contents`` should be a bytes string. ``filename`` should end with
    ``.enc``.

    Returns the secret key used for the encryption.

    Decrypt the file with :func:`doctr.travis.decrypt_file`.

    """
    if not filename.endswith('.enc'):
        raise ValueError("%s does not end with .enc" % filename)

    key = Fernet.generate_key()
    fer = Fernet(key)

    encrypted_file = fer.encrypt(contents)

    with open(filename, 'wb') as f:
        f.write(encrypted_file)

    return key 
开发者ID:drdoctr,项目名称:doctr,代码行数:26,代码来源:local.py

示例6: test_normalize_encrypt_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def test_normalize_encrypt_key():
    key = Fernet.generate_key()
    # b64 bytes
    assert db_base._normalize_encrypt_key(key) == key
    # b64 string
    assert db_base._normalize_encrypt_key(key.decode()) == key
    # raw bytes
    raw = base64.urlsafe_b64decode(key)
    assert db_base._normalize_encrypt_key(raw) == key

    # Too short
    with pytest.raises(ValueError) as exc:
        db_base._normalize_encrypt_key(b"abcde")
    assert "DASK_GATEWAY_ENCRYPT_KEYS" in str(exc.value)

    # Too short decoded
    with pytest.raises(ValueError) as exc:
        db_base._normalize_encrypt_key(b"\x00" * 43 + b"=")
    assert "DASK_GATEWAY_ENCRYPT_KEYS" in str(exc.value)

    # Invalid b64 encode
    with pytest.raises(ValueError) as exc:
        db_base._normalize_encrypt_key(b"=" + b"a" * 43)
    assert "DASK_GATEWAY_ENCRYPT_KEYS" in str(exc.value) 
开发者ID:dask,项目名称:dask-gateway,代码行数:26,代码来源:test_db_backend.py

示例7: create_datakey

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def create_datakey(encryption_context, keyid, client=None):
    '''
    Create a datakey from KMS.
    '''
    # Fernet key; from spec and cryptography implementation, but using
    # random from KMS, rather than os.urandom:
    #   https://github.com/fernet/spec/blob/master/Spec.md#key-format
    #   https://cryptography.io/en/latest/_modules/cryptography/fernet/#Fernet.generate_key
    key = base64.urlsafe_b64encode(
        client.generate_random(NumberOfBytes=32)['Plaintext']
    )
    response = client.encrypt(
        KeyId='{0}'.format(keyid),
        Plaintext=key,
        EncryptionContext=encryption_context

    )
    return {'ciphertext': response['CiphertextBlob'],
            'plaintext': key} 
开发者ID:lyft,项目名称:confidant,代码行数:21,代码来源:cryptolib.py

示例8: save_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def save_key():
    """
    Generates and saves a key for password encryption and 
    decryption.
    
    Uses cryptography.fernet.
    
    """

    # Generate key
    key = Fernet.generate_key()
    
    # Save key to file
    try:
        f = open(config_dir+key_file, 'wb')
    except IOError as e:
        if e.strerror == 'No such file or directory':
            print("Could not open key file for write")
            sys.exit()
        else:
            raise e
   
    f.write(key)
    f.close() 
开发者ID:bobbydurrett,项目名称:PythonDBAGraphs,代码行数:26,代码来源:util.py

示例9: load_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def load_key(self):
        """Loads the key from a hidden location"""
        token = ""
        if os.path.exists(self.keyname):
            with open(self.keyname, "r") as file:
                lines = file.readlines()
                for line in lines:
                    token = line.replace("\n", "")
                    break
        else:
            token = Fernet.generate_key()
            with open(self.keyname, "w+") as file:
                file.write(token.decode("utf-8"))
        if isinstance(token, bytes):
            return bytes(token)
        return bytes(token.encode()) 
开发者ID:oitsjustjose,项目名称:Flask-OpenCV-Streamer,代码行数:18,代码来源:login_manager.py

示例10: cmd_crypto_fernet_genkey

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def cmd_crypto_fernet_genkey(writecfg):
    """Generate a new Fernet Key, optionally write it to ~/.habu.json

    Example:

    \b
    $ habu.crypto.fernet.genkey
    xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg=
    """

    key = Fernet.generate_key()
    print(key.decode())

    if writecfg:
        habucfg = loadcfg(environment=False)
        habucfg['FERNET_KEY'] = key.decode()
        with Path('~/.habu.json').expanduser().open('w') as f:
            f.write(json.dumps(habucfg, indent=4, sort_keys=True)) 
开发者ID:fportantier,项目名称:habu,代码行数:20,代码来源:cmd_crypto_fernet_genkey.py

示例11: generate_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def generate_key(self):
        """
        Generates a 128-bit AES key for encrypting files. Sets self.cyptor with a Fernet object
        """

        self.key = Fernet.generate_key()
        self.cryptor = Fernet(self.key) 
开发者ID:jg-fisher,项目名称:python-ransomware,代码行数:9,代码来源:main.py

示例12: test_armm_encrypt

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def test_armm_encrypt(mock_remember_me_manager, monkeypatch):
    """
    unit tested:  encrypt

    test case:
    passes call to fernet.encrypt
    """
    mrmm = mock_remember_me_manager
    key = Fernet.generate_key()
    monkeypatch.setattr(mrmm, 'encryption_cipher_key', key)
    with mock.patch.object(Fernet, 'encrypt') as fernet_encrypt:
        fernet_encrypt.return_value = 'encrypted'
        result = mrmm.encrypt('serialized')
        fernet_encrypt.assert_called_once_with('serialized')
        assert result == 'encrypted' 
开发者ID:YosaiProject,项目名称:yosai,代码行数:17,代码来源:test_mgt.py

示例13: test_armm_decrypt

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def test_armm_decrypt(mock_remember_me_manager, monkeypatch):
    """
    unit tested:  decrypt

    test case:
    passes call to fernet.decrypt
    """
    mrmm = mock_remember_me_manager
    key = Fernet.generate_key()
    monkeypatch.setattr(mrmm, 'decryption_cipher_key', key)
    with mock.patch.object(Fernet, 'decrypt') as fernet_decrypt:
        fernet_decrypt.return_value = 'decrypted'
        result = mrmm.decrypt('serialized')
        fernet_decrypt.assert_called_once_with('serialized')
        assert result == 'decrypted' 
开发者ID:YosaiProject,项目名称:yosai,代码行数:17,代码来源:test_mgt.py

示例14: fernet_and_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def fernet_and_key():
    key = Fernet.generate_key()
    fernet = Fernet(key)
    return fernet, base64.urlsafe_b64decode(key) 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:6,代码来源:test_encrypted_cookie_storage.py

示例15: generate_key

# 需要导入模块: from cryptography.fernet import Fernet [as 别名]
# 或者: from cryptography.fernet.Fernet import generate_key [as 别名]
def generate_key():
    return Fernet.generate_key().decode("utf-8") 
开发者ID:MaibornWolff,项目名称:dcos-deploy,代码行数:4,代码来源:crypto.py


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