rsa 对数据进行加密和解密
#!/usr/bin/env python
# coding=utf-8
"""
pip3 install rsa
"""
import rsa
import base64
# ######### 1. 生成公钥私钥 #########
pub_key_obj, priv_key_obj = rsa.newkeys(1024) # 128 - 11 = 117
# 公钥字符串
pub_key_str = pub_key_obj.save_pkcs1()
pub_key_code = base64.standard_b64encode(pub_key_str)
print(pub_key_code)
# 私钥字符串
priv_key_str = priv_key_obj.save_pkcs1()
priv_key_code = base64.standard_b64encode(priv_key_str)
print(priv_key_code)
# # ######### 2. 用公钥加密 #########
def encrypt(pub_key_code,value):
"""
:param pub_key_code: 公钥
:param value: 要加密的数据
:return: 成功加密的数据
"""
key_str = base64.standard_b64decode(pub_key_code)
pk = rsa.PublicKey.load_pkcs1(key_str)
result = rsa.encrypt(value.encode('utf-8'), pk)
return result
data = encrypt(pub_key_code,'liyp')
print(data)
# # ######### 3. 用私钥解密 #########
def decrypt(priv_key_code,value):
"""
:param priv_key_code: 私钥
:param value: 要解密的数据
:return: 成功解密的数据
"""
key_str = base64.standard_b64decode(priv_key_code)
pk = rsa.PrivateKey.load_pkcs1(key_str)
val = rsa.decrypt(value, pk)
return val
origin = decrypt(priv_key_code,data)
print(origin.decode('utf-8'))
但是对长字符串(超过117位的字符串进行加密)就会出现异常,需要对长字符串进行切割,进行加密然后将加密的数据进行拼接。解密也是如此
# ######### 1. 生成公钥私钥 #########
pub_key_obj, priv_key_obj = rsa.newkeys(1024) # 128 - 11 = 117
# 公钥字符串
pub_key_str = pub_key_obj.save_pkcs1()
pub_key_code = base64.standard_b64encode(pub_key_str)
print(pub_key_code)
# 私钥字符串
priv_key_str = priv_key_obj.save_pkcs1()
priv_key_code = base64.standard_b64encode(priv_key_str)
print(priv_key_code)
value = 'liyp' * 30
# # ######### 2. 用公钥加密 #########
def big_encrypt(pub_key_code,value):
"""
:param pub_key_code: 公钥
:param value: 要加密的数据
:return: 成功加密的数据
"""
big_list = []
key_str = base64.standard_b64decode(pub_key_code)
pk = rsa.PublicKey.load_pkcs1(key_str)
for item in range(0,len(value),117):
chunk = value[item:item+117]
result = rsa.encrypt(chunk.encode('utf-8'), pk)
big_list.append(result)
return b''.join(big_list)
data = big_encrypt(pub_key_code,value)
print(data)
# ######### 3. 用私钥解密 #########
def big_decrypt(priv_key_code,value):
"""
:param priv_key_code: 私钥
:param value: 要解密的数据
:return: 成功解密的数据
"""
big_list = []
key_str = base64.standard_b64decode(priv_key_code)
pk = rsa.PrivateKey.load_pkcs1(key_str)
for item in range(0,len(value),128):
chunk = value[item:item+128]
val = rsa.decrypt(chunk, pk)
big_list.append(val)
return b''.join(big_list)
ret = big_decrypt(priv_key_code,data)
print(ret.decode('utf-8'))