1414from Crypto .PublicKey import RSA
1515from django .core import cache
1616from django .db .models import QuerySet
17-
17+ from common . cache . mem_cache import MemCache
1818from common .constants .cache_version import Cache_Version
1919from system_manage .models import SystemSetting , SettingType
2020
21+ rsa_message_cache = MemCache ('rsa' , {})
2122lock = threading .Lock ()
2223rsa_cache = cache .cache
2324cache_key = "rsa_key"
@@ -39,15 +40,18 @@ def generate():
3940 return {'key' : key .publickey ().export_key (), 'value' : encrypted_key }
4041
4142
43+ version , get_key = Cache_Version .SYSTEM .value
44+
45+
4246def get_key_pair ():
43- rsa_value = rsa_cache .get (cache_key )
47+ rsa_value = rsa_cache .get (get_key ( key = 'rsa_key' ), version = version )
4448 if rsa_value is None :
4549 with lock :
46- rsa_value = rsa_cache .get (cache_key )
50+ rsa_value = rsa_cache .get (get_key ( key = 'rsa_key' ), version = version )
4751 if rsa_value is not None :
4852 return rsa_value
4953 rsa_value = get_key_pair_by_sql ()
50- version , get_key = Cache_Version . SYSTEM . value
54+
5155 rsa_cache .set (get_key (key = 'rsa_key' ), rsa_value , timeout = None , version = version )
5256 return rsa_value
5357
@@ -90,7 +94,6 @@ def decrypt(msg, pri_key: str | None = None):
9094 return decrypt_data .decode ("utf-8" )
9195
9296
93-
9497@lru_cache (maxsize = 2 )
9598def _get_encrypt_cipher (public_key : str ):
9699 """缓存加密 cipher 对象"""
@@ -138,6 +141,9 @@ def rsa_long_decrypt(message, pri_key: str | None = None, length=256):
138141 :param length : 1024bit的证书用128,2048bit证书用256位
139142 :return: 解密后的数据
140143 """
144+ result = rsa_message_cache .get (message )
145+ if result is not None :
146+ return result
141147 if pri_key is None :
142148 pri_key = get_key_pair ().get ('value' )
143149
@@ -149,5 +155,6 @@ def rsa_long_decrypt(message, pri_key: str | None = None, length=256):
149155 for i in range (0 , len (base64_de ), length ):
150156 result .extend (cipher .decrypt (base64_de [i :i + length ], 0 ))
151157
152- return result .decode ()
153-
158+ r = result .decode ()
159+ rsa_message_cache .set (message , r , timeout = 60 * 60 * 8 )
160+ return r
0 commit comments