-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.py
40 lines (33 loc) · 948 Bytes
/
encrypt.py
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
# External Imports
import os
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# Create Salt
def setSalt():
return os.urandom(16) #16-bytes salt
# Get Key from a password
def getKdf(salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=10**5,
backend=default_backend()
)
return(kdf)
def getKey(password,salt):
kdf = getKdf(salt)
key = base64.urlsafe_b64encode(kdf.derive(password))
return(key)
def getFernet(password,salt):
key = getKey(password,salt)
return(Fernet(key))
def encrypt(text,password,salt):
f = getFernet(password,salt)
return(f.encrypt(text))
def decrypt(text,password,salt):
f = getFernet(password,salt)
return(f.decrypt(text))