Fernet (symmetric encryption) — Cryptography 44.0.0.dev1 documentation (2024)

Fernet guarantees that a message encrypted using it cannot bemanipulated or read without the key. Fernet is an implementation ofsymmetric (also known as “secret key”) authenticated cryptography. Fernet alsohas support for implementing key rotation via MultiFernet.

class cryptography.fernet.Fernet(key)[source]

This class provides both encryption and decryption facilities.

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

key (bytes or str) – A URL-safe base64-encoded 32-byte key. This must bekept secret. Anyone with this key is able to create andread messages.

classmethod generate_key()[source]

Generates a fresh fernet key. Keep this some place safe! If you lose ityou’ll no longer be able to decrypt messages; if anyone else gainsaccess to it, they’ll be able to decrypt all of your messages, andthey’ll also be able to forge arbitrary messages that will beauthenticated and decrypted.

encrypt(data)[source]

Encrypts data passed. The result of this encryption is known as a“Fernet token” and has strong privacy and authenticity guarantees.

Parameters:

data (bytes) – The message you would like to encrypt.

Returns bytes:

A secure message that cannot be read or alteredwithout the key. It is URL-safe base64-encoded. This isreferred to as a “Fernet token”.

Raises:

TypeError – This exception is raised if data is notbytes.

Note

The encrypted message contains the current time when it wasgenerated in plaintext, the time a message was created willtherefore be visible to a possible attacker.

encrypt_at_time(data, current_time)[source]

Added in version 3.0.

Encrypts data passed using explicitly passed current time. Seeencrypt() for the documentation of the data parameter, thereturn type and the exceptions raised.

The motivation behind this method is for the client code to be able totest token expiration. Since this method can be used in an insecuremanner one should make sure the correct time (int(time.time()))is passed as current_time outside testing.

Parameters:

current_time (int) – The current time.

Note

Similarly to encrypt() the encrypted message contains thetimestamp in plaintext, in this case the timestamp is the valueof the current_time parameter.

decrypt(token, ttl=None)[source]

Decrypts a Fernet token. If successfully decrypted you will receive theoriginal plaintext as the result, otherwise an exception will beraised. It is safe to use this data immediately as Fernet verifiesthat the data has not been tampered with prior to returning it.

Parameters:
  • token (bytes or str) – The Fernet token. This is the result ofcalling encrypt().

  • ttl (int) – Optionally, the number of seconds old a message may befor it to be valid. If the message is older thanttl seconds (from the time it was originallycreated) an exception will be raised. If ttl is notprovided (or is None), the age of the message isnot considered.

Returns bytes:

The original plaintext.

Raises:
  • cryptography.fernet.InvalidToken – If the token is in anyway invalid, this exceptionis raised. A token may beinvalid for a number ofreasons: it is older than thettl, it is malformed, orit does not have a validsignature.

  • TypeError – This exception is raised if token is notbytes or str.

decrypt_at_time(token, ttl, current_time)[source]

Added in version 3.0.

Decrypts a token using explicitly passed current time. Seedecrypt() for the documentation of the token and ttlparameters (ttl is required here), the return type and the exceptionsraised.

The motivation behind this method is for the client code to be able totest token expiration. Since this method can be used in an insecuremanner one should make sure the correct time (int(time.time()))is passed as current_time outside testing.

Parameters:

current_time (int) – The current time.

extract_timestamp(token)[source]

Added in version 2.3.

Returns the timestamp for the token. The caller can then decide ifthe token is about to expire and, for example, issue a new token.

Parameters:

token (bytes or str) – The Fernet token. This is the result ofcalling encrypt().

Returns int:

The Unix timestamp of the token.

Raises:
  • cryptography.fernet.InvalidToken – If the token’s signatureis invalid this exceptionis raised.

  • TypeError – This exception is raised if token is notbytes or str.

class cryptography.fernet.MultiFernet(fernets)[source]

Added in version 0.7.

This class implements key rotation for Fernet. It takes a list ofFernet instances and implements the same API with the exceptionof one additional method: MultiFernet.rotate():

>>> from cryptography.fernet import Fernet, MultiFernet>>> key1 = Fernet(Fernet.generate_key())>>> key2 = Fernet(Fernet.generate_key())>>> f = MultiFernet([key1, key2])>>> token = f.encrypt(b"Secret message!")>>> tokenb'...'>>> f.decrypt(token)b'Secret message!'

MultiFernet performs all encryption options using the first key in thelist provided. MultiFernet attempts to decrypt tokens with each key inturn. A cryptography.fernet.InvalidToken exception is raised ifthe correct key is not found in the list provided.

Key rotation makes it easy to replace old keys. You can add your new key atthe front of the list to start encrypting new messages, and remove old keysas they are no longer needed.

Token rotation as offered by MultiFernet.rotate() is a best practiceand manner of cryptographic hygiene designed to limit damage in the event ofan undetected event and to increase the difficulty of attacks. For example,if an employee who had access to your company’s fernet keys leaves, you’llwant to generate new fernet key, rotate all of the tokens currently deployedusing that new key, and then retire the old fernet key(s) to which theemployee had access.

rotate(msg)[source]

Added in version 2.2.

