Skip to content

Commit

Permalink
Merge PR #454.
Browse files Browse the repository at this point in the history
  • Loading branch information
dainnilsson committed Nov 10, 2021
2 parents e26570e + 835938d commit 0f29036
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
11 changes: 8 additions & 3 deletions ykman/cli/otp.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@
UpdateConfiguration,
)
from yubikit.core import TRANSPORT, CommandError
from yubikit.core.otp import modhex_encode, modhex_decode, OtpConnection
from yubikit.core.otp import (
MODHEX_ALPHABET,
modhex_encode,
modhex_decode,
OtpConnection,
)

from .util import (
ykman_group,
Expand Down Expand Up @@ -381,8 +386,8 @@ def yubiotp(

try:
public_id = modhex_decode(public_id)
except KeyError:
ctx.fail("Invalid public ID, must be modhex.")
except ValueError:
ctx.fail(f"Invalid public ID, must be modhex ({MODHEX_ALPHABET}).")

if not private_id:
if generate_private_id:
Expand Down
10 changes: 5 additions & 5 deletions yubikit/core/otp.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
logger = logging.getLogger(__name__)


MODHEX_ALPHABET = "cbdefghijklnrtuv"


class CommandRejectedError(CommandError):
"""The issues command was rejected by the YubiKey"""

Expand Down Expand Up @@ -70,18 +73,15 @@ def check_crc(data: bytes) -> bool:
return calculate_crc(data) == CRC_OK_RESIDUAL


_MODHEX = "cbdefghijklnrtuv"


def modhex_encode(data: bytes) -> str:
"""Encode a bytes-like object using Modhex (modified hexadecimal) encoding."""
return "".join(_MODHEX[b >> 4] + _MODHEX[b & 0xF] for b in data)
return "".join(MODHEX_ALPHABET[b >> 4] + MODHEX_ALPHABET[b & 0xF] for b in data)


def modhex_decode(string: str) -> bytes:
"""Decode the Modhex (modified hexadecimal) string."""
return bytes(
_MODHEX.index(string[i]) << 4 | _MODHEX.index(string[i + 1])
MODHEX_ALPHABET.index(string[i]) << 4 | MODHEX_ALPHABET.index(string[i + 1])
for i in range(0, len(string), 2)
)

Expand Down

0 comments on commit 0f29036

Please sign in to comment.