blob: c95077bbf3b1b4cf687567c2c854c177a408ef04 [file] [log] [blame]
Alex Gaynor333fb102013-10-31 10:27:35 -07001Fernet
2======
3
4.. currentmodule:: cryptography.fernet
5
6.. testsetup::
7
Alex Gaynor43307c72013-11-21 21:50:14 -08008 import base64
Alex Gaynor333fb102013-10-31 10:27:35 -07009 import binascii
Alex Gaynor43307c72013-11-21 21:50:14 -080010 key = base64.urlsafe_b64encode(binascii.unhexlify(b"0" * 64))
Alex Gaynor333fb102013-10-31 10:27:35 -070011
12
13`Fernet`_ is an implementation of symmetric (also known as "secret key")
Alex Gaynor43307c72013-11-21 21:50:14 -080014authenticated cryptography. Fernet provides guarantees that a message encrypted
Alex Gaynor333fb102013-10-31 10:27:35 -070015using it cannot be manipulated or read without the key.
16
17.. class:: Fernet(key)
18
19 This class provides both encryption and decryption facilities.
20
21 .. doctest::
22
23 >>> from cryptography.fernet import Fernet
24 >>> f = Fernet(key)
25 >>> ciphertext = f.encrypt(b"my deep dark secret")
Alex Gaynorde475eb2013-10-31 10:35:19 -070026 >>> ciphertext
27 '...'
Alex Gaynor333fb102013-10-31 10:27:35 -070028 >>> f.decrypt(ciphertext)
29 'my deep dark secret'
30
Alex Gaynor7a121fc2013-11-22 10:18:30 -080031 :param bytes key: A URL-safe base64-encoded 32-byte key. This **must** be
32 kept secret. Anyone with this key is able to create and
33 read messages.
Alex Gaynor333fb102013-10-31 10:27:35 -070034
35
36 .. method:: encrypt(plaintext)
37
38 :param bytes plaintext: The message you would like to encrypt.
39 :returns bytes: A secure message which cannot be read or altered
Alex Gaynor7a121fc2013-11-22 10:18:30 -080040 without the key. It is URL-safe base64-encoded.
Alex Gaynor333fb102013-10-31 10:27:35 -070041
42 .. method:: decrypt(ciphertext, ttl=None)
43
44 :param bytes ciphertext: An encrypted message.
45 :param int ttl: Optionally, the number of seconds old a message may be
46 for it to be valid. If the message is older than
47 ``ttl`` seconds (from the time it was originally
Alex Gaynor13e0d542013-10-31 10:38:04 -070048 created) an exception will be raised. If ``ttl`` is not
49 provided (or is ``None``), the age of the message is
50 not considered.
Alex Gaynor333fb102013-10-31 10:27:35 -070051 :returns bytes: The original plaintext.
Alex Gaynor7a121fc2013-11-22 10:18:30 -080052 :raises InvalidToken: If the ``ciphertext`` is in any way invalid, this
53 exception is raised. A ciphertext may be invalid
54 for a number of reasons: it is older than the
55 ``ttl``, it is malformed, or it does not have a
56 valid signature.
57
58
59.. class:: InvalidToken
60
61 See :meth:`Fernet.decrypt` for more information.
Alex Gaynor333fb102013-10-31 10:27:35 -070062
63
64.. _`Fernet`: https://github.com/fernet/spec/