aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDavid Reid <dreid@dreid.org>2013-11-12 16:41:13 -0800
committerDavid Reid <dreid@dreid.org>2013-11-12 16:41:13 -0800
commit152d6bec8c34c52d75373dd8d99a3d159baa9550 (patch)
treec8bee3c932c0173f6fa025ac0eb5e990fdf8cc51
parent4faa094526f49c83a75d21a6e796546d4d539c6c (diff)
downloadcryptography-152d6bec8c34c52d75373dd8d99a3d159baa9550.tar.gz
cryptography-152d6bec8c34c52d75373dd8d99a3d159baa9550.tar.bz2
cryptography-152d6bec8c34c52d75373dd8d99a3d159baa9550.zip
raise an exception if you try to use a HashContext after finalize is called.
-rw-r--r--cryptography/exceptions.py4
-rw-r--r--cryptography/hazmat/primitives/hashes.py9
-rw-r--r--tests/hazmat/primitives/test_hashes.py11
3 files changed, 23 insertions, 1 deletions
diff --git a/cryptography/exceptions.py b/cryptography/exceptions.py
index 391bed82..c2e71493 100644
--- a/cryptography/exceptions.py
+++ b/cryptography/exceptions.py
@@ -14,3 +14,7 @@
class UnsupportedAlgorithm(Exception):
pass
+
+
+class AlreadyFinalized(Exception):
+ pass
diff --git a/cryptography/hazmat/primitives/hashes.py b/cryptography/hazmat/primitives/hashes.py
index 6ae622cd..f85d36a0 100644
--- a/cryptography/hazmat/primitives/hashes.py
+++ b/cryptography/hazmat/primitives/hashes.py
@@ -15,6 +15,7 @@ from __future__ import absolute_import, division, print_function
import six
+from cryptography import exceptions
from cryptography.hazmat.primitives import interfaces
@@ -37,17 +38,23 @@ class Hash(object):
self._ctx = ctx
def update(self, data):
+ if self._ctx is None:
+ raise exceptions.AlreadyFinalized()
if isinstance(data, six.text_type):
raise TypeError("Unicode-objects must be encoded before hashing")
self._ctx.update(data)
def copy(self):
+ if self._ctx is None:
+ raise exceptions.AlreadyFinalized()
return Hash(
self.algorithm, backend=self._backend, ctx=self._ctx.copy()
)
def finalize(self):
- return self._ctx.finalize()
+ digest = self._ctx.finalize()
+ self._ctx = None
+ return digest
@interfaces.register(interfaces.HashAlgorithm)
diff --git a/tests/hazmat/primitives/test_hashes.py b/tests/hazmat/primitives/test_hashes.py
index 6cdb0a07..a5c440b8 100644
--- a/tests/hazmat/primitives/test_hashes.py
+++ b/tests/hazmat/primitives/test_hashes.py
@@ -19,6 +19,7 @@ import pytest
import six
+from cryptography import exceptions
from cryptography.hazmat.bindings import _default_backend
from cryptography.hazmat.primitives import hashes
@@ -51,6 +52,16 @@ class TestHashContext(object):
with pytest.raises(TypeError):
hashes.Hash(hashes.SHA1)
+ def test_raises_after_finalize(self):
+ h = hashes.Hash(hashes.SHA1())
+ h.finalize()
+
+ with pytest.raises(exceptions.AlreadyFinalized):
+ h.update(b"foo")
+
+ with pytest.raises(exceptions.AlreadyFinalized):
+ h.copy()
+
class TestSHA1(object):
test_SHA1 = generate_base_hash_test(