numpy refactor

This commit is contained in:
2025-03-13 04:40:45 -05:00
parent facd9ee318
commit f6bf731186
12 changed files with 261 additions and 140 deletions

View File

@@ -1,9 +1,9 @@
from dataclasses import dataclass
from uuid import UUID
import numpy as np
from src.customer_cipher import CustomerCipher
from src.models import NKodePolicy
from src.user import User
from src.utils import xor_lists
@dataclass
class Customer:
@@ -12,7 +12,7 @@ class Customer:
cipher: CustomerCipher
users: dict[str, User]
# TODO: validate policy and keypad size don't conflict
# TODO: validate policy and keypad_list size don't conflict
def add_new_user(self, user: User):
if user.username in self.users:
@@ -56,8 +56,8 @@ class Customer:
new_attrs = self.cipher.prop_key
new_sets = self.cipher.set_key
attrs_xor = xor_lists(new_attrs, old_attrs)
set_xor = xor_lists(new_sets, old_sets)
attrs_xor = np.bitwise_xor(new_attrs, old_attrs)
set_xor = np.bitwise_xor(new_sets, old_sets)
for user in self.users.values():
user.renew_keys(set_xor, attrs_xor)
self.users[user.username] = user
@@ -66,7 +66,7 @@ class Customer:
def valid_new_nkode(self, passcode_attr_idx: list[int]) -> bool:
nkode_len = len(passcode_attr_idx)
passcode_set_values = [
self.cipher.get_prop_set_val(self.cipher.prop_key[attr_idx]) for attr_idx in passcode_attr_idx
self.cipher.get_prop_set_val(int(self.cipher.prop_key[attr_idx])) for attr_idx in passcode_attr_idx
]
distinct_sets = len(set(passcode_set_values))
distinct_attributes = len(set(passcode_attr_idx))

View File

@@ -1,13 +1,13 @@
import numpy as np
from dataclasses import dataclass
from typing import ClassVar
from src.models import KeypadSize
from src.utils import generate_random_nonrepeating_list
@dataclass
class CustomerCipher:
prop_key: list[int]
set_key: list[int]
prop_key: np.ndarray
set_key: np.ndarray
keypad_size: KeypadSize
MAX_KEYS: ClassVar[int] = 256
MAX_PROP_PER_KEY: ClassVar[int] = 256
@@ -24,23 +24,28 @@ class CustomerCipher:
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.numb_of_props, replace=False)
set_key = np.random.choice(2 ** 16, size=keypad_size.props_per_key, replace=False)
return cls(
prop_key=generate_random_nonrepeating_list(keypad_size.numb_of_props),
set_key=generate_random_nonrepeating_list(keypad_size.props_per_key),
prop_key=prop_key,
set_key=set_key,
keypad_size=keypad_size,
)
def renew(self):
self.prop_key = generate_random_nonrepeating_list(self.keypad_size.numb_of_props)
self.set_key = generate_random_nonrepeating_list(self.keypad_size.props_per_key)
self.prop_key = np.random.choice(2 ** 16, size=self.keypad_size.numb_of_props, replace=False)
self.set_key = np.random.choice(2 ** 16, size=self.keypad_size.props_per_key, replace=False)
def get_prop_set_val(self, prop: int) -> int:
assert (prop in self.prop_key)
prop_idx = self.prop_key.index(prop)
assert np.isin(prop, self.prop_key)
prop_idx = np.where(self.prop_key == prop)[0][0]
set_idx = prop_idx % self.keypad_size.props_per_key
return self.set_key[set_idx]
return int(self.set_key[set_idx])
def get_set_index(self, set_val: int) -> int:
if set_val not in self.set_key:
if not np.isin(set_val, self.set_key):
raise ValueError(f"Set value {set_val} not found in set values")
return self.set_key.index(set_val)
return int(np.where(self.set_key == set_val)[0][0])

View File

