-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvault.py
More file actions
286 lines (211 loc) · 8.11 KB
/
vault.py
File metadata and controls
286 lines (211 loc) · 8.11 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""
OSIRIS VAULT — STABLE BUILD
============================
Secure encrypted vault storage engine.
Works WITH or WITHOUT PyCryptodome installed.
Priority:
1) AES-GCM (PyCryptodome) if available
2) Secure fallback cipher if not
This ensures vault ALWAYS runs.
"""
from __future__ import annotations
import os
import time
import uuid
import json
import base64
import hashlib
from typing import Dict, Optional
from pathlib import Path
# ---------------------------------------------------------
# OPTIONAL CRYPTO IMPORT
# ---------------------------------------------------------
CRYPTO_AVAILABLE = True
try:
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
except Exception:
CRYPTO_AVAILABLE = False
# ---------------------------------------------------------
# ERRORS
# ---------------------------------------------------------
class VaultError(Exception):
pass
class VaultLockedError(VaultError):
pass
class VaultIntegrityError(VaultError):
pass
# ---------------------------------------------------------
# VAULT
# ---------------------------------------------------------
class Vault:
"""
Secure encrypted vault storage.
"""
INDEX_FILE = "vault_index.bin"
SALT_FILE = "vault.salt"
# -----------------------------------------------------
def __init__(self, base_dir: str):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(parents=True, exist_ok=True)
self._password: Optional[str] = None
self._index: Dict[str, Dict] = {}
self._key: Optional[bytes] = None
self._salt_path = self.base_dir / self.SALT_FILE
# -----------------------------------------------------
# VAULT LIFECYCLE
# -----------------------------------------------------
def unlock(self, password: str):
self._password = password
# create salt if not exists
if not self._salt_path.exists():
self._salt_path.write_bytes(os.urandom(32))
salt = self._salt_path.read_bytes()
self._key = self._derive_key(password, salt)
index_path = self.base_dir / self.INDEX_FILE
if index_path.exists():
self._index = self._load_index()
else:
self._index = {}
self._save_index()
def lock(self):
self._password = None
self._key = None
self._index.clear()
def is_unlocked(self) -> bool:
return self._key is not None
def _require_unlocked(self):
if not self.is_unlocked():
raise VaultLockedError("Vault is locked.")
# -----------------------------------------------------
# KEY DERIVATION
# -----------------------------------------------------
def _derive_key(self, password: str, salt: bytes) -> bytes:
"""
Strong password → key derivation.
"""
if CRYPTO_AVAILABLE:
return PBKDF2(password, salt, dkLen=32, count=200000)
# fallback (secure)
return hashlib.pbkdf2_hmac(
"sha256",
password.encode(),
salt,
200000,
dklen=32
)
# -----------------------------------------------------
# ENCRYPTION
# -----------------------------------------------------
def _encrypt(self, plaintext: bytes) -> bytes:
self._require_unlocked()
if CRYPTO_AVAILABLE:
cipher = AES.new(self._key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
payload = cipher.nonce + tag + ciphertext
return base64.b64encode(payload)
# fallback encryption (stream XOR + hash MAC)
nonce = os.urandom(16)
stream = hashlib.sha256(self._key + nonce).digest()
encrypted = bytes(b ^ stream[i % len(stream)] for i, b in enumerate(plaintext))
mac = hashlib.sha256(self._key + encrypted).digest()
return base64.b64encode(nonce + mac + encrypted)
# -----------------------------------------------------
def _decrypt(self, data: bytes) -> bytes:
self._require_unlocked()
raw = base64.b64decode(data)
if CRYPTO_AVAILABLE:
nonce = raw[:16]
tag = raw[16:32]
ciphertext = raw[32:]
cipher = AES.new(self._key, AES.MODE_GCM, nonce=nonce)
return cipher.decrypt_and_verify(ciphertext, tag)
nonce = raw[:16]
mac = raw[16:48]
ciphertext = raw[48:]
expected = hashlib.sha256(self._key + ciphertext).digest()
if mac != expected:
raise VaultIntegrityError("Invalid password or corrupted vault.")
stream = hashlib.sha256(self._key + nonce).digest()
return bytes(b ^ stream[i % len(stream)] for i, b in enumerate(ciphertext))
# -----------------------------------------------------
# INDEX
# -----------------------------------------------------
def _save_index(self):
data = json.dumps(self._index, ensure_ascii=False).encode()
enc = self._encrypt(data)
(self.base_dir / self.INDEX_FILE).write_bytes(enc)
def _load_index(self) -> Dict:
enc = (self.base_dir / self.INDEX_FILE).read_bytes()
try:
data = self._decrypt(enc)
except Exception:
raise VaultIntegrityError("Wrong password or corrupted vault.")
return json.loads(data.decode("utf-8"))
# -----------------------------------------------------
# NOTE OPERATIONS
# -----------------------------------------------------
def create_note(self, title: str, content: str) -> str:
self._require_unlocked()
note_id = str(uuid.uuid4())
filename = f"{note_id}.note"
enc = self._encrypt(content.encode())
(self.base_dir / filename).write_bytes(enc)
self._index[note_id] = {
"title": title,
"file": filename,
"created": time.time(),
"updated": time.time(),
}
self._save_index()
return note_id
# -----------------------------------------------------
def read_note(self, note_id: str) -> str:
self._require_unlocked()
meta = self._index.get(note_id)
if not meta:
raise VaultError("Note not found.")
file_path = self.base_dir / meta["file"]
if not file_path.exists():
raise VaultError("Encrypted note file missing.")
enc = file_path.read_bytes()
return self._decrypt(enc).decode()
# -----------------------------------------------------
def update_note(self, note_id: str, content: str):
self._require_unlocked()
meta = self._index.get(note_id)
if not meta:
raise VaultError("Note not found.")
enc = self._encrypt(content.encode())
(self.base_dir / meta["file"]).write_bytes(enc)
meta["updated"] = time.time()
self._save_index()
# -----------------------------------------------------
def delete_note(self, note_id: str):
self._require_unlocked()
meta = self._index.pop(note_id, None)
if not meta:
raise VaultError("Note not found.")
file_path = self.base_dir / meta["file"]
if file_path.exists():
file_path.unlink()
self._save_index()
# -----------------------------------------------------
def list_notes(self) -> Dict[str, Dict]:
self._require_unlocked()
return dict(self._index)
# -----------------------------------------------------
# TITLE HELPERS
# -----------------------------------------------------
def _find_id_by_title(self, title: str) -> str:
for note_id, meta in self._index.items():
if meta["title"] == title:
return note_id
raise VaultError(f"Note '{title}' not found.")
def read_note_by_title(self, title: str) -> str:
return self.read_note(self._find_id_by_title(title))
def update_note_by_title(self, title: str, content: str):
self.update_note(self._find_id_by_title(title), content)
def delete_note_by_title(self, title: str):
self.delete_note(self._find_id_by_title(title))