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'))
