remove salt from UserCipher

This commit is contained in:
2025-03-16 08:07:42 -05:00
parent b6ab0c1890
commit 2a19aa73c4
3 changed files with 169 additions and 181 deletions

View File

@@ -3,7 +3,6 @@ import hashlib
from dataclasses import dataclass
import bcrypt
import numpy as np
from secrets import choice
from src.models import EncipheredNKode, KeypadSize
from src.customer_cipher import CustomerCipher
@@ -14,83 +13,89 @@ class UserCipher:
combined_set_key: np.ndarray
pass_key: np.ndarray
mask_key: np.ndarray
salt: bytes
max_nkode_len: int
@classmethod
def create(cls, keypad_size: KeypadSize, set_values: np.ndarray, max_nkode_len: int) -> 'UserCipher':
if len(set_values) != keypad_size.props_per_key:
def create(cls, keypad_size: KeypadSize, customer_set_key: np.ndarray, max_nkode_len: int) -> 'UserCipher':
if len(customer_set_key) != keypad_size.props_per_key:
raise ValueError("Invalid set values")
set_values_array = np.array(set_values, dtype=np.uint16)
set_key = np.random.choice(2**16,size=keypad_size.props_per_key, replace=False)
set_key = np.bitwise_xor(set_key, set_values_array)
user_set_key = np.random.choice(2**16,size=keypad_size.props_per_key, replace=False)
return UserCipher(
prop_key=np.random.choice(2 ** 16, size=keypad_size.total_props, replace=False),
pass_key=np.random.choice(2 ** 16, size=max_nkode_len, replace=False),
mask_key=np.random.choice(2**16, size=max_nkode_len, replace=False),
combined_set_key=set_key,
salt=bcrypt.gensalt(),
combined_set_key=user_set_key ^ customer_set_key,
max_nkode_len=max_nkode_len
)
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")
raise ValueError("User encoded_mask is too long")
padding_size = self.max_nkode_len - len(user_mask)
# Generate padding directly using np.random.choice
padding = np.random.choice(set_vals, size=padding_size, replace=True).astype(np.uint16)
# Concatenate original mask with padding
return np.concatenate([user_mask, padding])
@staticmethod
def encode_base64_str(data: np.ndarray) -> str:
return base64.b64encode(int_array_to_bytes(data)).decode("utf-8")
return base64.b64encode( b"".join([int(num).to_bytes(2, byteorder='big') for num in data])).decode("utf-8")
@staticmethod
def decode_base64_str(data: str) -> np.ndarray:
byte_data = base64.b64decode(data)
int_list = []
for i in range(0, len(byte_data), 2):
int_val = int.from_bytes(byte_data[i:i + 2], byteorder='big')
int_list.append(int_val)
return np.array(int_list, dtype=np.uint16)
def _hash_passcode(self, passcode: np.ndarray) -> str:
passcode_bytes = passcode.astype(np.uint16).tobytes()
passcode_digest = base64.b64encode(hashlib.sha256(passcode_bytes).digest())
hashed_data = bcrypt.hashpw(passcode_digest, self.salt)
return hashed_data.decode("utf-8")
def encipher_nkode(
self,
passcode_prop_idx: list[int],
customer_cipher: CustomerCipher
) -> EncipheredNKode:
mask = self.encipher_mask(passcode_prop_idx, customer_cipher)
code = self.encipher_salt_hash_code(passcode_prop_idx, customer_cipher)
code = self.hash_nkode(passcode_prop_idx, customer_cipher)
return EncipheredNKode(
code=code,
mask=mask
)
def encipher_salt_hash_code(
def hash_nkode(
self,
passcode_prop_idx: list[int],
customer_prop: CustomerCipher,
) -> str:
salt = bcrypt.gensalt(rounds=12)
passcode_bytes = self.prehash_passcode(passcode_prop_idx, customer_prop)
passcode_digest = base64.b64encode(hashlib.sha256(passcode_bytes).digest())
hashed_data = bcrypt.hashpw(passcode_digest, salt)
return hashed_data.decode("utf-8")
def compare_nkode(
self,
passcode_prop_idx: list[int],
customer_prop: CustomerCipher,
hashed_passcode: str
) -> bool:
passcode_bytes = self.prehash_passcode(passcode_prop_idx, customer_prop)
passcode_digest = base64.b64encode(hashlib.sha256(passcode_bytes).digest())
return bcrypt.checkpw(passcode_digest, hashed_passcode.encode('utf-8'))
def prehash_passcode(
self,
passcode_prop_idx: list[int],
customer_prop: CustomerCipher
) -> bytes:
passcode_len = len(passcode_prop_idx)
passcode_cipher = self.pass_key.copy()
passcode_cipher[:passcode_len] = (
passcode_cipher[:passcode_len] ^
self.prop_key[passcode_prop_idx] ^
customer_prop.prop_key[passcode_prop_idx]
passcode_cipher[:passcode_len] ^
self.prop_key[passcode_prop_idx] ^
customer_prop.prop_key[passcode_prop_idx]
)
return self._hash_passcode(passcode_cipher)
return passcode_cipher.astype(np.uint16).tobytes()
def encipher_mask(
self,
@@ -100,33 +105,21 @@ class UserCipher:
customer_props = customer_cipher.prop_key[passcode_prop_idx]
customer_sets = [customer_cipher.get_prop_set_val(prop) for prop in customer_props]
padded_customer_sets = self.pad_user_mask(np.array(customer_sets), customer_cipher.set_key)
# Get indices of set values
set_idx = np.array([customer_cipher.get_set_index(set_val) for set_val in padded_customer_sets],
dtype=np.uint16)
mask_set_keys = np.array([self.combined_set_key[idx] for idx in set_idx], dtype=np.uint16)
ordered_set_key = self.combined_set_key[set_idx]
mask = ordered_set_key ^ padded_customer_sets ^ self.mask_key
encoded_mask = self.encode_base64_str(mask)
return encoded_mask
# XOR operations
ciphered_mask = np.bitwise_xor(mask_set_keys, padded_customer_sets)
ciphered_mask = np.bitwise_xor(ciphered_mask, self.mask_key)
mask = self.encode_base64_str(ciphered_mask)
return mask
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)
set_key_rand_component = np.bitwise_xor(set_vals_array, self.combined_set_key)
def decipher_mask(self, encoded_mask: str, customer_set_key: np.ndarray, passcode_len: int) -> list[int]:
mask = self.decode_base64_str(encoded_mask)
# user_set_key ordered by the user's nkode and padded to be length max_nkode_len
ordered_set_key = mask ^ self.mask_key
user_set_key = customer_set_key ^ self.combined_set_key
passcode_sets = []
for partial_set in ordered_set_key[:passcode_len]:
set_idx = np.where(user_set_key == partial_set)[0][0]
passcode_sets.append(int(customer_set_key[set_idx]))
return passcode_sets
for set_cipher in deciphered_mask[:passcode_len]:
# Find index where values match
set_idx = np.where(set_key_rand_component == set_cipher)[0][0]
passcode_sets.append(set_vals[set_idx])
return np.array(passcode_sets)
def int_array_to_bytes(int_arr: np.ndarray, byte_size: int = 2) -> bytes:
return b"".join([int(num).to_bytes(byte_size, byteorder='big') for num in int_arr])