-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurelib.py
More file actions
29 lines (25 loc) · 846 Bytes
/
securelib.py
File metadata and controls
29 lines (25 loc) · 846 Bytes
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
import os
import hashlib
import base64
def derive_key(password: str, salt: bytes, length: int = 32) -> bytes:
return hashlib.pbkdf2_hmac(
hash_name='sha256',
password=password.encode(),
salt=salt,
iterations=100_000,
dklen=length
)
def xor_crypt(data: bytes, key: bytes) -> bytes:
return bytes(d ^ key[i % len(key)] for i, d in enumerate(data))
def encrypt(text: str, password: str) -> str:
salt = os.urandom(16)
key = derive_key(password, salt)
encrypted = xor_crypt(text.encode(), key)
return base64.b64encode(salt + encrypted).decode()
def decrypt(token: str, password: str) -> str:
raw = base64.b64decode(token)
salt = raw[:16]
encrypted = raw[16:]
key = derive_key(password, salt)
decrypted = xor_crypt(encrypted, key)
return decrypted.decode()