Skip to content

Commit 1c0d332

Browse files
committed
fix: use hmac.compare_digest in verify method
1 parent 65bcc53 commit 1c0d332

File tree

3 files changed

+10
-5
lines changed

3 files changed

+10
-5
lines changed

src/otpauth/core.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import base64
2+
from urllib.parse import quote
23
from abc import ABCMeta, abstractmethod
34

45

@@ -34,6 +35,10 @@ def from_b32encode(cls, secret: bytes):
3435
obj._b32_secret = b32_secret
3536
return obj
3637

38+
def _get_base_uri(self, label: str, issuer: str) -> str:
39+
label = quote(label, safe="/@")
40+
return f"otpauth://hotp/{label}?secret={self.b32_secret}&issuer={issuer}&algorithm={self.algorithm}&digits={self.digit}"
41+
3742
@abstractmethod
3843
def generate(self, *args, **kwargs) -> int:
3944
...

src/otpauth/rfc4226.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def verify(self, code: int, counter: int) -> bool:
2222
"""
2323
if len(str(code)) > self.digit:
2424
return False
25-
return hashlib.compare_digest(bytes(self.generate(counter)), bytes(code))
25+
return hmac.compare_digest(bytes(self.generate(counter)), bytes(code))
2626

2727
def to_uri(self, label: str, issuer: str, counter: int) -> str:
2828
"""Generate the otpauth protocal string for HOTP.
@@ -31,7 +31,7 @@ def to_uri(self, label: str, issuer: str, counter: int) -> str:
3131
:param issuer: The company, the organization or something else.
3232
:param counter: Initial counter of the HOTP algorithm.
3333
"""
34-
uri = f"otpauth://hotp/{label}?secret={self.b32_secret}&issuer={issuer}&algorithm={self.algorithm}&digits={self.digit}"
34+
uri = self._get_base_uri(label, issuer)
3535
return uri + f"&counter={counter}"
3636

3737

src/otpauth/rfc6238.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import time
2-
import hashlib
2+
import hmac
33
from .core import OTP
44
from .rfc4226 import generate_hotp
55

@@ -26,15 +26,15 @@ def verify(self, code: int, timestamp: int = None) -> bool:
2626
"""
2727
if len(str(code)) > self.digit:
2828
return False
29-
return hashlib.compare_digest(bytes(self.generate(timestamp)), bytes(code))
29+
return hmac.compare_digest(bytes(self.generate(timestamp)), bytes(code))
3030

3131
def to_uri(self, label: str, issuer: str) -> str:
3232
"""Generate the otpauth protocal string for TOTP.
3333
3434
:param label: Label of the identifier.
3535
:param issuer: The company, the organization or something else.
3636
"""
37-
uri = f"otpauth://totp/{label}?secret={self.b32_secret}&issuer={issuer}&algorithm={self.algorithm}&digits={self.digit}"
37+
uri = self._get_base_uri(label, issuer)
3838
return uri + f"&period={self.period}"
3939

4040

0 commit comments

Comments
 (0)