aboutsummaryrefslogtreecommitdiffstats
path: root/cryptography
diff options
context:
space:
mode:
authorAyrx <terrycwk1994@gmail.com>2014-02-13 12:27:56 +0800
committerAyrx <terrycwk1994@gmail.com>2014-02-21 11:13:35 +0800
commita7769110ef8f575105847f84cadf6bb5b9aa5fba (patch)
tree9dd292842a82903d1d2c42529250de41515a322c /cryptography
parentb2ee044298caf5772fb8774dc691add3afe8cdc1 (diff)
downloadcryptography-a7769110ef8f575105847f84cadf6bb5b9aa5fba.tar.gz
cryptography-a7769110ef8f575105847f84cadf6bb5b9aa5fba.tar.bz2
cryptography-a7769110ef8f575105847f84cadf6bb5b9aa5fba.zip
Updated according to code review feedback.
Diffstat (limited to 'cryptography')
-rw-r--r--cryptography/exceptions.py4
-rw-r--r--cryptography/hazmat/oath/hotp.py29
2 files changed, 23 insertions, 10 deletions
diff --git a/cryptography/exceptions.py b/cryptography/exceptions.py
index e2542a1f..f9849e2f 100644
--- a/cryptography/exceptions.py
+++ b/cryptography/exceptions.py
@@ -42,3 +42,7 @@ class InternalError(Exception):
class InvalidKey(Exception):
pass
+
+
+class InvalidToken(Exception):
+ pass
diff --git a/cryptography/hazmat/oath/hotp.py b/cryptography/hazmat/oath/hotp.py
index a04d0d49..a1f62746 100644
--- a/cryptography/hazmat/oath/hotp.py
+++ b/cryptography/hazmat/oath/hotp.py
@@ -12,28 +12,37 @@
# limitations under the License.
import struct
+from cryptography.exceptions import InvalidToken
import six
-from cryptography.hazmat.primitives import constant_time
+from cryptography.hazmat.primitives import constant_time, hmac
from cryptography.hazmat.primitives.hashes import SHA1
class HOTP(object):
- def __init__(self, secret, length, backend):
- self.secret = secret
- self.length = length
- self.backend = backend
+ def __init__(self, key, length, backend):
+
+ if len(key) < 16:
+ raise ValueError("Key length has to be at least 128 bits.")
+
+ if length < 6:
+ raise ValueError("Length of HOTP has to be at least 6.")
+
+ self._key = key
+ self._length = length
+ self._backend = backend
def generate(self, counter):
- sbit = self._dynamic_truncate(counter)
- foo = sbit % (10**self.length)
- return ('%s' % foo).zfill(self.length).encode()
+ truncated_value = self._dynamic_truncate(counter)
+ hotp = truncated_value % (10**self._length)
+ return "{0:0{1}}".format(hotp, self._length).encode()
def verify(self, hotp, counter):
- return constant_time.bytes_eq(self.generate(counter), hotp)
+ if not constant_time.bytes_eq(self.generate(counter), hotp):
+ raise InvalidToken("Supplied HOTP value does not match")
def _dynamic_truncate(self, counter):
- ctx = self.backend.create_hmac_ctx(self.secret, SHA1)
+ ctx = hmac.HMAC(self._key, SHA1(), self._backend)
ctx.update(struct.pack(">Q", counter))
hmac_value = ctx.finalize()