Loading... 安装包`pip install pycryptodome` ## 生成密钥对 如果是自用的,则需要生成一对秘钥 ```python from Crypto.PublicKey import RSA # def create_rsa_pair(is_save=False): ''' 创建rsa公钥私钥对 :param is_save: default:False 是否保存到本地 :return: public_key, private_key ''' f = RSA.generate(2048) private_key = f.exportKey("PEM") # 生成私钥 public_key = f.publickey().exportKey() # 生成公钥 if is_save: with open("crypto_private_key.pem", "wb") as f: f.write(private_key) with open("crypto_public_key.pem", "wb") as f: f.write(public_key) return public_key, private_key public_key, private_key = create_rsa_pair(is_save=False) print('公钥' , public_key.decode() ) print('私钥' , private_key.decode()) ``` ## 公钥加密、私钥解密 使用公钥对文本进行加密 ```python import base64 from Crypto.Cipher import PKCS1_v1_5 from Crypto.PublicKey import RSA # ------------------------加密------------------------ def rsa_encrypt(text: str, public_key: str): ''' :param text: 代加密文本 :param public_key: 公钥 :return: 加密后结果 同样的文本和公钥加密后结果每次不一样 ''' # 先对公钥进行处理 public_key = [public_key[64 * _: 64 * _ + 64] for _ in range(0 , len(public_key) // 64 + 1)] public_key = [_ for _ in public_key if _] public_key = '''-----BEGIN PUBLIC KEY-----\n''' + '\n'.join(public_key) + '''\n-----END PUBLIC KEY-----''' # 字符串指定编码(转为bytes) public_key = public_key.encode() # 字符串指定编码(转为bytes) text = text.encode('utf-8') # 构建公钥对象 cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key)) # 加密(bytes) text_encrypted = cipher_public.encrypt(text) # base64编码,并转为字符串 text_encrypted_base64 = base64.b64encode(text_encrypted).decode() return text_encrypted_base64 # 加密 text = 'A90122184E03FF98' public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNwj/Y4bZcHtqzxj6fjLxBksX/r3+TXfdR3ZDMujN+Nrnx24YZf1EmV/aUa8qrEfnZvWdyRDAVQtj48RnpJOkNqCqfa41yQ3Vb7NE3B8X97nCdrFLC0Hx6grWq7WI1GVE7MTCbvRG4ExOnheKV0F3TUHFhgAtgmtFoCLAdYmpznQIDAQAB" text_encrypted_base64 = rsa_encrypt(text , public_key) print('密文:' , text_encrypted_base64) ``` 最后修改:2025 年 01 月 04 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