54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
![]() |
'''Cyptographic module'''
|
||
|
import base64
|
||
|
|
||
|
from cryptography.fernet import Fernet, InvalidToken
|
||
|
from cryptography.hazmat.primitives import hashes
|
||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||
|
|
||
|
|
||
|
def _get_crypto(password: str) -> Fernet:
|
||
|
_CRYPTO16_SALT = b'\xac\xaa\xc7\xae\x99\xb1\x7fO\x01\xc6\x94<R$\xf7?'
|
||
|
kdf = PBKDF2HMAC(
|
||
|
algorithm=hashes.SHA256(),
|
||
|
length=32,
|
||
|
salt=_CRYPTO16_SALT,
|
||
|
iterations=390000,
|
||
|
)
|
||
|
key = base64.urlsafe_b64encode(kdf.derive(password.encode('UTF-8')))
|
||
|
return Fernet(key)
|
||
|
|
||
|
|
||
|
def validate_password(password: str) -> bool:
|
||
|
'''Validate password using test message'''
|
||
|
_VERIFICATION_MESSAGE = 'Hello BRE'
|
||
|
_VERIFICATION_CRYPTO = \
|
||
|
'gAAAAABiMGnQn96MZkBpBE9qZRJfZ91-muMLzxMnydwcXt3ZaG6zjRt576E1waelYKxhGMazRSYwmslHpqxpgtIMSDbQSuE6_A=='
|
||
|
try:
|
||
|
keyphrase = decrypt(_VERIFICATION_CRYPTO, password)
|
||
|
return keyphrase == _VERIFICATION_MESSAGE
|
||
|
except InvalidToken:
|
||
|
return False
|
||
|
|
||
|
|
||
|
def encrypt(message: str, password: str) -> str:
|
||
|
'''Encrypt message using key locked by password'''
|
||
|
crypto = _get_crypto(password)
|
||
|
return crypto.encrypt(message.encode('UTF-8')).decode('UTF-8')
|
||
|
|
||
|
|
||
|
def encrypt_user(user_name: str, user_password: str, crypto_passwrod: str) -> str:
|
||
|
'''Encrypt user password using key locked by crypto password'''
|
||
|
return encrypt(user_name + user_password, crypto_passwrod)
|
||
|
|
||
|
|
||
|
def decrypt(ciphertext: str, password: str):
|
||
|
'''Decrypt ciphertext using key locked by password'''
|
||
|
crypto = _get_crypto(password)
|
||
|
return crypto.decrypt(ciphertext.encode('UTF-8')).decode('UTF-8')
|
||
|
|
||
|
|
||
|
def decrypt_user(user_name: str, ciphertext: str, crypto_passwrod: str) -> str:
|
||
|
'''Decrypt user password using key locked by crypto password'''
|
||
|
text = decrypt(ciphertext, crypto_passwrod)
|
||
|
return text[len(user_name):]
|