-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecureGameDataManager.py
More file actions
64 lines (55 loc) · 2.14 KB
/
SecureGameDataManager.py
File metadata and controls
64 lines (55 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import json
import os
from cryptography.fernet import Fernet
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
class SecureSaveSystem:
def __init__(self, password: str):
# パスワードから安全な鍵を生成
salt = b'salt_for_python_save'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
self.fernet = Fernet(key)
self.filename = "game_data.sav"
self.backup = "game_data.bak"
def save(self, data):
try:
# 1. バックアップ
if os.path.exists(self.filename):
os.replace(self.filename, self.backup)
# 2. シリアライズ & 暗号化
json_str = json.dumps(data).encode()
encrypted_data = self.fernet.encrypt(json_str)
# 3. 書き込み
with open(self.filename, "wb") as f:
f.write(encrypted_data)
print(f">>> [Py] 保存完了 (Size: {len(encrypted_data)} bytes)")
except Exception as e:
print(f"Save Error: {e}")
def load(self):
if not os.path.exists(self.filename):
return {"name": "PythonHero", "lv": 1, "items": []}
try:
with open(self.filename, "rb") as f:
encrypted_data = f.read()
# 4. 復号 (改ざんがあればここで例外が発生する)
decrypted_data = self.fernet.decrypt(encrypted_data)
print(">>> [Py] ロード成功 (整合性確認済み)")
return json.loads(decrypted_data.decode())
except Exception as e:
print(f"Load Error (改ざん検知): {e}")
return None
# 実行テスト
if __name__ == "__main__":
manager = SecureSaveSystem("Strong_Password_Python_99")
game_state = manager.load()
print(f"現在データ: {game_state}")
game_state["lv"] += 1
game_state["items"].append("Master Sword")
manager.save(game_state)