import numpy as np from dataclasses import dataclass from typing import ClassVar from src.models import KeypadSize @dataclass class CustomerCipher: property_key: np.ndarray position_key: np.ndarray keypad_size: KeypadSize MAX_KEYS: ClassVar[int] = 256 MAX_PROP_PER_KEY: ClassVar[int] = 256 def __post_init__(self): if self.keypad_size.is_dispersable: raise ValueError("number of keys must be less than the number of " "properties per key to be dispersion resistant") @classmethod def create(cls, keypad_size: KeypadSize) -> 'CustomerCipher': if keypad_size.numb_of_keys > cls.MAX_KEYS or keypad_size.props_per_key > cls.MAX_PROP_PER_KEY: raise ValueError(f"Keys and properties per key must not exceed {cls.MAX_KEYS}") # Using numpy to generate non-repeating random integers prop_key = np.random.choice(2 ** 16, size=keypad_size.total_props, replace=False) pos_key = np.random.choice(2 ** 16, size=keypad_size.props_per_key, replace=False) return cls( property_key=prop_key, position_key=pos_key, keypad_size=keypad_size, ) def renew(self): self.property_key = np.random.choice(2 ** 16, size=self.keypad_size.total_props, replace=False) self.position_key = np.random.choice(2 ** 16, size=self.keypad_size.props_per_key, replace=False) def get_props_position_vals(self, props: np.ndarray | list[int]) -> np.ndarray: if not all([prop in self.property_key for prop in props]): raise ValueError("Property values must be within valid range") pos_vals = [self._get_prop_position_val(prop) for prop in props] return np.array(pos_vals) def _get_prop_position_val(self, prop: int) -> int: assert prop in self.property_key prop_idx = np.where(self.property_key == prop)[0][0] pos_idx = prop_idx % self.keypad_size.props_per_key return int(self.position_key[pos_idx]) def get_position_index(self, pos_val: int) -> int: if not np.isin(pos_val, self.position_key): raise ValueError(f"Position value {pos_val} not found in customer cipher position_key") return int(np.where(self.position_key == pos_val)[0][0]) def get_passcode_position_indices_padded(self, passcode_indices: list[int], max_nkode_len: int) -> list[int]: if not all(0 <= idx < self.keypad_size.total_props for idx in passcode_indices): raise ValueError("invalid passcode index") pos_indices = [idx % self.keypad_size.props_per_key for idx in passcode_indices] pad_len = max_nkode_len - len(passcode_indices) pad = np.random.choice(self.keypad_size.props_per_key, pad_len, replace=True) return pos_indices + pad.tolist()