Skip to content

Commit

Permalink
fix: use hmac.compare_digest in verify method
Browse files Browse the repository at this point in the history
  • Loading branch information
lepture committed Mar 23, 2023
1 parent 65bcc53 commit 1c0d332
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
5 changes: 5 additions & 0 deletions src/otpauth/core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
from urllib.parse import quote
from abc import ABCMeta, abstractmethod


Expand Down Expand Up @@ -34,6 +35,10 @@ def from_b32encode(cls, secret: bytes):
obj._b32_secret = b32_secret
return obj

def _get_base_uri(self, label: str, issuer: str) -> str:
label = quote(label, safe="/@")
return f"otpauth://hotp/{label}?secret={self.b32_secret}&issuer={issuer}&algorithm={self.algorithm}&digits={self.digit}"

@abstractmethod
def generate(self, *args, **kwargs) -> int:
...
Expand Down
4 changes: 2 additions & 2 deletions src/otpauth/rfc4226.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def verify(self, code: int, counter: int) -> bool:
"""
if len(str(code)) > self.digit:
return False
return hashlib.compare_digest(bytes(self.generate(counter)), bytes(code))
return hmac.compare_digest(bytes(self.generate(counter)), bytes(code))

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


Expand Down
6 changes: 3 additions & 3 deletions src/otpauth/rfc6238.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import time
import hashlib
import hmac
from .core import OTP
from .rfc4226 import generate_hotp

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

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


Expand Down

0 comments on commit 1c0d332

Please # to comment.