45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
import bcrypt
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from cryptography.fernet import Fernet
|
|
from .models import MasterHash
|
|
from django.http import JsonResponse
|
|
|
|
# Salva l'hash della master password
|
|
def save_master_hash(hash):
|
|
MasterHash.objects.create(
|
|
hash=hash,
|
|
)
|
|
|
|
# Carica l'hash della master password
|
|
def load_master_hash():
|
|
try:
|
|
entry = MasterHash.objects.get()
|
|
return entry.hash
|
|
except Exception as e:
|
|
return None
|
|
|
|
# Autenticazione della master password
|
|
def authenticate(master_password):
|
|
master_hash = load_master_hash()
|
|
if master_hash is None:
|
|
hashed_password = bcrypt.hashpw(master_password.encode(), bcrypt.gensalt())
|
|
save_master_hash(hashed_password)
|
|
return True
|
|
|
|
auth_success = bcrypt.checkpw(master_password.encode(), master_hash.tobytes())
|
|
return auth_success
|
|
|
|
def derive_key(master_password):
|
|
hash = hashlib.sha256(master_password.encode()).digest()
|
|
return base64.urlsafe_b64encode(hash)
|
|
|
|
def encrypt_password(password, key):
|
|
cipher = Fernet(key)
|
|
return cipher.encrypt(password.encode()).decode()
|
|
|
|
def decrypt_password(encrypted_password, key):
|
|
cipher = Fernet(key)
|
|
return cipher.decrypt(encrypted_password.encode()).decode()
|