@@ -1,6 +1,5 @@
from dataclasses import dataclass, field
from uuid import UUID, uuid4
from typing import Dict, List, Tuple
from src.customer import Customer
from src.models import NKodePolicy, KeypadSize
from src.user import User
@@ -8,12 +7,13 @@ from src.user_cipher import UserCipher
from src.user_signup_session import UserSignupSession
from src.user_keypad import UserKeypad
from src.customer_cipher import CustomerCipher
import numpy as np
@dataclass
class NKodeAPI:
customers: Dict[UUID, Customer] = field(default_factory=dict)
signup_sessions: Dict[UUID, UserSignupSession] = field(default_factory=dict)
customers: dict[UUID, Customer] = field(default_factory=dict)
signup_sessions: dict[UUID, UserSignupSession] = field(default_factory=dict)
def create_new_customer(self, keypad_size: KeypadSize, nkode_policy: NKodePolicy) -> UUID:
new_customer = Customer(
@@ -25,7 +25,7 @@ class NKodeAPI:
self.customers[new_customer.customer_id] = new_customer
return new_customer.customer_id
def generate_signup_keypad(self, customer_id: UUID) -> Tuple[UUID, List[int]]:
def generate_signup_keypad(self, customer_id: UUID) -> tuple[UUID, np.ndarray]:
if customer_id not in self.customers.keys():
raise ValueError(f"Customer with ID '{customer_id}' does not exist")
customer = self.customers[customer_id]
@@ -45,9 +45,9 @@ class NKodeAPI:
self,
username: str,
customer_id: UUID,
key_selection: List[int],
key_selection: list[int],
session_id: UUID
) -> List[int]:
) -> np.ndarray:
if customer_id not in self.customers.keys():
raise ValueError(f"Customer ID {customer_id} not found")
customer = self.customers[customer_id]
@@ -62,7 +62,7 @@ class NKodeAPI:
self,
username: str,
customer_id: UUID,
confirm_key_entry: List[int],
confirm_key_entry: list[int],
session_id: UUID
) -> bool:
if session_id not in self.signup_sessions.keys():
@@ -90,7 +90,7 @@ class NKodeAPI:
del self.signup_sessions[session_id]
return True
def get_login_keypad(self, username: str, customer_id: UUID) -> List[int]:
def get_login_keypad(self, username: str, customer_id: UUID) -> np.ndarray:
if customer_id not in self.customers.keys():
raise ValueError("Customer ID not found")
customer = self.customers[customer_id]
@@ -98,9 +98,10 @@ class NKodeAPI:
raise ValueError("Username not found")
user = customer.users[username]
user.user_keypad.partial_keypad_shuffle()
# TODO: implement split_keypad_shuffle()
return user.user_keypad.keypad
def login(self, customer_id: UUID, username: str, key_selection: List[int]) -> bool:
def login(self, customer_id: UUID, username: str, key_selection: list[int]) -> bool:
if customer_id not in self.customers.keys():
raise ValueError("Customer ID not found")
customer = self.customers[customer_id]

View File

@@ -1,9 +1,11 @@
from dataclasses import dataclass, field
import numpy as np
from src.models import EncipheredNKode
from src.customer_cipher import CustomerCipher
from src.user_cipher import UserCipher
from src.user_keypad import UserKeypad
from src.utils import xor_lists
@dataclass
@@ -14,10 +16,10 @@ class User:
user_keypad: UserKeypad
renew: bool = field(default=False)
def renew_keys(self, set_xor: list[int], prop_xor: list[int]):
def renew_keys(self, set_xor: np.ndarray, prop_xor: np.ndarray):
self.renew = True
self.cipher.set_key = xor_lists(self.cipher.set_key, set_xor)
self.cipher.prop_key = xor_lists(self.cipher.prop_key, prop_xor)
self.cipher.set_key = np.bitwise_xor(self.cipher.set_key, set_xor)
self.cipher.prop_key = np.bitwise_xor(self.cipher.prop_key, prop_xor)
def refresh_passcode(self, passcode_attr_idx: list[int], customer_attributes: CustomerCipher):
self.cipher = UserCipher.create(

View File

@@ -18,7 +18,7 @@ class UserCipher:
max_nkode_len: int
@classmethod
def create(cls, keypad_size: KeypadSize, set_values: list[int], max_nkode_len: int) -> 'UserCipher':
def create(cls, keypad_size: KeypadSize, set_values: np.ndarray, max_nkode_len: int) -> 'UserCipher':
if len(set_values) != keypad_size.props_per_key:
raise ValueError("Invalid set values")
@@ -35,18 +35,15 @@ class UserCipher:
max_nkode_len=max_nkode_len
)
def pad_user_mask(self, user_mask: list[int], set_vals: list[int]) -> np.ndarray:
def pad_user_mask(self, user_mask: np.ndarray, set_vals: np.ndarray) -> np.ndarray:
if len(user_mask) >= self.max_nkode_len:
raise ValueError("User mask is too long")
user_mask_array = np.array(user_mask, dtype=np.uint16)
set_vals_array = np.array(set_vals, dtype=np.uint16)
# Create padding of random choices from set_vals
padding_size = self.max_nkode_len - len(user_mask)
padding_indices = np.random.choice(len(set_vals), padding_size)
padding = np.array([set_vals[i] for i in padding_indices], dtype=np.uint16)
# Concatenate original mask with padding
padded_user_mask = np.concatenate([user_mask_array, padding])
return padded_user_mask
@@ -121,7 +118,7 @@ class UserCipher:
mask = self.encode_base64_str(ciphered_mask)
return mask
def decipher_mask(self, mask: str, set_vals: list, passcode_len: int) -> list[int]:
def decipher_mask(self, mask: str, set_vals: np.ndarray, passcode_len: int) -> np.ndarray:
set_vals_array = np.array(set_vals, dtype=np.uint16)
decoded_mask = self.decode_base64_str(mask)
deciphered_mask = np.bitwise_xor(decoded_mask, self.mask_key)

