python3使用Pycrypto进行RSA加解密

from Cryptodome.Cipher import AES
from Cryptodome import Random
from binascii import b2a_hex
from Cryptodome.PublicKey import RSA
import base64
from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

def encrypt(public_key, message):
    message_bype=message.encode(encoding="utf-8")
    cipher = Cipher_pkcs1_v1_5.new(public_key)
    dd=cipher.encrypt(message_bype)
    cipher_text = base64.b64encode(dd)
    return cipher_text

# rsa解密
def decrypt(rsakey, encrypt_text):
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    return cipher.decrypt(base64.b64decode(encrypt_text), '')

def test(request):
    # 生成rsa密钥
    rsa_obj = RSA.generate(1024)
    private_pem = rsa_obj.exportKey()  # pem格式输出私钥
    public_key = rsa_obj.publickey()
    public_pem = public_key.exportKey()  # 将公钥输出成pem格式
    print("公钥",public_pem)
    msg = 'hello world' 
    encrypt_text = encrypt(public_key,msg)  #公钥加密
    print("公钥加密",encrypt_text)
    text = decrypt(rsa_obj, encrypt_text)  #私钥解密
    print("私钥解密",text)

    msg="大家好,我们是超级市场"
    encrypt_text = encrypt(public_key, msg)  # 公钥加密
    print("公钥加密0", encrypt_text)
    text = decrypt(rsa_obj, encrypt_text)  # 私钥解密
    print("私钥解密0", text.decode('utf-8'))

python2原文引用自https://www.cnblogs.com/lilinwei340/p/6754652.html

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