-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignatures.py
87 lines (74 loc) · 2.14 KB
/
signatures.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
A) Installed Modules
1.pip install cryptography
B) Code Reference
link: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/
"""
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.exceptions import InvalidSignature
def generate_keys():
private = rsa.generate_private_key(
public_exponent=65537,
key_size=1024,
backend=default_backend()
)
public = private.public_key()
return private, public
def sign(message, private):
message = bytes(str(message), 'utf-8')
sig = private.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return sig
def verify(message, sig, public):
message = bytes(str(message), 'utf-8')
try:
public.verify(
sig,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except InvalidSignature:
return False
except:
print("Error executing public_key.verify")
return False
if __name__ == '__main__':
pr, pu = generate_keys()
print(pr)
print(pu)
message = "This is a secret message"
sig = sign(message, pr)
print("Signature: ", sig)
correct = verify(message, sig, pu)
print(correct)
if correct:
print("Success! Good sig")
else:
print("ERROR! Signature is bad")
pr2, pu2 = generate_keys()
sig2 = sign(message, pr2)
correct = verify(message, sig2, pu)
if correct:
print("ERROR! Bad signature checks out!")
else:
print("Success! Bad sig detected")
badmess = message + "Q"
correct = verify(badmess, sig, pu)
if correct:
print("ERROR! Tampered message checks out!")
else:
print("Success! Tampering detected")