Python 使用 RSA 公钥加密数据
作者:互联网
安装 pycryptodome 库
pip install pycryptodome
使用 RSA 公钥加密数据
import base64
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from Crypto.PublicKey import RSA
def _encrpt(string, public_key):
rsakey = RSA.importKey(public_key) # 读取公钥
cipher = Cipher_pksc1_v1_5.new(rsakey)
# 因为encryptor.encrypt方法其内部就实现了加密再次Base64加密的过程,所以这里实际是通过下面的1和2完成了JSEncrypt的加密方法
encrypt_text = cipher.encrypt(string.encode()) # 1.对账号密码组成的字符串加密
cipher_text_tmp = base64.b64encode(encrypt_text) # 2.对加密后的字符串base64加密
return cipher_text_tmp.decode()
# 使用公钥加密
def gen_body(pwd, public_key=None):
'''根据账号密码生成请求的body然后调用_encrpt方法加密'''
if not public_key: public_key = '输入公钥' # 输入对应的公钥
key = '-----BEGIN PUBLIC KEY-----\n' + public_key + '\n-----END PUBLIC KEY-----'
encrypt_res = _encrpt(pwd, key)
return str_replace(encrypt_res)
# 文本替换
def str_replace(encoder):
result = encoder.replace("+","-")
result = result.replace("/","_")
result = result.replace("=",",")
return result
if __name__ == '__main__':
PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANunOZNi98lS7GiaUdnFJbzVy5oxsLqsTetCRfp2pE3sD3pWGBa1xjqrU/+9VtcJC6KvHel0IMSmlfoCxXvlKQkCAwEAAQ=="
print(gen_body("这是 public 测试 password",PUBLIC_KEY)) #输入要加密的密码```
问题解决
- 报 ModuleNotFoundError: No module named 'Crypto' 错误
标签:公钥,加密,Python,RSA,result,key,encrypt,public 来源: https://www.cnblogs.com/kmswilliam/p/16408265.html