Python3对消息进行RSA加密

背景

已知rsa加密公钥字符串,需要将字符串进行转换后,对给定消息内容进行加密。

安装pycryptodome加密库

pip3 install pycryptodome

代码

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
 
# 加密消息体
message = "9ca97d3bdd4d4dc5b21a30bbe6e227b8"
 
# 接口抓取公钥
str_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAbfx4VggVVpcfCjzQ+nEiJ2DLnRg3e2QdDf/m/qMvtqXi4xhwvbpHfaX46CzQznU8l9NJtF28pTSZSKnE/791MJfVnucVcJcxRAEcpPprb8X3hfdxKEEYjOPAuVseewmO5cM+x7zi9FWbZ89uOp5sxjMnlVjDaIczKTRx+7vn2wIDAQAB'

# 加密方法
def encrypt_data(str_key, msg):
    rsakey = RSA.importKey('-----BEGIN PUBLIC KEY-----\n'   # 必须加\n,分为三部分,不换行会报错
                           '%s'
                    	   '\n-----END PUBLIC KEY-----\n' % str_key)
    cipher = PKCS1_v1_5.new(rsakey)     # 创建用于执行PKCS1_v1_5加密或解密的密码
    cipher_text = base64.b64encode(cipher.encrypt(msg.encode('utf-8')))
    return cipher_text.decode('utf-8') 


if __name__=='__main__':
    ret = encrypt_data(str_key, message)
    print(ret)

你可能感兴趣的:(python,rsa)