aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--cryptography/fernet.py18
-rw-r--r--tests/test_fernet.py15
2 files changed, 15 insertions, 18 deletions
diff --git a/cryptography/fernet.py b/cryptography/fernet.py
index ae3a8bfa..1c6cb5dd 100644
--- a/cryptography/fernet.py
+++ b/cryptography/fernet.py
@@ -85,24 +85,22 @@ class Fernet(object):
).encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
+ basic_parts = (
+ b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
+ )
+
h = HMAC(self.signing_key, hashes.SHA256(), self.backend)
- h.update(b"\x80")
- h.update(struct.pack(">Q", current_time))
- h.update(iv)
- h.update(ciphertext)
+ h.update(basic_parts)
hmac = h.finalize()
- return base64.urlsafe_b64encode(
- b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext + hmac
- )
+ return base64.urlsafe_b64encode(basic_parts + hmac)
- def decrypt(self, data, ttl=None, current_time=None):
+ def decrypt(self, data, ttl=None):
if isinstance(data, six.text_type):
raise TypeError(
"Unicode-objects must be encoded before decryption"
)
- if current_time is None:
- current_time = int(time.time())
+ current_time = int(time.time())
try:
data = base64.urlsafe_b64decode(data)
diff --git a/tests/test_fernet.py b/tests/test_fernet.py
index 4080bd2d..c1caaa05 100644
--- a/tests/test_fernet.py
+++ b/tests/test_fernet.py
@@ -15,6 +15,7 @@ import base64
import calendar
import json
import os
+import time
import iso8601
@@ -51,22 +52,20 @@ class TestFernet(object):
@json_parametrize(
("secret", "now", "src", "ttl_sec", "token"), "verify.json",
)
- def test_verify(self, secret, now, src, ttl_sec, token):
+ def test_verify(self, secret, now, src, ttl_sec, token, monkeypatch):
f = Fernet(secret.encode("ascii"))
current_time = calendar.timegm(iso8601.parse_date(now).utctimetuple())
- payload = f.decrypt(
- token.encode("ascii"), ttl=ttl_sec, current_time=current_time
- )
+ monkeypatch.setattr(time, "time", lambda: current_time)
+ payload = f.decrypt(token.encode("ascii"), ttl=ttl_sec)
assert payload == src.encode("ascii")
@json_parametrize(("secret", "token", "now", "ttl_sec"), "invalid.json")
- def test_invalid(self, secret, token, now, ttl_sec):
+ def test_invalid(self, secret, token, now, ttl_sec, monkeypatch):
f = Fernet(secret.encode("ascii"))
current_time = calendar.timegm(iso8601.parse_date(now).utctimetuple())
+ monkeypatch.setattr(time, "time", lambda: current_time)
with pytest.raises(InvalidToken):
- f.decrypt(
- token.encode("ascii"), ttl=ttl_sec, current_time=current_time
- )
+ f.decrypt(token.encode("ascii"), ttl=ttl_sec)
def test_unicode(self):
f = Fernet(base64.b64encode(b"\x00" * 32))