summaryrefslogtreecommitdiff
path: root/crypto.py
blob: 0274ec18e99a154e0d189116fae5952fc5a9fd26 (plain)
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
import M2Crypto.RSA
import M2Crypto.EVP
import time, sys
import base64

default_alg = 'sha256'

def sign(keyfile, data, alg = default_alg):
	digest = M2Crypto.EVP.MessageDigest(alg)
	digest.update(data)
	digval = digest.final()

	key = M2Crypto.RSA.load_key(keyfile)
	signature = key.sign(digval, algo = alg)
	return base64.urlsafe_b64encode(signature)

def verify(keyfile, data, sig, alg = default_alg):
	digest = M2Crypto.EVP.MessageDigest(alg)
	digest.update(data)
	digval = digest.final()

	key = M2Crypto.RSA.load_pub_key(keyfile)

	rawsig = base64.urlsafe_b64decode(sig)
	return bool(key.verify(digval, rawsig, algo = alg))

if __name__ == '__main__':
	if len(sys.argv) != 3:
		print 'pls give private + public key as arg.'
		sys.exit(1)
	sig = sign(sys.argv[1], 'test')
	vfy = verify(sys.argv[2], 'test', sig)
	print '(%d) %s %s' % (len(sig), vfy, sig)