89 lines
2.7 KiB
Python
89 lines
2.7 KiB
Python
import os, sys
|
|
import keyring
|
|
import json
|
|
import base64
|
|
from libs.fspn.utils import sha256_util, aes_util, ecdh_util, ecdsa_util
|
|
from libs.app.common.paths import ROOT_DIR
|
|
|
|
def encrypt_secret(secret: dict, user_password: str) -> str:
|
|
secret = json.dumps(secret)
|
|
key = ecdh_util.generate_derived_key(user_password.encode())
|
|
nonce, ciphertext, mac = aes_util.encrypt(secret.encode(), key)
|
|
|
|
payload = {
|
|
"nonce": base64.b64encode(nonce).decode(),
|
|
"ciphertext": base64.b64encode(ciphertext).decode(),
|
|
"mac": base64.b64encode(mac).decode()
|
|
}
|
|
|
|
return json.dumps(payload)
|
|
|
|
def decrypt_secret(payload_json: str, user_password: str) -> str | None:
|
|
payload = json.loads(payload_json)
|
|
|
|
nonce = base64.b64decode(payload["nonce"])
|
|
ciphertext = base64.b64decode(payload["ciphertext"])
|
|
mac = base64.b64decode(payload["mac"])
|
|
|
|
key = ecdh_util.generate_derived_key(user_password.encode())
|
|
plaintext = aes_util.decrypt_and_verify(nonce, ciphertext, mac, key)
|
|
|
|
return json.loads(plaintext.decode())
|
|
|
|
SERVICE_NAME = "NoSys"
|
|
|
|
def save_credential_data(data, verifying_key_b64, user_password):
|
|
credential_name = get_credential_name(verifying_key_b64)
|
|
payload = encrypt_secret(data, user_password)
|
|
keyring.set_password(credential_name, verifying_key_b64, payload)
|
|
|
|
def delete_credential(verifying_key_b64):
|
|
credential_name = get_credential_name(verifying_key_b64)
|
|
keyring.delete_password(credential_name, verifying_key_b64)
|
|
|
|
def get_credential_data(verifying_key_b64, user_password):
|
|
credential_name = get_credential_name(verifying_key_b64)
|
|
payload = keyring.get_password(credential_name, verifying_key_b64)
|
|
if payload:
|
|
data = decrypt_secret(payload, user_password)
|
|
return data
|
|
return None
|
|
|
|
def credential_exists(verifying_key_b64):
|
|
credential_name = get_credential_name(verifying_key_b64)
|
|
payload = keyring.get_password(credential_name, verifying_key_b64)
|
|
if payload:
|
|
return True
|
|
return False
|
|
|
|
def get_credential_name(verifying_key_b64):
|
|
return f"{SERVICE_NAME}|{verifying_key_b64}"
|
|
|
|
import json
|
|
import os
|
|
|
|
HISTORY_FILE = os.path.join(ROOT_DIR, "libs/lockbox", "userHistory.json")
|
|
|
|
def load_history():
|
|
if os.path.exists(HISTORY_FILE):
|
|
with open(HISTORY_FILE, "r") as f:
|
|
return json.load(f)
|
|
return []
|
|
|
|
def save_history(history):
|
|
with open(HISTORY_FILE, "w") as f:
|
|
json.dump(history, f, indent=2)
|
|
|
|
def add_to_history(item):
|
|
history = load_history()
|
|
if item not in history:
|
|
history.append(item)
|
|
save_history(history)
|
|
|
|
def delete_from_history(item):
|
|
history = load_history()
|
|
if item in history:
|
|
history.remove(item)
|
|
save_history(history)
|
|
return True
|
|
return False |