RSA加密及签名
RSA加密及签名
CSDN
51CTO博客
'''
使用函数库Crypto或cryptography完成RSA算法相关操作
包括密钥的生成、导入导出;
加密和解密;
签名和验证;
'''
from Crypto.Util.number import *
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Sig_pk
from Crypto.Hash import SHA
import base64
def enc_sign(plaintext):
m = bytes_to_long(plaintext)
key = RSA.generate(2048)
f = open('private.pem', 'wb')
f.write(key.export_key('PEM'))
f.close()
f = open('public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('public.pem', 'r')
key = RSA.import_key(f.read())
n = key.n
e = key.e
c = pow(m, e, n)
ciphertext = long_to_bytes(c)
f = open('private.pem', 'r')
private_key = RSA.import_key(f.read())
key = private_key
hash_value = SHA.new(plaintext)
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(hash_value)
signature = base64.b64encode(signature).decode()
return key.export_key('PEM'), ciphertext, signature
''''''
''''''
def dec_ver(key, ciphertext, signature):
key = RSA.import_key(key)
n = key.n
d = key.d
c = bytes_to_long(ciphertext)
m = pow(c, d, n)
pt = long_to_bytes(m)
signature = base64.b64decode(signature.encode())
f = open('public.pem', 'r')
public_key = RSA.import_key(f.read())
hash_value = SHA.new(pt)
verifier = Sig_pk.new(public_key)
result = verifier.verify(hash_value, signature)
return pt, result
if __name__ == '__main__':
plaintext = 'pycryptdemo is easy to learn. 你觉得呢?'.encode()
key, ciphertext, signature = enc_sign(plaintext)
print('==================================================')
pt, result = dec_ver(key, ciphertext, signature)
print('==================================================')
if (pt == plaintext) and result:
print('success')