fernet.rst 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. Fernet (symmetric encryption)
  2. =============================
  3. .. currentmodule:: cryptography.fernet
  4. Fernet guarantees that a message encrypted using it cannot be
  5. manipulated or read without the key. `Fernet`_ is an implementation of
  6. symmetric (also known as "secret key") authenticated cryptography. Fernet also
  7. has support for implementing key rotation via :class:`MultiFernet`.
  8. .. class:: Fernet(key)
  9. This class provides both encryption and decryption facilities.
  10. .. doctest::
  11. >>> from cryptography.fernet import Fernet
  12. >>> key = Fernet.generate_key()
  13. >>> f = Fernet(key)
  14. >>> token = f.encrypt(b"my deep dark secret")
  15. >>> token
  16. '...'
  17. >>> f.decrypt(token)
  18. 'my deep dark secret'
  19. :param bytes key: A URL-safe base64-encoded 32-byte key. This **must** be
  20. kept secret. Anyone with this key is able to create and
  21. read messages.
  22. .. classmethod:: generate_key()
  23. Generates a fresh fernet key. Keep this some place safe! If you lose it
  24. you'll no longer be able to decrypt messages; if anyone else gains
  25. access to it, they'll be able to decrypt all of your messages, and
  26. they'll also be able forge arbitrary messages that will be
  27. authenticated and decrypted.
  28. .. method:: encrypt(data)
  29. Encrypts data passed. The result of this encryption is known as a
  30. "Fernet token" and has strong privacy and authenticity guarantees.
  31. :param bytes data: The message you would like to encrypt.
  32. :returns bytes: A secure message that cannot be read or altered
  33. without the key. It is URL-safe base64-encoded. This is
  34. referred to as a "Fernet token".
  35. :raises TypeError: This exception is raised if ``data`` is not
  36. ``bytes``.
  37. .. note::
  38. The encrypted message contains the current time when it was
  39. generated in *plaintext*, the time a message was created will
  40. therefore be visible to a possible attacker.
  41. .. method:: decrypt(token, ttl=None)
  42. Decrypts a Fernet token. If successfully decrypted you will receive the
  43. original plaintext as the result, otherwise an exception will be
  44. raised. It is safe to use this data immediately as Fernet verifies
  45. that the data has not been tampered with prior to returning it.
  46. :param bytes token: The Fernet token. This is the result of calling
  47. :meth:`encrypt`.
  48. :param int ttl: Optionally, the number of seconds old a message may be
  49. for it to be valid. If the message is older than
  50. ``ttl`` seconds (from the time it was originally
  51. created) an exception will be raised. If ``ttl`` is not
  52. provided (or is ``None``), the age of the message is
  53. not considered.
  54. :returns bytes: The original plaintext.
  55. :raises cryptography.fernet.InvalidToken: If the ``token`` is in any
  56. way invalid, this exception
  57. is raised. A token may be
  58. invalid for a number of
  59. reasons: it is older than the
  60. ``ttl``, it is malformed, or
  61. it does not have a valid
  62. signature.
  63. :raises TypeError: This exception is raised if ``token`` is not
  64. ``bytes``.
  65. .. class:: MultiFernet(fernets)
  66. .. versionadded:: 0.7
  67. This class implements key rotation for Fernet. It takes a ``list`` of
  68. :class:`Fernet` instances, and implements the same API:
  69. .. doctest::
  70. >>> from cryptography.fernet import Fernet, MultiFernet
  71. >>> key1 = Fernet(Fernet.generate_key())
  72. >>> key2 = Fernet(Fernet.generate_key())
  73. >>> f = MultiFernet([key1, key2])
  74. >>> token = f.encrypt(b"Secret message!")
  75. >>> token
  76. '...'
  77. >>> f.decrypt(token)
  78. 'Secret message!'
  79. MultiFernet performs all encryption options using the *first* key in the
  80. ``list`` provided. MultiFernet attempts to decrypt tokens with each key in
  81. turn. A :class:`cryptography.fernet.InvalidToken` exception is raised if
  82. the correct key is not found in the ``list`` provided.
  83. Key rotation makes it easy to replace old keys. You can add your new key at
  84. the front of the list to start encrypting new messages, and remove old keys
  85. as they are no longer needed.
  86. .. class:: InvalidToken
  87. See :meth:`Fernet.decrypt` for more information.
  88. Using passwords with Fernet
  89. ---------------------------
  90. It is possible to use passwords with Fernet. To do this, you need to run the
  91. password through a key derivation function such as
  92. :class:`~cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC`, bcrypt or
  93. :class:`~cryptography.hazmat.primitives.kdf.scrypt.Scrypt`.
  94. .. doctest::
  95. >>> import base64
  96. >>> import os
  97. >>> from cryptography.fernet import Fernet
  98. >>> from cryptography.hazmat.backends import default_backend
  99. >>> from cryptography.hazmat.primitives import hashes
  100. >>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
  101. >>> password = b"password"
  102. >>> salt = os.urandom(16)
  103. >>> kdf = PBKDF2HMAC(
  104. ... algorithm=hashes.SHA256(),
  105. ... length=32,
  106. ... salt=salt,
  107. ... iterations=100000,
  108. ... backend=default_backend()
  109. ... )
  110. >>> key = base64.urlsafe_b64encode(kdf.derive(password))
  111. >>> f = Fernet(key)
  112. >>> token = f.encrypt(b"Secret message!")
  113. >>> token
  114. '...'
  115. >>> f.decrypt(token)
  116. 'Secret message!'
  117. In this scheme, the salt has to be stored in a retrievable location in order
  118. to derive the same key from the password in the future.
  119. The iteration count used should be adjusted to be as high as your server can
  120. tolerate. A good default is at least 100,000 iterations which is what Django
  121. recommended in 2014.
  122. Implementation
  123. --------------
  124. Fernet is built on top of a number of standard cryptographic primitives.
  125. Specifically it uses:
  126. * :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` in
  127. :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode with a
  128. 128-bit key for encryption; using
  129. :class:`~cryptography.hazmat.primitives.padding.PKCS7` padding.
  130. * :class:`~cryptography.hazmat.primitives.hmac.HMAC` using
  131. :class:`~cryptography.hazmat.primitives.hashes.SHA256` for authentication.
  132. * Initialization vectors are generated using ``os.urandom()``.
  133. For complete details consult the `specification`_.
  134. Limitations
  135. -----------
  136. Fernet is ideal for encrypting data that easily fits in memory. As a design
  137. feature it does not expose unauthenticated bytes. Unfortunately, this makes it
  138. generally unsuitable for very large files at this time.
  139. .. _`Fernet`: https://github.com/fernet/spec/
  140. .. _`specification`: https://github.com/fernet/spec/blob/master/Spec.md