提前准备好公钥和私钥文件.
公钥和私钥文件生成见文章Python生成RSA公钥public.pem私钥private.pem

利用Crypto模块实现

python3需要安装pycryptodome
pip install pycryptodome

注意: windows环境下可能会有找不到Crypto的情况,这里有个小BUG,windows环境下安装完pycryptodome后在你python的根目录下如:
Python\Python36\Lib\site-packages
里面有一个文件夹叫做crypto,将首字母小写c改成大写C即可解决.

实现代码:

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
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.Hash import SHA
import base64


class RSAsys:
public_pem = './public.pem' # 公钥文件路径
private_pem = './private.pem' # 私钥文件路径

# 加密
@classmethod
def rsa_encrypt(cls, message):
rsakey = RSA.importKey(open(cls.public_pem).read())
cipher = Cipher_pkcs1_v1_5.new(rsakey) # 创建用于执行pkcs1_v1_5加密或解密的密码
cipher_text = base64.b64encode(cipher.encrypt(message.encode('utf-8')))
return cipher_text.decode('utf-8')

# 解密
@classmethod
def rsa_decrypt(cls, cipher_text):
encrypt_text = cipher_text.encode('utf-8')
rsakey = RSA.importKey(open(cls.private_pem).read())
cipher = Cipher_pkcs1_v1_5.new(rsakey) # 创建用于执行pkcs1_v1_5加密或解密的密码
text = cipher.decrypt(base64.b64decode(encrypt_text), "解密失败")
return text.decode('utf-8')

# 加签
@classmethod
def sign_add(cls, message):
rsakey = RSA.importKey(open(cls.private_pem).read())
signer = Signature_pkcs1_v1_5.new(rsakey)
digest = SHA.new()
digest.update(message.encode("utf-8"))
sign = signer.sign(digest)
signature = base64.b64encode(sign)
return signature.decode('utf-8')

# 验签
@classmethod
def sign_verify(cls, message_verify, signature):
rsakey = RSA.importKey(open(cls.public_pem).read())
verifier = Signature_pkcs1_v1_5.new(rsakey)
hsmsg = SHA.new()
hsmsg.update(message_verify.encode("utf-8"))
try:
verifier.verify(hsmsg, base64.b64decode(signature))
return True
except Exception as e:
return False


if __name__ == '__main__':
message = 'helloworld'
cipher = RSAsys.rsa_encrypt(message)
print("加密", cipher)
text = RSAsys.rsa_decrypt(cipher)
print("解密", text)
sign = RSAsys.sign_add(message)
print("加签", sign)
sign_ver = RSAsys.sign_verify(message, sign)
print("验签", sign_ver)

参考文章