python的rsa公钥解密方法

博客内容介绍了Python中RSA公钥解密的使用,包括公钥信息的处理和base64解码问题的解决,重点是公钥解密在签名验证场景的应用。
摘要由CSDN通过智能技术生成

示例:

 

'''
想最快的入门Python吗?请搜索:"泉小朵",来学习Python最快入门教程。
也可以加入我们的Python学习Q群:902936549,送给每一位python的小伙伴教程资料。
'''
# -*- coding: UTF-8 -*-
import M2Crypto
import base64
#私钥加密,公钥解密
def pri_encrypt(msg, file_name):
    rsa_pri = M2Crypto.RSA.load_key(file_name)
    ctxt_pri = rsa_pri.private_encrypt(msg, M2Crypto.RSA.pkcs1_padding) #这里的方法选择加密填充方式,所以在解密的时候 要对应。
    ctxt64_pri = base64.b64encode(ctxt_pri)  #密文是base64 方便保存 encode成str
    print ('密文:%s'% ctxt64_pri)
    return ctxt64_pri
def pub_decrypt_with_pubkeyfile(msg, file_name):
    rsa_pub = M2Crypto.RSA.load_pub_key(file_name)
    pub_decrypt(msg, rsa_pub)
def pub_decrypt_with_pubkeystr(msg, pub_key):
    #将pub_key转成bio对象,再将bio对象转换成公钥对象
    bio = M2Crypto.BIO.MemoryBuffer(pub_key)
    rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio)
    pub_decrypt(msg, rsa_pub)
def pub_decrypt(msg, rsa_pub):
    ctxt_pri 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,用于在计算机通信中提供数据保密。Python中,你可以使用`cryptography`库来实现RSA公钥解密。以下是一个简单的步骤概述: 1. 安装`cryptography`库(如果未安装): ```bash pip install cryptography ``` 2. 导入必要的模块和功能: ```python from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.backends import default_backend ``` 3. 生成RSA密钥对(包括公钥和私钥): ```python private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() ``` 4. 获取公钥(用于解密): ```python public_numbers = public_key.public_numbers() n = public_numbers.n e = public_numbers.e ``` 5. 接收加密后的消息(通常是以Base64或hex编码的形式): ```python encrypted_message = b"your_base64_or_hex_encoded_ciphertext" ``` 6. 解密消息: ```python def encrypt_rsa(message, public_key, e): ciphertext = pow(int.from_bytes(message, byteorder="big"), e, n).to_bytes((n.bit_length() + 7) // 8, byteorder="big") return ciphertext decrypted_message = public_key.decrypt(encrypted_message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) ``` 7. 最后,解密后的消息将是一个字节串,可以转换为字符串: ```python decrypted_message_str = decrypted_message.decode("utf-8") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值