blob: 241bf1ea974d694189c23235670fe54f04dd89ce [file] [log] [blame]
Alex Gaynor333fb102013-10-31 10:27:35 -07001Fernet
2======
3
4.. currentmodule:: cryptography.fernet
5
Alex Gaynor333fb102013-10-31 10:27:35 -07006`Fernet`_ is an implementation of symmetric (also known as "secret key")
Alex Gaynor43307c72013-11-21 21:50:14 -08007authenticated cryptography. Fernet provides guarantees that a message encrypted
Alex Gaynor333fb102013-10-31 10:27:35 -07008using it cannot be manipulated or read without the key.
9
10.. class:: Fernet(key)
11
12 This class provides both encryption and decryption facilities.
13
14 .. doctest::
15
16 >>> from cryptography.fernet import Fernet
Alex Gaynor36597b42013-11-22 10:25:13 -080017 >>> key = Fernet.generate_key()
Alex Gaynor333fb102013-10-31 10:27:35 -070018 >>> f = Fernet(key)
19 >>> ciphertext = f.encrypt(b"my deep dark secret")
Alex Gaynorde475eb2013-10-31 10:35:19 -070020 >>> ciphertext
21 '...'
Alex Gaynor333fb102013-10-31 10:27:35 -070022 >>> f.decrypt(ciphertext)
23 'my deep dark secret'
24
Alex Gaynor7a121fc2013-11-22 10:18:30 -080025 :param bytes key: A URL-safe base64-encoded 32-byte key. This **must** be
26 kept secret. Anyone with this key is able to create and
27 read messages.
Alex Gaynor333fb102013-10-31 10:27:35 -070028
Alex Gaynor36597b42013-11-22 10:25:13 -080029 .. classmethod:: generate_key()
30
31 Generates a fresh fernet key. Keep this some place safe! If you lose it
32 you'll no longer be able to decrypt messages; if anyone else gains
33 access to it, they'll be able to decrypt all of your messages.
Alex Gaynor333fb102013-10-31 10:27:35 -070034
35 .. method:: encrypt(plaintext)
36
37 :param bytes plaintext: The message you would like to encrypt.
38 :returns bytes: A secure message which cannot be read or altered
Alex Gaynor7a121fc2013-11-22 10:18:30 -080039 without the key. It is URL-safe base64-encoded.
Alex Gaynor333fb102013-10-31 10:27:35 -070040
41 .. method:: decrypt(ciphertext, ttl=None)
42
43 :param bytes ciphertext: An encrypted message.
44 :param int ttl: Optionally, the number of seconds old a message may be
45 for it to be valid. If the message is older than
46 ``ttl`` seconds (from the time it was originally
Alex Gaynor13e0d542013-10-31 10:38:04 -070047 created) an exception will be raised. If ``ttl`` is not
48 provided (or is ``None``), the age of the message is
49 not considered.
Alex Gaynor333fb102013-10-31 10:27:35 -070050 :returns bytes: The original plaintext.
Alex Gaynor7a121fc2013-11-22 10:18:30 -080051 :raises InvalidToken: If the ``ciphertext`` is in any way invalid, this
52 exception is raised. A ciphertext may be invalid
53 for a number of reasons: it is older than the
54 ``ttl``, it is malformed, or it does not have a
55 valid signature.
56
57
58.. class:: InvalidToken
59
60 See :meth:`Fernet.decrypt` for more information.
Alex Gaynor333fb102013-10-31 10:27:35 -070061
62
63.. _`Fernet`: https://github.com/fernet/spec/