parent
f8b1a808cf
commit
963dd8ed5c
@ -0,0 +1,61 @@
|
||||
from Crypto.PublicKey import RSA
|
||||
#from Crypto.Cipher import PKCS1_OAEP
|
||||
from Crypto.Signature import PKCS1_v1_5
|
||||
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
|
||||
from Crypto import Random
|
||||
#from base64 import b64encode, b64decode
|
||||
|
||||
hash = "SHA-256"
|
||||
|
||||
def new_keys(keysize):
|
||||
random_generator = Random.new().read
|
||||
key = RSA.generate(keysize, random_generator)
|
||||
private, public = key, key.publickey()
|
||||
return public, private
|
||||
|
||||
def key_import(key):
|
||||
return RSA.importKey(key)
|
||||
|
||||
def key_export(key):
|
||||
return key.exportKey()
|
||||
|
||||
def sign(message, priv_key, hashAlg="SHA-256"):
|
||||
global hash
|
||||
hash = hashAlg
|
||||
signer = PKCS1_v1_5.new(priv_key)
|
||||
if (hash == "SHA-512"):
|
||||
digest = SHA512.new()
|
||||
elif (hash == "SHA-384"):
|
||||
digest = SHA384.new()
|
||||
elif (hash == "SHA-256"):
|
||||
digest = SHA256.new()
|
||||
elif (hash == "SHA-1"):
|
||||
digest = SHA.new()
|
||||
else:
|
||||
digest = MD5.new()
|
||||
digest.update(message)
|
||||
return signer.sign(digest)
|
||||
|
||||
def verify(message, signature, pub_key):
|
||||
signer = PKCS1_v1_5.new(pub_key)
|
||||
if (hash == "SHA-512"):
|
||||
digest = SHA512.new()
|
||||
elif (hash == "SHA-384"):
|
||||
digest = SHA384.new()
|
||||
elif (hash == "SHA-256"):
|
||||
digest = SHA256.new()
|
||||
elif (hash == "SHA-1"):
|
||||
digest = SHA.new()
|
||||
else:
|
||||
digest = MD5.new()
|
||||
digest.update(message)
|
||||
return signer.verify(digest, signature)
|
||||
|
||||
|
||||
keys = new_keys(1024)
|
||||
print(keys[1]) # public, private
|
||||
s = sign(b"Hello", keys[1])
|
||||
print(s)
|
||||
print(verify(b"Hello", s, keys[0]))
|
||||
|
||||
print(key_export(keys[0]))
|
Loading…
Reference in new issue