非对称加密解密
一. 加密代码
#私钥加密 公钥解密
import rsa import base64 # #生成公钥私钥 pub_key_obj, priv_key_obj = rsa.newkeys(1024) pub_key_str = pub_key_obj.save_pkcs1() pub_key_code = base64.standard_b64encode(pub_key_str) priv_key_str = priv_key_obj.save_pkcs1() priv_key_code = base64.standard_b64encode(priv_key_str) print(pub_key_code) print(priv_key_code) #加密 def encrypt(values): key_str = base64.standard_b64decode(pub_key_code) pk = rsa.PublicKey.load_pkcs1(key_str) val = rsa.encrypt(values.encode('utf-8'),pk) return val ret = encrypt('hhhhhh') print(ret) def decrypt(values): key_str = base64.standard_b64decode(priv_key_code) pk = rsa.PrivateKey.load_pkcs1(key_str) val = rsa.decrypt(values,pk) return val ret1 = decrypt(ret) print(ret1)
二. 实用代码
import rsa import base64 # #生成公钥私钥 pub_key_obj, priv_key_obj = rsa.newkeys(1024) pub_key_str = pub_key_obj.save_pkcs1() pub_key_code = base64.standard_b64encode(pub_key_str) priv_key_str = priv_key_obj.save_pkcs1() priv_key_code = base64.standard_b64encode(priv_key_str) print(pub_key_code) print(priv_key_code) #加密 def encrypt(values): length = len(values) i,more = divmod(length,117) if more: i+= 1 data_list = [] for j in range(0,i): data = values[117*j:(j+1)*117] key_str = base64.standard_b64decode(pub_key_code) pk = rsa.PublicKey.load_pkcs1(key_str) val = rsa.encrypt(data.encode('utf-8'),pk) data_list.append(val) return b''.join(data_list) ret = encrypt('hhhh' * 1000) print(ret) def decrypt(values): length = len(values) i, more = divmod(length, 128) if more: i += 1 data_list = [] for j in range(0, i): data = values[128 * j:(j + 1) * 128] key_str = base64.standard_b64decode(priv_key_code) pk = rsa.PrivateKey.load_pkcs1(key_str) val = rsa.decrypt(data,pk) data_list.append(val.decode('utf-8')) return ''.join(data_list) ret1 = decrypt(ret) print(ret1)
We are down, but not beaten. tested but not defeated.