Skip to content

Commit aa48b4a

Browse files
Refactor database connection and salt handling
Refactor database connection management to use thread-local storage and improve salt handling in user registration and verification processes.
1 parent 739633e commit aa48b4a

1 file changed

Lines changed: 42 additions & 14 deletions

File tree

kha256/kha256.py

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@
7979
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Literal, NamedTuple, Optional, overload, Tuple, Union, cast
8080
import xxhash
8181

82-
from . import __version__ # paket __init__.py'de tanımlı
82+
#from . import __version__ # paket __init__.py'de tanımlı
83+
from ._version import __version__, __author__, __license__
8384

8485
# Jupyter Notebook uyumluluğu için
8586
nest_asyncio2.apply()
@@ -10616,6 +10617,8 @@ def secure_avalanche_mix(data: bytes, salt: bytes) -> bytes:
1061610617

1061710618

1061810619
# ChaCha20 Permutation (Hızlı + Güvenli)
10620+
10621+
1061910622
def chacha_avalanche_mix(data: bytes, salt: bytes) -> bytes:
1062010623
"""ChaCha20 quarter rounds - kanıtlanmış diffusion"""
1062110624
key = (data + salt)[:32] # 256-bit key
@@ -12726,6 +12729,7 @@ def show_info(self):
1272612729

1272712730
print(info)
1272812731

12732+
1272912733
class db:
1273012734
"""database manager"""
1273112735

@@ -12736,23 +12740,26 @@ class db:
1273612740
@contextmanager
1273712741
def get_db_connection():
1273812742
"""Thread-safe veritabanı bağlantısı için context manager"""
12739-
# ✅ DÜZELTME: Lokal değişken oluşturma, sınıf attribute'unu kullan
12743+
# Thread başına bir connection
12744+
# Thread-local storage for database connections
12745+
thread_local = threading.local()
12746+
1274012747
if not hasattr(db.thread_local, "conn"):
12741-
db.thread_local.conn = sqlite3.connect("users.db", check_same_thread=False)
12742-
db.thread_local.conn.execute("PRAGMA journal_mode=WAL")
12743-
db.thread_local.conn.execute("PRAGMA busy_timeout=5000")
12748+
thread_local.conn = sqlite3.connect("users.db", check_same_thread=False)
12749+
thread_local.conn.execute("PRAGMA journal_mode=WAL") # Write-Ahead Logging
12750+
thread_local.conn.execute("PRAGMA busy_timeout=5000") # 5 second timeout
1274412751

12745-
conn = db.thread_local.conn
12752+
conn = thread_local.conn
1274612753
try:
1274712754
yield conn
1274812755
except sqlite3.Error as e:
1274912756
print(f"Veritabanı hatası: {e}")
12757+
# Bağlantıyı kapat ve yeniden dene
1275012758
try:
1275112759
conn.close()
1275212760
except BaseException:
1275312761
pass
12754-
if hasattr(db.thread_local, "conn"):
12755-
delattr(db.thread_local, "conn")
12762+
delattr(thread_local, "conn")
1275612763
raise
1275712764

1275812765
def setup_database():
@@ -12762,6 +12769,7 @@ def setup_database():
1276212769
try:
1276312770
with db.get_db_connection() as conn:
1276412771
cursor = conn.cursor()
12772+
# Foreign keys etkinleştir
1276512773
cursor.execute("PRAGMA foreign_keys = ON")
1276612774

1276712775
cursor.execute("""
@@ -12774,6 +12782,7 @@ def setup_database():
1277412782
)
1277512783
""")
1277612784

12785+
# Index oluştur
1277712786
cursor.execute(
1277812787
"CREATE INDEX IF NOT EXISTS idx_username ON users(username)"
1277912788
)
@@ -12801,6 +12810,7 @@ def save_user(username, password, retry_count=3):
1280112810

