Python cryptography.fernet.Fernet.generate_key() Examples

The following are 30 code examples of cryptography.fernet.Fernet.generate_key(). 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.fernet.Fernet , or try the search function .
Example #1
Source File: util.py    From PythonDBAGraphs with GNU General Public License v3.0 7 votes vote down vote up
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() 
Example #2
Source File: test_db_backend.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #3
Source File: cmd_crypto_fernet_genkey.py    From habu with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #4
Source File: test_encrypted_cookie_storage.py    From aiohttp-session with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: test_variable.py    From airflow with Apache License 2.0 6 votes vote down vote up
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()) 
Example #6
Source File: local.py    From doctr with MIT License 6 votes vote down vote up
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 
Example #7
Source File: login_manager.py    From Flask-OpenCV-Streamer with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #8
Source File: plugin.py    From lemur with Apache License 2.0 6 votes vote down vote up
def export(self, body, chain, key, options, **kwargs):
        """
        Generates a Java Keystore
        """

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

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

        raw = create_keystore(body, chain, key, alias, passphrase)

        return "jks", passphrase, raw 
Example #9
Source File: plugin.py    From lemur with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: cryptolib.py    From confidant with Apache License 2.0 6 votes vote down vote up
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} 
Example #11
Source File: cli.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def make_flowauth_fernet_key():
    """
    Generate a new Fernet key for symmetric encryption of data at
    rest.
    """
    print(f'FLOWAUTH_FERNET_KEY="{Fernet.generate_key().decode()}"') 
Example #12
Source File: test_db_backend.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_encryption(tmpdir):
    db_url = "sqlite:///%s" % tmpdir.join("dask_gateway.sqlite")
    encrypt_keys = [Fernet.generate_key() for i in range(3)]
    db = DataManager(url=db_url, encrypt_keys=encrypt_keys)

    assert db.fernet is not None

    data = b"my secret data"
    encrypted = db.encrypt(data)
    assert encrypted != data

    data2 = db.decrypt(encrypted)
    assert data == data2

    c = db.create_cluster("alice", {}, {})
    assert c.tls_cert is not None
    assert c.tls_key is not None

    # Check database state is encrypted
    with db.db.begin() as conn:
        res = conn.execute(
            db_base.clusters.select(db_base.clusters.c.id == c.id)
        ).fetchone()
    assert res.tls_credentials != b";".join((c.tls_cert, c.tls_key))
    cert, key = db.decrypt(res.tls_credentials).split(b";")
    token = db.decrypt(res.token).decode()
    assert cert == c.tls_cert
    assert key == c.tls_key
    assert token == c.token

    # Check can reload database with keys
    db2 = DataManager(url=db_url, encrypt_keys=encrypt_keys)
    c2 = db2.id_to_cluster[c.id]
    assert c2.tls_cert == c.tls_cert
    assert c2.tls_key == c.tls_key
    assert c2.token == c.token 
Example #13
Source File: ciphermanager_test.py    From confidant with Apache License 2.0 5 votes vote down vote up
def test_cipher_version_2():
    key = Fernet.generate_key()
    cipher = CipherManager(key, 2)
    ciphertext = cipher.encrypt('testdata')

    # Assert we're getting back some form of altered data
    assert ciphertext != 'testdata'

    cipher = CipherManager(key, 2)
    plaintext = cipher.decrypt(ciphertext).decode('UTF-8')

    # Assert that decrypting using a new cipher object with the same key
    # and version give back the same plaintext.
    assert plaintext == 'testdata' 
Example #14
Source File: ciphermanager_test.py    From confidant with Apache License 2.0 5 votes vote down vote up
def test_cipher_version_1():
    key = Fernet.generate_key()
    cipher = CipherManager(key, 1)
    with pytest.raises(CipherManagerError):
        cipher.encrypt('testdata')
    with pytest.raises(CipherManagerError):
        cipher.decrypt('random_text') 
Example #15
Source File: ciphermanager_test.py    From confidant with Apache License 2.0 5 votes vote down vote up
def test_cipher_version_3():
    key = Fernet.generate_key()
    cipher = CipherManager(key, 3)
    with pytest.raises(CipherManagerError):
        cipher.encrypt('testdata')
    with pytest.raises(CipherManagerError):
        cipher.decrypt('random_text') 
Example #16
Source File: cryptolib.py    From confidant with Apache License 2.0 5 votes vote down vote up
def create_mock_datakey():
    '''
    Mock encryption meant to be used for testing or development. Returns a
    generated data key, but the encrypted version of the key is simply the
    unencrypted version. If this is called for anything other than testing
    or development purposes, it will cause unencrypted keys to be stored along
    with the encrypted content, rending the encryption worthless.
    '''
    key = Fernet.generate_key()
    return {'ciphertext': key,
            'plaintext': key} 
