最近在做Web系统的一个license许可功能的时候遇到了一个问题,当我用RSA对获取到的系统的特征值进行加密解密时,由于特征值字符串过长,导致RSA加解密的时候提示文本过长,失败。因此这里记录下我封装的对于长文本,RSA加解密的一个类。

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

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


long_text = "helloworld......" # 可自行加长补全


class RSAsys:
public_pem = './public.pem'
private_pem = './private.pem'

# 加密
@classmethod
def rsa_encrypt(cls, message, p_length=200):
rsakey = RSA.importKey(open(cls.public_pem).read())
cipher = Cipher_pkcs1_v1_5.new(rsakey) # 创建用于执行pkcs1_v1_5加密或解密的密码
res = []
for i in range(0, len(message), p_length):
res.append(cipher.encrypt(message[i:i+p_length].encode()))
cipher_text_byte = b''
for b in res:
cipher_text_byte += b
cipher_text = base64.b64encode(cipher_text_byte)
return cipher_text.decode('utf-8')

# 解密
@classmethod
def rsa_decrypt(cls, cipher_text, p_length=256):
encrypt_text = base64.b64decode(cipher_text.encode('utf-8'))
rsakey = RSA.importKey(open(cls.private_pem).read())
cipher = Cipher_pkcs1_v1_5.new(rsakey) # 创建用于执行pkcs1_v1_5加密或解密的密码
res = []
for i in range(0, len(encrypt_text), p_length):
res.append(cipher.decrypt(encrypt_text[i:i+p_length], "解密失败"))
text = b''
for b in res:
text += b
return text.decode('utf-8')


if __name__ == '__main__':
en_text = RSAsys.rsa_encrypt(long_text)
print(en_text)
de_text = RSAsys.rsa_decrypt(en_text)
print(de_text)