示例:
# -*- 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