What does the f = Fernet(key) code represent when using the cryptography.Fernet library?

Asked

Viewed 554 times

3

The program consists of encrypting a message with a key and then decrypting.

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"my deep dark secret")
f.decrypt(token)

Can someone explain to me what the line f = Fernet(key) ago ?

1 answer

5

Without looking at the library documentation you can already say that what it does is instantiate an object - in Python, as a rule, names in Camelcase are class names - if you "call" a class, create an instance of it - and in this case, with the key passed.

This created object has the methods encrypt and decrypt that use the key used to create the object to translate bytes between encrypted and decrypted.

The interesting thing about Python projects is that it’s easy to look at your source code - or in the folder site-packages, where it is installed on its own computer, or directly in the repository where the source code is. In this case, I put "pythn Fernet github" on google, and the first link went straight to the file containing the class, within the Python "cryptography" project: https://github.com/pyca/cryptography/blob/master/src/cryptography/fernet.py

Inside the file we have the class statement - the method __init__ is well-taught:

class Fernet(object):
    def __init__(self, key, backend=None):
        if backend is None:
            backend = default_backend()

        key = base64.urlsafe_b64decode(key)
        if len(key) != 32:
            raise ValueError(
                "Fernet key must be 32 url-safe base64-encoded bytes."
            )

        self._signing_key = key[:16]
        self._encryption_key = key[16:]
        self._backend = backend

    ...

That is - it prepares the key for use, translating it from a representation in a usable form in Urls to a sequence of 32 bytes, and separates the first 16 as a signature key, and the last 16 as a croptographic key - in addition to selecting a backend - The rest of the class is code for "piloting" the algorithms at the lowest level, passing to the same keys, parts to be encrypted with standardized size, extra randomness data such as time and a salt - so that the end user only needs to worry about calling the methods encrypt and decrypt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.