diff options
author | Paul Kehrer <paul.l.kehrer@gmail.com> | 2018-05-12 11:57:32 -0400 |
---|---|---|
committer | Alex Gaynor <alex.gaynor@gmail.com> | 2018-05-12 11:57:32 -0400 |
commit | 36ad98fd5e4b7358dc2aa903b6d51569bf19c5f8 (patch) | |
tree | b176b10478a5cfe302ca3ed7193fda5964c16d8b /src | |
parent | 33ae3cea990b307eafaa5f52232eba8315fd05fe (diff) | |
download | cryptography-36ad98fd5e4b7358dc2aa903b6d51569bf19c5f8.tar.gz cryptography-36ad98fd5e4b7358dc2aa903b6d51569bf19c5f8.tar.bz2 cryptography-36ad98fd5e4b7358dc2aa903b6d51569bf19c5f8.zip |
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
Diffstat (limited to 'src')
-rw-r--r-- | src/cryptography/fernet.py | 21 |
1 files changed, 15 insertions, 6 deletions
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] |