-
Notifications
You must be signed in to change notification settings - Fork 1
/
sign.py
88 lines (72 loc) · 2.24 KB
/
sign.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
88
import glob
import time
import random
import string
import gc
available = {}
try:
import M2Crypto.EVP
except ImportError:
available["m2crypto"] = False
else:
available["m2crypto"] = True
try:
import Crypto.Hash.SHA
import Crypto.PublicKey.RSA
import Crypto.Signature.PKCS1_v1_5
except ImportError:
available["crypto"] = False
else:
available["crypto"] = True
def get_signature_m2crypto(private_key, message):
key = M2Crypto.EVP.load_key_string(private_key)
key.reset_context(md='sha1')
key.sign_init()
key.sign_update(bytes(message))
return key.sign_final()
def get_signature_crypto(private_key, message):
key = Crypto.PublicKey.RSA.importKey(private_key)
signer = Crypto.Signature.PKCS1_v1_5.new(key)
sha1_hash = Crypto.Hash.SHA.new()
sha1_hash.update(bytes(message))
return signer.sign(sha1_hash)
def get_random_string(length):
pool = string.letters + string.digits
return "".join(random.choice(pool) for i in range(length))
get_signature = {
"m2crypto": get_signature_m2crypto,
"crypto": get_signature_crypto,
}
def main():
for key_file in glob.glob("*.pem"):
with open(key_file, "r") as f:
private_key = f.read()
# Check that the signatures match.
results = []
for name, func in get_signature.items():
if not available[name]:
continue
results.append((name, func(private_key, "foo bar")))
print "{} using {}:".format(key_file, ", ".join(r[0] for r in results))
signatures = dict((r[1], True) for r in results).keys()
if len(signatures) == 1:
print " EQUAL"
else:
print " NOT EQUAL"
# Simple benchmark.
iters = 500
s = get_random_string(500)
for name, func in get_signature.items():
if not available[name]:
continue
print "running {} iterations of {}".format(iters, name)
gc.disable()
tic = time.time()
for i in range(iters):
func(private_key, s)
toc = time.time()
gc.enable()
print " took {:.3f}s".format(toc - tic)
print
if __name__ == "__main__":
main()