python的rsa公钥解密方法

示例:

# -*- 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 = base64.b64decode(msg) # 先将str转成base64
    maxlength = 128
    output = ''
    while ctxt_pri:
        input = ctxt_pri[:maxlength]
        ctxt_pri = ctxt_pri[maxlength:]
        out = rsa_pub.public_decrypt(input, M2Crypto.RSA.pkcs1_padding) #解密
        output = output + out
    print('明文:%s'% output)
if __name__ == "__main__":
    prikey_file = './rsa/rsa_private_key.pem'
    pubkey_file = './rsa/rsa_public_key.pem'
    msg = 'Test String.'
    primsg = pri_encrypt(msg, prikey_file)
    pub_decrypt(primsg, pubkey_file)

公钥信息,要有开头和结尾信息:

pkey_str = '''-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2kcrRvxURhFijDoPpqZ/IgPlA
gppkKrek6wSrua1zBiGTwHI2f+YCa5vC1JEiIi9uw4srS0OSCB6kY3bP2DGJagBo
Egj/rYAGjtYJxJrEiTxVs5/GfPuQBYmU0XAtPXFzciZy446VPJLHMPnmTALmIOR5
Dddd1Zklod9IQBMjjwIDAQAB
-----END PUBLIC KEY-----'''

 python base64 decode incorrect padding错误解决方法

个人觉得原因应该是不同的语言/base64库编码规则不太统一的问题。
python中base64串的长度需为4的整数倍,故对长度不为4整数倍的base64串需要用"='补足

如下代码: data为base64编码字符串,经过补齐后的data即可被python base64解码
missing_padding
= 4 - len(data) % 4 if missing_padding: data += b'=' * missing_pad ding
  base64.b64decode(data))

其实一般使用场景是,私钥签名,公钥验证:

https://www.cnblogs.com/hhh5460/p/5243410.html 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    @Author      : xxx
    @Date        : 2019-01-30 14:07
    @Description : 本文件的作用描述
    @File        : login_with_janus.py
"""

import M2Crypto
import base64
import os
import logging
import json

logger = logging.getLogger('operation')

current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pub_key_file = os.path.abspath(os.path.join(current_path, "utils", "jar_file", "janus.pub"))


def decrypt_by_default_public_key(token):
    # 补齐padding,这是因为java加密的长度和python加密的长度不一致
    missing_padding = 4 - len(token) % 4
    if missing_padding:
        token += '=' * missing_padding
    token = token.replace(" ", "+")
    rsa_pub = M2Crypto.RSA.load_pub_key(pub_key_file)
    # 先进行base64解码
    logging.info(len(token))
    cipher = base64.b64decode(token)
    maxlength = 128
    output = ''
    while cipher:
        _input = cipher[:maxlength]
        cipher = cipher[maxlength:]
        out = rsa_pub.public_decrypt(_input, M2Crypto.RSA.pkcs1_padding)  # 解密
        output = output + out.decode()
    user_info = json.loads(output)
    return user_info

这篇文章:https://cloud.tencent.com/developer/article/1039467,没有尝试走通

参考:

https://blog.csdn.net/nyist327/article/details/48496595

https://www.cnblogs.com/yaks/p/6890625.html

原文地址:https://www.cnblogs.com/shengulong/p/10339881.html