美文网首页
python rsa加解密

python rsa加解密

作者: 明明就_c565 | 来源:发表于2022-06-15 17:45 被阅读0次

方法一

# 非对称RSA加密

def rsa_encrypt(data: bytes, public_key):

    pub_key = RSA.importKey(public_key)

    cipher = PKCS1_cipher.new(pub_key)

    rsa_text = base64.b64encode(cipher.encrypt(data))

    returnrsa_text

# 非对称RSA解密

def rsa_decrypt(data: bytes, private_key):

    # 私钥解密

    pri_key = RSA.importKey(private_key)

    cipher = PKCS1_cipher.new(pri_key)

    back_text = cipher.decrypt(base64.b64decode(data), 0)

    print(back_text.decode('utf-8'))

    returnback_text.decode('utf-8')

方法二

import rsa, base64

private_pem ='E:/a_test/private.pem'

public_pem ='E:/a_test/public.pem'

def gen_pem():

    (pubkey, privkey) = rsa.newkeys(1024)

    print('公钥:', pubkey)

    print('私钥:', privkey)

    # 保存公/私钥

    pub = pubkey.save_pkcs1()

    with open(public_pem, 'wb+')as pubfile:

        pubfile.write(pub)

    pri = privkey.save_pkcs1()

    with open(private_pem, 'wb+')as prifile:

        prifile.write(pri)

    print('公/私钥已保存')

# 加密

def encrypt(str_data):

    print('加密前原始字符串:', str_data)

    message = str_data.encode('utf8')

    with open(public_pem, mode='rb')as privatefile:

        keydata = privatefile.read()

        print('读取公钥', type(keydata), len(keydata), keydata)

    pubkey = rsa.PublicKey.load_pkcs1(keydata)

    crypto = rsa.encrypt(message, pubkey)

    print('加密后长度{}: 密文{}'.format(len(crypto), crypto))

    en = base64.b64encode(crypto)

    print('base64编码后类型:{} 长度:{} 内容:{}'.format(type(en), len(en), en))

    return en

# 解密

def decrypt(cry):

    crypto = base64.b64decode(cry)

    print('base64解码后:', type(crypto), len(crypto), crypto)

    with open(private_pem, mode='rb')as privatefile:

        keydata = privatefile.read()

    privkey = rsa.PrivateKey.load_pkcs1(keydata)

    print(type(privkey), privkey)

    message = rsa.decrypt(crypto, privkey)

    print('解密后:', message)

    print('解密后长度:', len(message))

    return message

参考

http://t.zoukankan.com/zhangxingcomeon-p-14678705.html

https://blog.csdn.net/qq_41621362/article/details/102105642

https://blog.csdn.net/Quentin_nb/article/details/123353053

相关文章

网友评论

      本文标题:python rsa加解密

      本文链接:https://www.haomeiwen.com/subject/tibxvrtx.html