Example #17
Source File: aes_stream_encoder.py    From PyIris-backdoor with Mozilla Public License 2.0 5 votes vote down vote up
def main(option, filepath=None):
    if not filepath:
        filepath = config.scout_values['Path'][0]
    if option == 'encode':
        try:    
            imported_modules = ['from cryptography.fernet import Fernet']
            with open(filepath, 'r') as f:
                data = f.read().replace(';', '\n')
            source = data.split('\n')
            for i in source:
                if 'import' in i and i != 'from cryptography.fernet import Fernet':
                    imported_modules.append(i)
            key = Fernet.generate_key()
            print('   ' + config.inf + 'Fernet generated cipher key for AES symmetrical encryption : ' + key.decode())
            cipher_suite = Fernet(key)
            encoded_source = cipher_suite.encrypt(('\n'.join(source).encode()))
            obfuscated = ';'.join(
                imported_modules) + ';cipher_suite = Fernet(b"' + key.decode() + '");exec(cipher_suite.decrypt(b"' + encoded_source.decode() + '"))'
            with open(filepath, 'w') as f:
                f.write(obfuscated)
                print('   ' + config.inf + 'Encoded scout and overwrote raw file with AES encrypted file contents using Fernet')
        except SyntaxError:
            print('   ' + config.neg + 'Could not encode scout')
    elif option == 'info':
        print('\nName             : AES Encoder' \
              '\nRequired Modules : cryptography' \
              '\nDescription      : Uses Fernet to AES encrypt the scout\n') 
Example #18
Source File: config.py    From predixpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_crypt_key(key_path):
    """
    Get the user's PredixPy manifest key.  Generate and store one if not
    yet generated.
    """
    key_path = os.path.expanduser(key_path)
    if os.path.exists(key_path):
        with open(key_path, 'r') as data:
            key = data.read()
    else:
        key = Fernet.generate_key()
        with open(key_path, 'w') as output:
            output.write(key)

    return key 
Example #19
Source File: model.py    From schedula with European Union Public License 1.1 5 votes vote down vote up
def generate_key():
    return Fernet.generate_key().decode() 
Example #20
Source File: streamer.py    From Flask-OpenCV-Streamer with GNU General Public License v3.0 5 votes vote down vote up
def generate_guest_password(self):
        """Generates and prints a random password on creation"""
        print("Generating Flask password")
        self.guest_password = str(Fernet.generate_key().decode())
        self.password_create_time = time.time()
        print(
            "Password for stream on Port: {} is\n    {}".format(
                self.port, self.guest_password
            )
        ) 
Example #21
Source File: test_fields.py    From django-fernet-fields with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_no_hkdf(self, settings):
        """Can set FERNET_USE_HKDF=False to avoid HKDF."""
        settings.FERNET_USE_HKDF = False
        k1 = Fernet.generate_key()
        settings.FERNET_KEYS = [k1]
        f = fields.EncryptedTextField()
        fernet = Fernet(k1)

        assert fernet.decrypt(f.fernet.encrypt(b'foo')) == b'foo' 
Example #22
Source File: crypt.py    From Awesome-Python-Scripts with MIT License 5 votes vote down vote up
def __init__(self):
        
        # can be generated Fernet.generate_key()
        # if generated, save it below
        self.key = b'oBa5LeeJt1r4BmNyJXb6FHd1U21GMshH9Pqu_J-HzNQ='
        self.fernet = Fernet(self.key) 
Example #23
Source File: utils.py    From django-blockchain with MIT License 5 votes vote down vote up
def generate_key():
        return Fernet.generate_key() 
Example #24
Source File: encrypted_cookies.py    From vibora with MIT License 5 votes vote down vote up
def set_up_sessions(current_app: Vibora):
    # In this example every time the server is restart a new key will be generated, which means
    # you lose all your sessions... you may want to have a fixed key instead.
    current_app.session_engine = EncryptedCookiesEngine(
        'cookie_name', secret_key=Fernet.generate_key()
    ) 
Example #25
Source File: test_integration.py    From autopush with Mozilla Public License 2.0 5 votes vote down vote up
def setUp(self):
        self.logs = _TestingLogObserver()
        begin_or_register(self.logs)
        self.addCleanup(globalLogPublisher.removeObserver, self.logs)

        crypto_key = Fernet.generate_key()
        ep_conf = AutopushConfig(
            crypto_key=crypto_key,
            **self.endpoint_kwargs()
        )
        conn_conf = AutopushConfig(
            crypto_key=crypto_key,
            **self.conn_kwargs()
        )

        # Endpoint HTTP router
        self.ep = ep = EndpointApplication(
            conf=ep_conf,
            resource=autopush.tests.boto_resource
        )
        ep.setup(rotate_tables=False)
        ep.startService()
        self.addCleanup(ep.stopService)

        # Websocket server
        self.conn = conn = ConnectionApplication(
            conf=conn_conf,
            resource=autopush.tests.boto_resource
        )
        conn.setup(rotate_tables=False)
        conn.startService()
        self.addCleanup(conn.stopService) 
Example #26
Source File: test_mgt.py    From yosai with Apache License 2.0 5 votes vote down vote up
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' 
Example #27
Source File: test_mgt.py    From yosai with Apache License 2.0 5 votes vote down vote up
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' 
Example #28
Source File: test_encrypted_cookie_storage.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def fernet_and_key():
    key = Fernet.generate_key()
    fernet = Fernet(key)
    return fernet, base64.urlsafe_b64decode(key) 
Example #29
Source File: crypto.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def generate_key():
    return Fernet.generate_key().decode("utf-8") 
Example #30
Source File: test_connection.py    From airflow with Apache License 2.0 5 votes vote down vote up
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')