How to use the cryptography.fernet.Fernet function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aio-libs / aiohttp-session / tests / View on Github external
def fernet_and_key():
    key = Fernet.generate_key()
    fernet = Fernet(key)
    return fernet, base64.urlsafe_b64decode(key)
github pyca / cryptography / tests / View on Github external
def test_rotate(self, backend):
        f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend)
        f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend)

        mf1 = MultiFernet([f1])
        mf2 = MultiFernet([f2, f1])

        plaintext = b"abc"
        mf1_ciphertext = mf1.encrypt(plaintext)

        assert mf2.decrypt(mf1_ciphertext) == plaintext

        rotated = mf2.rotate(mf1_ciphertext)

        assert rotated != mf1_ciphertext
        assert mf2.decrypt(rotated) == plaintext

        with pytest.raises(InvalidToken):
github GoogleCloudPlatform / python-docs-samples / composer / tools / View on Github external
def reencrypt_variables_connections(old_fernet_key_str, new_fernet_key_str):
    old_fernet_key = fernet.Fernet(old_fernet_key_str.encode("utf-8"))
    new_fernet_key = fernet.Fernet(new_fernet_key_str.encode("utf-8"))
    db = connector.connect(
    variable_cursor = db.cursor()
    variable_cursor.execute("SELECT id, val, is_encrypted FROM variable")
    rows = variable_cursor.fetchall()
    for row in rows:
        id = row[0]
        val = row[1]
        is_encrypted = row[2]
        if is_encrypted:
            updated_val = new_fernet_key.encrypt(
github scottphilip / caller-lookup / CallerLookup / Utils / View on Github external
    h ="ripemd160")
    selected_account = account.upper() if account is not None else config.account.upper()
    if sys.version_info[0] >= 3:
        account_bytes = bytes(selected_account, CallerLookupKeys.UTF8)
        account_bytes = bytes(selected_account)
    key_path = join(key_dir, ".{0}".format(h.hexdigest()))
    system_key, system_key_str = __get_system_key(selected_account)
    log_debug(config, "SYSTEM_KEY", system_key_str, system_key)
    f = Fernet(key=system_key)
    if not isfile(key_path):
        if not isdir(key_dir):
        key = Fernet.generate_key()
        with open(key_path, "w") as file:
            encoded = b64encode(key)
        log_debug(config, "CRYPTO_KEY_CREATED", selected_account, key_path)
        if osname == 'nt':
                import ctypes
                ctypes.windll.kernel32.SetFileAttributesW(key_path, 0x02)
                ignore = True
    with open(key_path, "r") as file:
        if sys.version_info[0] >= 3:
            data = bytes(, encoding=CallerLookupKeys.UTF8)
            data = bytes(
github huseyinyilmaz / django-numerics / djangonumerics / View on Github external
def get_fernet():
    """Return a fernet object. Object is encoded on module level.

    Fernet object gets a long time to create so we are creating it only once
    per runtime.

    if _FERNET_KEY not in _CACHE:
            key = six.b(getattr(settings, 'DJANGO_NUMERICS_SECRET_KEY', ''))
            if not key:
                # same error if key is not hexedecimal.
                # that way 2 errors will be handled in same place.
                raise binascii.Error
            _CACHE[_FERNET_KEY] = Fernet(key)
        except binascii.Error:
            raise ImproperlyConfigured('DJANGO_NUMERICS_SECRET_KEY must be a '
                                       'hexedecimal value. Here is one that '
                                       'is randomly generated for you ;) '
    return _CACHE[_FERNET_KEY]
github resulto / pytracking / pytracking / View on Github external
def cache_encryption_key(self):
        if self.encryption_bytestring_key:
            self.encryption_key = Fernet(self.encryption_bytestring_key)
            self.encryption_key = None
github openstack / heat / heat / common / View on Github external
def cryptography_decrypt_v1(value, encryption_key=None):
    encryption_key = get_valid_encryption_key(encryption_key, fix_length=True)
    encoded_key = base64.b64encode(encryption_key.encode('utf-8'))
    sym = fernet.Fernet(encoded_key)
        return sym.decrypt(encodeutils.safe_encode(value))
    except fernet.InvalidToken:
        raise exception.InvalidEncryptionKey()
github vibora-io / vibora / vibora / sessions / View on Github external
def __init__(self, cookie_name='vibora', secret_key=None):
        self.cipher = Fernet(secret_key)
github TylerOlson / reddit2instagrambot / reddit2instagram / View on Github external
def decrypt_password(key, password_encrypted):
    cipher_suite = Fernet(key)
    password_decoded = cipher_suite.decrypt(password_encrypted)
    return password_decoded
github olcf / pkpass / libpkpass / View on Github external
command = ['pkcs15-crypt', '--decipher', '--raw', '--pkcs', '--input',]
        if card_slot is not None:
            command.extend(['--reader', str(card_slot)])
        command.extend(['--pin', '-'])
        proc = Popen(command, stdout=PIPE, stdin=PIPE, stderr=DEVNULL)
        stdout, _ = proc.communicate(input=passphrase.encode('UTF-8'))
            plaintext_derived_key = stdout
        except IndexError:
            raise DecryptionError(stdout)

    if proc.returncode != 0:
        raise DecryptionError(stdout)

    fern = Fernet(plaintext_derived_key)

    plaintext_string = fern.decrypt(handle_python_strings(ciphertext_string))
    return plaintext_string.decode("UTF-8")