@
among ```
import M2Crypto
from tornado import escape
import base64
"""
sudo yum install -y python3-devel openssl-devel swig
pip install M2Crypto
"""
def handle_key_inner(key, start, end):
result = ''
# 分割 key,每 64 位长度换一行
divide = int(len(key) / 64)
divide = divide if (divide > 0) else divide + 1
line = divide if (len(key) % 64 == 0) else divide + 1
for i in range(line):
result += key[i * 64:(i + 1) * 64] + '\n'
result = start + result + end
return result
def handle_pub_key(key):
"""
处理公钥
公钥格式 pem,处理成以-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾的格式
:param key:pem 格式的公钥,无-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾
:return:
"""
start = '-----BEGIN PUBLIC KEY-----\n'
end = '-----END PUBLIC KEY-----'
return handle_key_inner(key, start, end)
def handle_pri_key(key):
start = '-----BEGIN PRIVATE KEY-----\n'
end = '-----END PRIVATE KEY-----'
return handle_key_inner(key, start, end)
def util_rsa_encrypt_with_private_key_str(msg: bytes, private_key_str: str, blocksize=117):
private_key_str = "".join([e.strip() for e in private_key_str.splitlines()])
private_key_str = handle_pri_key(private_key_str)
bio = M2Crypto.BIO.MemoryBuffer(private_key_str.encode("utf-8"))
rsa_pri = M2Crypto.RSA.load_key_bio(bio)
out_li = []
len_msg = len(msg)
for i in range(0, len_msg, blocksize):
piece = msg[i:i + blocksize]
ctxt_pri = rsa_pri.private_encrypt(piece, M2Crypto.RSA.pkcs1_padding) # 这里的方法选择加密填充方式,所以在解密的时候 要对应。
out_li.append(ctxt_pri)
raw_msg = b''.join(out_li)
return base64.b64encode(raw_msg)
def pub_decrypt_with_pubkeyfile(msg, file_name):
rsa_pub = M2Crypto.RSA.load_pub_key(file_name)
pub_decrypt(msg, rsa_pub)
def util_rsa_decrypt_with_public_key_str(msg, pub_key: str):
"""
Args:
msg: base64 string
"""
pub_key = "".join([e.strip() for e in pub_key.splitlines()])
pub_key = handle_pub_key(pub_key)
msg = escape.utf8(msg)
bio = M2Crypto.BIO.MemoryBuffer(pub_key.encode("utf-8"))
rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio)
return pub_decrypt(msg, rsa_pub)
def pub_decrypt(msg, rsa_pub, block_size=128):
ctxt_pri = base64.b64decode(msg) # 先将 str 转成 base64
# maxlength = 128
li = []
len_ctxt = len(ctxt_pri)
for i in range(0, len_ctxt, block_size):
input = ctxt_pri[i:i + block_size]
out = rsa_pub.public_decrypt(input, M2Crypto.RSA.pkcs1_padding) # 解密
li.append(out)
return b''.join(li)
```