View File

@@ -1,17 +1,17 @@
from dataclasses import dataclass
from secrets import choice
import numpy as np
from src.models import KeypadSize
from src.utils import list_to_matrix, secure_fisher_yates_shuffle, matrix_to_list, matrix_transpose
@dataclass
class UserKeypad:
keypad: list[int]
keypad: np.ndarray
keypad_size: KeypadSize
@classmethod
def create(cls, keypad_size: KeypadSize) -> 'UserKeypad':
keypad = UserKeypad(
keypad=list(range(keypad_size.numb_of_props)),
keypad=np.arange(keypad_size.numb_of_props),
keypad_size=keypad_size
)
keypad.random_keypad_shuffle()
@@ -22,71 +22,77 @@ class UserKeypad:
raise ValueError("Keypad size is dispersable")
self.random_keypad_shuffle()
keypad_matrix = self.keypad_matrix()
attr_set_view = matrix_transpose(keypad_matrix)
attr_set_view = secure_fisher_yates_shuffle(attr_set_view)
attr_set_view = keypad_matrix.T
#attr_set_view = secure_fisher_yates_shuffle(attr_set_view)
attr_set_view = np.random.permutation(attr_set_view)
attr_set_view = attr_set_view[:self.keypad_size.numb_of_keys]
keypad_matrix = matrix_transpose(attr_set_view)
keypad_matrix = attr_set_view.reshape(-1)#matrix_transpose(attr_set_view)
return UserKeypad(
keypad=matrix_to_list(keypad_matrix),
keypad=keypad_matrix.reshape(-1),#matrix_to_list(keypad_matrix),
keypad_size=KeypadSize(
numb_of_keys=self.keypad_size.numb_of_keys,
props_per_key=self.keypad_size.numb_of_keys
)
)
def keypad_matrix(self) -> list[list[int]]:
return list_to_matrix(self.keypad, self.keypad_size.props_per_key)
def keypad_matrix(self) -> np.ndarray:
return self.keypad.reshape(-1,self.keypad_size.props_per_key)
def random_keypad_shuffle(self):
rng = np.random.default_rng()
keypad_view = self.keypad_matrix()
keypad_view = secure_fisher_yates_shuffle(keypad_view)
set_view = matrix_transpose(keypad_view)
set_view = [secure_fisher_yates_shuffle(attr_set) for attr_set in set_view]
keypad_view = matrix_transpose(set_view)
self.keypad = matrix_to_list(keypad_view)
rng.shuffle(keypad_view, axis=0)
set_view = keypad_view.T
set_view = rng.permutation(set_view, axis=1)
keypad_view = set_view.T
self.keypad = keypad_view.reshape(-1)
def disperse_keypad(self):
if not self.keypad_size.is_dispersable:
raise ValueError("Keypad size is not dispersable")
user_keypad_matrix = list_to_matrix(self.keypad, self.keypad_size.props_per_key)
shuffled_keys = secure_fisher_yates_shuffle(user_keypad_matrix)
attr_rotation = secure_fisher_yates_shuffle(list(range(self.keypad_size.numb_of_keys)))[
:self.keypad_size.props_per_key]
rng = np.random.default_rng()
#user_keypad_matrix = list_to_matrix(self.keypad, self.keypad_size.props_per_key)
user_keypad_matrix = self.keypad_matrix()
#shuffled_keys = secure_fisher_yates_shuffle(user_keypad_matrix)
shuffled_keys = rng.permutation(user_keypad_matrix, axis=0)
#attr_rotation = secure_fisher_yates_shuffle(list(range(self.keypad_size.numb_of_keys)))[:self.keypad_size.props_per_key]
attr_rotation = rng.permutation(list(range(self.keypad_size.numb_of_keys)))[:self.keypad_size.props_per_key]
dispersed_keypad = self.random_attribute_rotation(
shuffled_keys,
attr_rotation,
attr_rotation.tolist(),
)
self.keypad = matrix_to_list(dispersed_keypad)
self.keypad = dispersed_keypad.reshape(-1)
def partial_keypad_shuffle(self):
# TODO: this should be split shuffle
numb_of_selected_sets = self.keypad_size.props_per_key // 2
# randomly shuffle half the sets. if props_per_key is odd, randomly add one 50% of the time
numb_of_selected_sets += choice([0, 1]) if (self.keypad_size.props_per_key & 1) == 1 else 0
selected_sets = secure_fisher_yates_shuffle(list(range(self.keypad_size.props_per_key)))[:numb_of_selected_sets]
user_keypad_matrix = self.keypad_matrix()
shuffled_keys = secure_fisher_yates_shuffle(user_keypad_matrix)
keypad_by_sets = []
for idx, attrs in enumerate(matrix_transpose(shuffled_keys)):
if idx in selected_sets:
keypad_by_sets.append(secure_fisher_yates_shuffle(attrs))
else:
keypad_by_sets.append(attrs)
self.keypad = matrix_to_list(matrix_transpose(keypad_by_sets))
#numb_of_selected_sets = self.keypad_size.props_per_key // 2
## randomly shuffle half the sets. if props_per_key is odd, randomly add one 50% of the time
#numb_of_selected_sets += choice([0, 1]) if (self.keypad_size.props_per_key & 1) == 1 else 0
#selected_sets = secure_fisher_yates_shuffle(list(range(self.keypad_size.props_per_key)))[:numb_of_selected_sets]
#user_keypad_matrix = self.keypad_matrix()
#shuffled_keys = secure_fisher_yates_shuffle(user_keypad_matrix)
#keypad_by_sets = []
#for idx, attrs in enumerate(matrix_transpose(shuffled_keys)):
# if idx in selected_sets:
# keypad_by_sets.append(secure_fisher_yates_shuffle(attrs))
# else:
# keypad_by_sets.append(attrs)
#self.keypad = matrix_to_list(matrix_transpose(keypad_by_sets))
pass
@staticmethod
def random_attribute_rotation(
user_keypad: list[list[int]],
user_keypad: np.ndarray,
attr_rotation: list[int]
) -> list[list[int]]:
transposed_user_keypad = matrix_transpose(user_keypad)
if len(attr_rotation) != len(transposed_user_keypad):
raise ValueError("attr_rotation must be the same length as the transposed user keypad")
for idx, attr_set in enumerate(transposed_user_keypad):
) -> np.ndarray:
transposed = user_keypad.T
if len(attr_rotation) != len(transposed):
raise ValueError("attr_rotation must be the same length as the number of attributes")
for idx, attr_set in enumerate(transposed):
rotation = attr_rotation[idx]
transposed_user_keypad[idx] = attr_set[rotation:] + attr_set[:rotation]
return matrix_transpose(transposed_user_keypad)
rotation = rotation % len(attr_set) if len(attr_set) > 0 else 0
transposed[idx] = np.roll(attr_set, rotation)
return transposed.T
def attribute_adjacency_graph(self) -> dict[int, set[int]]:
user_keypad_keypad = self.keypad_matrix()
@@ -103,4 +109,4 @@ class UserKeypad:
if not (0 <= set_idx < self.keypad_size.props_per_key):
raise ValueError(f"set_idx must be between 0 and {self.keypad_size.props_per_key - 1}")
keypad_attr_idx = self.keypad_matrix()
return keypad_attr_idx[key_numb][set_idx]
return int(keypad_attr_idx[key_numb][set_idx])

View File

@@ -9,12 +9,6 @@ def secure_fisher_yates_shuffle(arr: list) -> list:
return arr
def generate_random_nonrepeating_list(list_len: int, min_val: int = 0, max_val: int = 2 ** 16) -> list[int]:
if max_val - min_val < list_len:
raise ValueError("Range of values is less than the list length requested")
return secure_fisher_yates_shuffle(list(range(min_val, max_val)))[:list_len]
def xor_lists(l1: list[int], l2: list[int]):
if len(l1) != len(l2):
raise ValueError("Lists must be of equal length")