fernet.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import base64
  5. import binascii
  6. import os
  7. import time
  8. import typing
  9. from cryptography import utils
  10. from cryptography.exceptions import InvalidSignature
  11. from cryptography.hazmat.primitives import hashes, padding
  12. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  13. from cryptography.hazmat.primitives.hmac import HMAC
  14. class InvalidToken(Exception):
  15. pass
  16. _MAX_CLOCK_SKEW = 60
  17. class Fernet:
  18. def __init__(
  19. self,
  20. key: typing.Union[bytes, str],
  21. backend: typing.Any = None,
  22. ):
  23. try:
  24. key = base64.urlsafe_b64decode(key)
  25. except binascii.Error as exc:
  26. raise ValueError(
  27. "Fernet key must be 32 url-safe base64-encoded bytes."
  28. ) from exc
  29. if len(key) != 32:
  30. raise ValueError(
  31. "Fernet key must be 32 url-safe base64-encoded bytes."
  32. )
  33. self._signing_key = key[:16]
  34. self._encryption_key = key[16:]
  35. @classmethod
  36. def generate_key(cls) -> bytes:
  37. return base64.urlsafe_b64encode(os.urandom(32))
  38. def encrypt(self, data: bytes) -> bytes:
  39. return self.encrypt_at_time(data, int(time.time()))
  40. def encrypt_at_time(self, data: bytes, current_time: int) -> bytes:
  41. iv = os.urandom(16)
  42. return self._encrypt_from_parts(data, current_time, iv)
  43. def _encrypt_from_parts(
  44. self, data: bytes, current_time: int, iv: bytes
  45. ) -> bytes:
  46. utils._check_bytes("data", data)
  47. padder = padding.PKCS7(algorithms.AES.block_size).padder()
  48. padded_data = padder.update(data) + padder.finalize()
  49. encryptor = Cipher(
  50. algorithms.AES(self._encryption_key),
  51. modes.CBC(iv),
  52. ).encryptor()
  53. ciphertext = encryptor.update(padded_data) + encryptor.finalize()
  54. basic_parts = (
  55. b"\x80"
  56. + current_time.to_bytes(length=8, byteorder="big")
  57. + iv
  58. + ciphertext
  59. )
  60. h = HMAC(self._signing_key, hashes.SHA256())
  61. h.update(basic_parts)
  62. hmac = h.finalize()
  63. return base64.urlsafe_b64encode(basic_parts + hmac)
  64. def decrypt(self, token: bytes, ttl: typing.Optional[int] = None) -> bytes:
  65. timestamp, data = Fernet._get_unverified_token_data(token)
  66. if ttl is None:
  67. time_info = None
  68. else:
  69. time_info = (ttl, int(time.time()))
  70. return self._decrypt_data(data, timestamp, time_info)
  71. def decrypt_at_time(
  72. self, token: bytes, ttl: int, current_time: int
  73. ) -> bytes:
  74. if ttl is None:
  75. raise ValueError(
  76. "decrypt_at_time() can only be used with a non-None ttl"
  77. )
  78. timestamp, data = Fernet._get_unverified_token_data(token)
  79. return self._decrypt_data(data, timestamp, (ttl, current_time))
  80. def extract_timestamp(self, token: bytes) -> int:
  81. timestamp, data = Fernet._get_unverified_token_data(token)
  82. # Verify the token was not tampered with.
  83. self._verify_signature(data)
  84. return timestamp
  85. @staticmethod
  86. def _get_unverified_token_data(token: bytes) -> typing.Tuple[int, bytes]:
  87. utils._check_bytes("token", token)
  88. try:
  89. data = base64.urlsafe_b64decode(token)
  90. except (TypeError, binascii.Error):
  91. raise InvalidToken
  92. if not data or data[0] != 0x80:
  93. raise InvalidToken
  94. if len(data) < 9:
  95. raise InvalidToken
  96. timestamp = int.from_bytes(data[1:9], byteorder="big")
  97. return timestamp, data
  98. def _verify_signature(self, data: bytes) -> None:
  99. h = HMAC(self._signing_key, hashes.SHA256())
  100. h.update(data[:-32])
  101. try:
  102. h.verify(data[-32:])
  103. except InvalidSignature:
  104. raise InvalidToken
  105. def _decrypt_data(
  106. self,
  107. data: bytes,
  108. timestamp: int,
  109. time_info: typing.Optional[typing.Tuple[int, int]],
  110. ) -> bytes:
  111. if time_info is not None:
  112. ttl, current_time = time_info
  113. if timestamp + ttl < current_time:
  114. raise InvalidToken
  115. if current_time + _MAX_CLOCK_SKEW < timestamp:
  116. raise InvalidToken
  117. self._verify_signature(data)
  118. iv = data[9:25]
  119. ciphertext = data[25:-32]
  120. decryptor = Cipher(
  121. algorithms.AES(self._encryption_key), modes.CBC(iv)
  122. ).decryptor()
  123. plaintext_padded = decryptor.update(ciphertext)
  124. try:
  125. plaintext_padded += decryptor.finalize()
  126. except ValueError:
  127. raise InvalidToken
  128. unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
  129. unpadded = unpadder.update(plaintext_padded)
  130. try:
  131. unpadded += unpadder.finalize()
  132. except ValueError:
  133. raise InvalidToken
  134. return unpadded
  135. class MultiFernet:
  136. def __init__(self, fernets: typing.Iterable[Fernet]):
  137. fernets = list(fernets)
  138. if not fernets:
  139. raise ValueError(
  140. "MultiFernet requires at least one Fernet instance"
  141. )
  142. self._fernets = fernets
  143. def encrypt(self, msg: bytes) -> bytes:
  144. return self.encrypt_at_time(msg, int(time.time()))
  145. def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes:
  146. return self._fernets[0].encrypt_at_time(msg, current_time)
  147. def rotate(self, msg: bytes) -> bytes:
  148. timestamp, data = Fernet._get_unverified_token_data(msg)
  149. for f in self._fernets:
  150. try:
  151. p = f._decrypt_data(data, timestamp, None)
  152. break
  153. except InvalidToken:
  154. pass
  155. else:
  156. raise InvalidToken
  157. iv = os.urandom(16)
  158. return self._fernets[0]._encrypt_from_parts(p, timestamp, iv)
  159. def decrypt(self, msg: bytes, ttl: typing.Optional[int] = None) -> bytes:
  160. for f in self._fernets:
  161. try:
  162. return f.decrypt(msg, ttl)
  163. except InvalidToken:
  164. pass
  165. raise InvalidToken
  166. def decrypt_at_time(
  167. self, msg: bytes, ttl: int, current_time: int
  168. ) -> bytes:
  169. for f in self._fernets:
  170. try:
  171. return f.decrypt_at_time(msg, ttl, current_time)
  172. except InvalidToken:
  173. pass
  174. raise InvalidToken