Skip to content

Commit

Permalink
更新rsa 支持分段加密
Browse files Browse the repository at this point in the history
  • Loading branch information
limoruirui committed Dec 11, 2022
1 parent c2b12e2 commit ed6c14c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion tools/aes_encrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
try:
from Crypto.Cipher import AES
except:
print("检测到还未安装 pycryptdemo 请按照md的方法安装")
print("检测到还未安装 pycryptdome 请按照md的方法安装")
exit(0)
from binascii import b2a_hex, a2b_hex
from base64 import b64encode, b64decode
Expand Down
2 changes: 1 addition & 1 deletion tools/encrypt_symmetric.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
try:
from Crypto.Cipher import AES, DES, DES3
except:
print("检测到还未安装 pycryptdemo 请按照md的方法安装")
print("检测到还未安装 pycryptdome 请按照md的方法安装")
exit(0)
from binascii import b2a_hex, a2b_hex
from base64 import b64encode, b64decode
Expand Down
21 changes: 17 additions & 4 deletions tools/rsa_encrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from Crypto.PublicKey.RSA import importKey, construct
from Crypto.Cipher import PKCS1_v1_5
except:
print("检测到还未安装 pycryptdemo 请按照md的方法安装")
print("检测到还未安装 pycryptdome 请按照md的方法安装")
exit(0)
from base64 import b64encode

Expand All @@ -29,8 +29,21 @@ def public_key(self, rsaExponent, rsaModulus=10001):
return pubkey

def encrypt(self, data, b64=False):
data = data.encode('utf-8')
length = len(data)
default_length = 117
pub_key = importKey(self.key)
cipher = PKCS1_v1_5.new(pub_key)
rsa_text = cipher.encrypt(data.encode("utf8"))
rsa_text = b64encode(rsa_text).decode() if b64 else rsa_text.hex()
return rsa_text
if length < default_length:
rsa_text = cipher.encrypt(data)
return b64encode(rsa_text).decode() if b64 else rsa_text.hex()
offset = 0
res = []
while length - offset > 0:
if length - offset > default_length:
res.append(cipher.encrypt(data[offset:offset + default_length]))
else:
res.append(cipher.encrypt(data[offset:]))
offset += default_length
byte_data = b''.join(res)
return b64encode(byte_data).decode() if b64 else byte_data.hex()

0 comments on commit ed6c14c

Please sign in to comment.