From 36ad98fd5e4b7358dc2aa903b6d51569bf19c5f8 Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Sat, 12 May 2018 11:57:32 -0400 Subject: Add support for extracting timestamp from a Fernet token (#4229) * Add API for retrieving the seconds-to-expiry for the token, given a TTL. * Process PR feedback: * Do compute the TTL, but just the age of the token. The caller can decided what to do next. * Factored out the HMAC signature verification to a separate function. * Fixed a copy&paste mistake in the test cases * Tests cleanup. * `struct` no longer needed * Document `def age()` * typo in `age()` documentation * token, not data * remove test for TTL expiry that is already covered by the parameterized `test_invalid()`. * let's call this extract_timestamp and just return timestamp * review comments * it's UNIX I know this --- src/cryptography/fernet.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/cryptography/fernet.py b/src/cryptography/fernet.py index 1f33a12d..ac2dd0b6 100644 --- a/src/cryptography/fernet.py +++ b/src/cryptography/fernet.py @@ -74,6 +74,12 @@ class Fernet(object): timestamp, data = Fernet._get_unverified_token_data(token) return self._decrypt_data(data, timestamp, ttl) + def extract_timestamp(self, token): + timestamp, data = Fernet._get_unverified_token_data(token) + # Verify the token was not tampered with. + self._verify_signature(data) + return timestamp + @staticmethod def _get_unverified_token_data(token): if not isinstance(token, bytes): @@ -93,6 +99,14 @@ class Fernet(object): raise InvalidToken return timestamp, data + def _verify_signature(self, data): + h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) + h.update(data[:-32]) + try: + h.verify(data[-32:]) + except InvalidSignature: + raise InvalidToken + def _decrypt_data(self, data, timestamp, ttl): current_time = int(time.time()) if ttl is not None: @@ -102,12 +116,7 @@ class Fernet(object): if current_time + _MAX_CLOCK_SKEW < timestamp: raise InvalidToken - h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) - h.update(data[:-32]) - try: - h.verify(data[-32:]) - except InvalidSignature: - raise InvalidToken + self._verify_signature(data) iv = data[9:25] ciphertext = data[25:-32] -- cgit v1.2.3