1+ from Crypto .Hash import SHA256 , SHA , MD5
2+ from Crypto .PublicKey import RSA
3+ from Crypto .Signature import PKCS1_v1_5
4+ from Crypto import Random
5+ import argparse
6+ import os .path
7+
8+ parse = argparse .ArgumentParser (prog = 'Make Digital Signature' , description = 'Support SHA1, SHA256, MD5' , add_help = False );
9+ parse .add_argument ("-h" , "--hash" , help = "Hash Althorigm" )
10+ parse .add_argument ("input" , help = "Input data file." )
11+ parse .add_argument ("output" , help = "Output signature file" )
12+ args = parse .parse_args ()
13+ args .hash = args .hash .lower ()
14+ if (args .hash != 'sha1' and args .hash != 'sha256' and args .hash != 'md5' ):
15+ print ('The althorigm is not supported' )
16+ else :
17+ #Create Hash value from data.
18+ print ("Creating digital signature" )
19+ block_size = 256
20+ data = ''
21+ fi = open (args .input ,"rb" )
22+ while (1 ):
23+ tmp = fi .read (block_size )
24+ if len (tmp ) == 0 :
25+ break ;
26+ else : data += tmp
27+ fi .close ()
28+
29+ hash
30+ if (args .hash == 'sha1' ):
31+ hash = SHA .new (data )
32+ elif (args .hash == 'sha256' ):
33+ hash = SHA256 .new (data )
34+ elif args .hash == 'md5' :
35+ hash = MD5 .new (data )
36+
37+ if os .path .isfile ("prvkey.prv" ):
38+ prvkey_file = open ("prvkey.prv" ,"r" )
39+ key = RSA .importKey (prvkey_file .read ())
40+ prvkey_file .close ()
41+ else :
42+ # create random key
43+ random_generator = Random .new ().read
44+ key = RSA .generate (1024 , random_generator )
45+
46+ # save private key
47+ prvkey_file = open ("prvkey.prv" ,"w" )
48+ prvkey_file .write (key .exportKey ())
49+ prvkey_file .close ()
50+
51+ # sign by private key
52+ signer = PKCS1_v1_5 .new (key )
53+ signature = signer .sign (hash )
54+ print ("The digital signature for your file is: " )
55+ print (signature )
56+
57+ # export public key
58+ pubkey_file = open ("pubkey.pub" ,"w" )
59+ pubkey_file .write (key .publickey ().exportKey ())
60+ pubkey_file .close ()
61+ print ("Public key is: " )
62+ print (key .publickey ().exportKey ())
63+ print ("Public key has been exported into <pubkey.pub>" )
64+
65+ #export signature
66+ fo = open (args .output ,"wb" )
67+ fo .write (signature )
68+ fo .close ()
69+ print ("Digital signature has been saved into file " + args .output )
70+ print ("Finished" )
0 commit comments