1280212811
for attempt in range(retry_count):
1280312812
try:
12813+
# Önce kullanıcı var mı kontrol et
1280412814
with db.get_db_connection() as conn:
1280512815
cursor = conn.cursor()
1280612816
cursor.execute(
@@ -12810,17 +12820,21 @@ def save_user(username, password, retry_count=3):
1281012820
print(f"⚠️ '{username}' kullanıcısı zaten kayıtlı")
1281112821
return False
1281212822

12813-
salt = secrets.token_bytes(32)
12823+
# Tuz oluştur - hasher'ın dışında oluştur
12824+
salt = secrets.token_bytes(32) # 32 byte yeterli, 64'e gerek yok
1281412825

12826+
# Memory-hard hash oluştur
1281512827
print(f"⏳ '{username}' için memory-hard hash hesaplanıyor...")
1281612828
hasher = TrueMemoryHardHasher(
1281712829
memory_cost_kb=8192, time_cost=3, parallelism=1
1281812830
)
1281912831

12832+
# ✅ DÜZELTME: salt parametresini adlandır!
1282012833
password_hash = hasher.hash(password, salt=salt)
1282112834

1282212835
print("✅ Hash hesaplandı")
1282312836

12837+
# Veritabanına kaydet
1282412838
with db.get_db_connection() as conn:
1282512839
cursor = conn.cursor()
1282612840
cursor.execute(
@@ -12847,6 +12861,7 @@ def save_user(username, password, retry_count=3):
1284712861
except Exception as e:
1284812862
print(f"❌ Kayıt hatası: {e}")
1284912863
import traceback
12864+
1285012865
traceback.print_exc()
1285112866
return False
1285212867

@@ -12869,21 +12884,30 @@ def verify_user(username, password, retry_count=3):
1286912884
result = cursor.fetchone()
1287012885

1287112886
if not result:
12887+
# Timing attack koruması için gecikme
1287212888
time.sleep(0.5)
1287312889
print(f"❌ Kullanıcı '{username}' bulunamadı")
1287412890
return False
1287512891

1287612892
stored_hash, salt = result
1287712893

12894+
# stored_hash string olarak geliyor, salt bytes olarak
1287812895
print(f"⏳ '{username}' için hash doğrulanıyor...")
1287912896

12897+
# ✅ DÜZELTME: verify metodunu kullan!
1288012898
hasher = TrueMemoryHardHasher(
1288112899
memory_cost_kb=8192, time_cost=3, parallelism=1
1288212900
)
1288312901

12902+
# Ya verify metodunu kullan:
1288412903
is_valid = hasher.verify(password, stored_hash, salt)
1288512904

12886-
if is_valid:
12905+
# Ya da hash metoduna salt'ı açıkça ver:
12906+
# computed_hash = hasher.hash(password, salt=salt) # salt
12907+
# parametresini adlandır!
12908+
12909+
if is_valid: # veya computed_hash == stored_hash
12910+
# Başarılı giriş tarihini güncelle
1288712911
cursor.execute(
1288812912
"UPDATE users SET last_login = datetime('now') WHERE username = ?",
1288912913
(username,),
@@ -12905,6 +12929,7 @@ def verify_user(username, password, retry_count=3):
1290512929
except Exception as e:
1290612930
print(f"❌ Doğrulama hatası: {e}")
1290712931
import traceback
12932+
1290812933
traceback.print_exc()
1290912934
return False
1291012935

@@ -12963,15 +12988,14 @@ def delete_user(username):
1296312988
def close_all_connections():
1296412989
"""Tüm veritabanı bağlantılarını kapat"""
1296512990
try:
12966-
# ✅ DÜZELTME: db.thread_local kullan
1296712991
if hasattr(db.thread_local, "conn"):
12968-
db.thread_local.conn.close()
12969-
delattr(db.thread_local, "conn")
12992+
thread_local.conn.close()
12993+
delattr(thread_local, "conn")
1297012994
print("✅ Veritabanı bağlantıları kapatıldı")
1297112995
except BaseException:
1297212996
pass
1297312997

12974-
# Jupyter için interaktif fonksiyon
12998+
# Jupyter için interaktif fonksiyon - Jupyter widget'larını import edelim
1297512999
import ipywidgets as widgets
1297613000
from IPython.display import HTML, clear_output, display
1297713001

@@ -12981,8 +13005,10 @@ def interactive_demo():
1298113005
print("🎮 İNTERAKTİF MEMORY-HARD HASH DEMO")
1298213006
print("=" * 60)
1298313007

13008+
# Önce veritabanını kur
1298413009
db.setup_database()
1298513010

13011+
# Widget'ları oluştur
1298613012
username_input = db.widgets.Text(
1298713013
placeholder="Kullanıcı adı",
1298813014
description="Kullanıcı:",
@@ -13078,6 +13104,7 @@ def on_clear_click(b):
1307813104
list_btn.on_click(on_list_click)
1307913105
clear_btn.on_click(on_clear_click)
1308013106

13107+
# Layout
1308113108
buttons = db.widgets.HBox([register_btn, login_btn, list_btn, clear_btn])
1308213109

1308313110
form = db.widgets.VBox(
@@ -13096,6 +13123,7 @@ def on_clear_click(b):
1309613123

1309713124
display(form)
1309813125

13126+
1309913127
def performance_comparison():
1310013128
"""Memory-hard vs normal hash performans karşılaştırması"""
1310113129

0 commit comments

Comments
 (0)