Rotates a token by re-encrypting it under the MultiFernetinstance’s primary key. This preserves the timestamp that was originallysaved with the token. If a token has successfully been rotated then therotated token will be returned. If rotation fails this will raise anexception.

>>> from cryptography.fernet import Fernet, MultiFernet>>> key1 = Fernet(Fernet.generate_key())>>> key2 = Fernet(Fernet.generate_key())>>> f = MultiFernet([key1, key2])>>> token = f.encrypt(b"Secret message!")>>> tokenb'...'>>> f.decrypt(token)b'Secret message!'>>> key3 = Fernet(Fernet.generate_key())>>> f2 = MultiFernet([key3, key1, key2])>>> rotated = f2.rotate(token)>>> f2.decrypt(rotated)b'Secret message!'
Parameters:

msg (bytes or str) – The token to re-encrypt.

Returns bytes:

A secure message that cannot be read or altered withoutthe key. This is URL-safe base64-encoded. This is referred to as a“Fernet token”.

Raises:
  • cryptography.fernet.InvalidToken – If a token is in anyway invalid this exception is raised.

  • TypeError – This exception is raised if the msg is notbytes or str.

class cryptography.fernet.InvalidToken[source]

See Fernet.decrypt() for more information.

Using passwords with Fernet

It is possible to use passwords with Fernet. To do this, you need to run thepassword through a key derivation function such asPBKDF2HMAC, bcrypt orScrypt.

>>> import base64>>> import os>>> from cryptography.fernet import Fernet>>> from cryptography.hazmat.primitives import hashes>>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC>>> password = b"password">>> salt = os.urandom(16)>>> kdf = PBKDF2HMAC(...  algorithm=hashes.SHA256(),...  length=32,...  salt=salt,...  iterations=480000,... )>>> key = base64.urlsafe_b64encode(kdf.derive(password))>>> f = Fernet(key)>>> token = f.encrypt(b"Secret message!")>>> tokenb'...'>>> f.decrypt(token)b'Secret message!'

In this scheme, the salt has to be stored in a retrievable location in orderto derive the same key from the password in the future.

The iteration count used should be adjusted to be as high as your server cantolerate. A good default is at least 480,000 iterations, which is what Djangorecommends as of December 2022.

Implementation

Fernet is built on top of a number of standard cryptographic primitives.Specifically it uses:

  • AES inCBC mode with a128-bit key for encryption; usingPKCS7 padding.

  • HMAC usingSHA256 for authentication.

  • Initialization vectors are generated using os.urandom().

For complete details consult the specification.

Limitations

Fernet is ideal for encrypting data that easily fits in memory. As a designfeature it does not expose unauthenticated bytes. This means that the completemessage contents must be available in memory, making Fernet generallyunsuitable for very large files at this time.

Fernet (symmetric encryption) — Cryptography 44.0.0.dev1 documentation (2024)
Top Articles
How To Get Emergency Student Loans at the Last Minute
How Google Chrome Plans to Block Hacking Attempts on Users' Network | - Times of India
Friskies Tender And Crunchy Recall
Live Basketball Scores Flashscore
Coverage of the introduction of the Water (Special Measures) Bill
9192464227
Craigslist Nj North Cars By Owner
Produzione mondiale di vino
Conduent Connect Feps Login
Obituary | Shawn Alexander | Russell Funeral Home, Inc.
OSRS Dryness Calculator - GEGCalculators
Pittsburgh Ultra Advanced Stain And Sealant Color Chart
Uhcs Patient Wallet
Spartanburg County Detention Facility - Annex I
Playgirl Magazine Cover Template Free
Curtains - Cheap Ready Made Curtains - Deconovo UK
Xxn Abbreviation List 2023
Sport-News heute – Schweiz & International | aktuell im Ticker
25Cc To Tbsp
Pekin Soccer Tournament
Officialmilarosee
CDL Rostermania 2023-2024 | News, Rumors & Every Confirmed Roster
Puss In Boots: The Last Wish Showtimes Near Cinépolis Vista
Heart Ring Worth Aj
Raz-Plus Literacy Essentials for PreK-6
Nesb Routing Number
Essence Healthcare Otc 2023 Catalog
Relaxed Sneak Animations
Stockton (California) – Travel guide at Wikivoyage
950 Sqft 2 BHK Villa for sale in Devi Redhills Sirinium | Red Hills, Chennai | Property ID - 15334774
Funky Town Gore Cartel Video
Rays Salary Cap
Bfri Forum
Mumu Player Pokemon Go
Kokomo Mugshots Busted
Everstart Jump Starter Manual Pdf
Puerto Rico Pictures and Facts
Craigslist In Myrtle Beach
Pensacola 311 Citizen Support | City of Pensacola, Florida Official Website
Labyrinth enchantment | PoE Wiki
What Does Code 898 Mean On Irs Transcript
Wayne State Academica Login
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Powerspec G512
2Nd Corinthians 5 Nlt
The Many Faces of the Craigslist Killer
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis
Kaamel Hasaun Wikipedia
Aurora Southeast Recreation Center And Fieldhouse Reviews
300 Fort Monroe Industrial Parkway Monroeville Oh
Southwind Village, Southend Village, Southwood Village, Supervision Of Alcohol Sales In Church And Village Halls
Craigs List Sarasota
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 5985

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.