Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fernet.py 6.7KB

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