-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12 Key Derivation.py
58 lines (47 loc) · 1.32 KB
/
12 Key Derivation.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Key Derivation
# Key derivation functions are used to generate cryptographically strong keys from passwords
# We are using PBKDF2 key derivation function
# Importing Libraries/Modules
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidKey
import os
# Class for Key Derivation
class KeyDerivation():
def __init__(self):
self.salt = os.urandom(16)
def derive(self, password):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=self.salt,
iterations=100000,
)
key = kdf.derive(password)
return key
def verify(self, password, key):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=self.salt,
iterations=100000,
)
try:
kdf.verify(password, key)
except InvalidKey:
return False
return True
# Key Derivation
print("Key Derivation:")
# Creating Object
kdf = KeyDerivation()
# Deriving Key
password = b"My Name is Khan"
key = kdf.derive(password)
print(key)
# Verifying Password
result = kdf.verify(password, key)
print(result)
password = b"Wrong Password"
result = kdf.verify(password, key)
print(result)