php-python2-python3跨语言rsa公钥加密私钥解密

首先介绍背景:有一php项目,只提供了php加解密接口,因业务需求,需要提供python版本加密接口。

注意:

1、加密方式:使用Crypto包,RSA/1024bit KEY,实例加密使用公钥加密,私钥解密,反过来原理一样
2、加密填充方式:OPENSSL_PKCS1_PADDING
3、python3 PKCS1_v1_5.new.encrypt 只接受byte数据
4、切割加密解密,原因自行百度,可参考:https://blog.csdn.net/orangleliu/article/details/72964948

php代码如下:

//请求内容结构体
$data=array(
        "fromname"=>"告警",
        "html"=>"恢复, 服务器: 192.168.2.111 utilization more than 90% bj,故障:IO 已恢复!",
        "mail"=>"XXXX@qq.com",
        "subject"=>"现网警告,请尽快处理"
        );
//通讯密钥公钥
$keyb_public="-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlRrb6KwJRTx8nvApuMX3f3QCH
qeHkvbxgMJuhHkWOwmD8su1k+OK8c1WHd41C+gkeQr2tVLmEl4VKPKcUEkCTOOBT
NVxSEZf0+xw/WqVqCdqRZGst444Xa6xCVjcuAsIdUjNNCZULLnvPcCTmb9W869BI
C3L5SGvta/Hq/izSswIDAQAB
-----END PUBLIC KEY-----";
$pu_key=openssl_pkey_get_public($keyb_public);
$encrypted="";

//函数:公钥加密代码
function encrypt($originalData,$rsaPublicKey)
        {
        $crypto = '';
        //分割加密
        foreach (str_split($originalData, 117) as $chunk) {
            $test=openssl_public_encrypt($chunk, $encryptData, $rsaPublicKey,OPENSSL_PKCS1_PADDING);
                        if(!$test) echo "<br>Encrypt faild:".openssl_error_string();
            echo "<br>".$encryptData;
            $crypto .= $encryptData;
        }
        return $crypto;
    }

//utf-8编码 json 格式化
$text="msg=".json_encode($data,JSON_UNESCAPED_UNICODE);
//加密
$encrypted=encrypt($text,$pu_key);
//base64 和urlencode 加密
$data=urlencode(base64_encode($encrypted));
echo "<br>加密后数据=".$data;

python2.7加解密版本,

yum install -y python-devel
pip2 install pycrypto

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Description:

# @Time    : 2019/8/12 23:07
# @Author  : hubo
# @Email   : hagic.hhj@gmail.com
"""
python2.7
"""
import base64,json
from Crypto.PublicKey import RSA as rsa
from Crypto.Cipher import PKCS1_v1_5
from urllib import quote, unquote

pub_key_str = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRUUJTzy4Nm9js/gbfE2K4QjIP
Lo+9a9s+xaK3mlyWHPgdTWfAFdqcTI2Rv8jysqE7OdAzl/lOO5j0d1yVyq/sUkc9
/43A8xyyC1cxmIFvWLYhS5cyKfxy5lrW32ynMcH17OJSJ5fSKLAHd2kZ7npnI9C7
DImkPmwbuLLGrbo1ZwIDAQAB
-----END PUBLIC KEY-----"""

priv_key_str = """-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANFRQlPPLg2b2Oz+
Bt8TYrhCMg8uj71r2z7ForeaXJYc+B1NZ8AV2pxMjZG/yPKyoTs50DOX+U47mPR3
XJXKr+xSRz3/jcDzHLILVzGYgW9YtiFLlzIp/HLmWtbfbKcxwfXs4lInl9IosAd3
aRnuemcj0LsMiaQ+bBu4ssatujVnAgMBAAECgYEAyhvcH3B810cUPkFKATuGpsPD
8kTTJeNu3z2V0BKMM6XlLOYAt8hiPWjtiT3VmgJBDB7Wmfq0DoYdOm/GRhxfn+DV
j/kDbXIlEe0jQkwDmCgLpN0rIGaqnY22yeEkfTHyLnwnRNu0HMbOmNsY27HolkjS
2iANzJuw2Cnt8kx38AECQQDumFy4nZnGZWNJ0PV15i1a03XJH+bdopmGj+k4LErU
dcDQvdd/ZvyFAiK7VNgAxoKCmP1d09BP9FDxW9RBHgTnAkEA4JYmisJtxUUs5Oji
CVaxmczeetP+px68NnqBVLrEvrdUtDsAHU//zEhWGWkGJA6b3puayD7viDUr0861
mjO7gQJAR08MLzUTF4OH2DD2m6UOmx2mD1VUh5soLVpnhp1eQ/9pgDms5WvfPtVz
ke96m0i5CtU0rE047hyD8I7Uch3JswJAQQ8eISpLtE7iv3k7KatkjYJMnNZWucDs
kveQCaSFJB5lukQxN0yadGosDvZeogldW/JFt2aL6zBD/vqtnvsHgQJBAMYwWXEY
tH/dBGao8NGDmzokEvlninUFLuUQm2gV3Gtm+KiJ9vsqFeuEMhcwby1BI0FHUDOW
Y+U95ipVY+0cMRc=
-----END RSA PRIVATE KEY-----"""


def encrypt(pub_key_str, msg):
    pubobj = rsa.importKey(pub_key_str)
    pubobj = PKCS1_v1_5.new(pubobj)
    buffer = []
    while msg:  # 分段进行加密
        input = msg[:117]
        tmp = pubobj.encrypt(input)
        buffer.append(tmp)
        msg = msg[117:]
    data = base64.b64encode(''.join(buffer))
    return data

def decrypt(priv_key_str, msg):
    privobj = rsa.importKey(priv_key_str)
    privobj = PKCS1_v1_5.new(privobj)
    ctxt_pri = base64.b64decode(msg)  # 先将str转成base64
    buffer = []
    while ctxt_pri:
        input = ctxt_pri[:128]
        ctxt_pri = ctxt_pri[128:]
        tmp = privobj.decrypt(input, 'decrypt error')
        buffer.append(tmp)
    return ''.join(buffer)


if __name__ == "__main__":
    salt = "msg="
    data = {
            "subject": "现网警告,请尽快处理",
            "fromname": "告警",
            "mail": "XXXX@qq.com",
            "html": "恢复, 服务器: 192.168.2.111 utilization more than 90% bj,故障:IO 已恢复!"
    }
    ##utf-8格式化字符串,
    msg = salt + json.dumps(data, ensure_ascii=False, encoding='utf-8')
    ##去掉json格式化字典后,字典元素之前的空格
    msg = msg.replace('": ', '":').replace(', "', ',"').replace(", {", ",{")
    print(msg)
    #加密
    mmsg = encrypt(pub_key_str, msg)
    enData = quote(mmsg)
    print("加密:%s" % enData)
    #解密
    mmsg = unquote(enData)
    dmsg = decrypt(priv_key_str, mmsg)
    print("解密:%s" % dmsg)

python3.6版本

pip3 install pycryptodome

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Description:

# @Time    : 2019/8/12 23:07
# @Author  : hubo
# @Email   : hagic.hhj@gmail.com

import base64,json
from Crypto.PublicKey import RSA as rsa
from Crypto.Cipher import PKCS1_v1_5
from urllib.parse import quote, unquote

pub_key_str = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRUUJTzy4Nm9js/gbfE2K4QjIP
Lo+9a9s+xaK3mlyWHPgdTWfAFdqcTI2Rv8jysqE7OdAzl/lOO5j0d1yVyq/sUkc9
/43A8xyyC1cxmIFvWLYhS5cyKfxy5lrW32ynMcH17OJSJ5fSKLAHd2kZ7npnI9C7
DImkPmwbuLLGrbo1ZwIDAQAB
-----END PUBLIC KEY-----"""

priv_key_str = """-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANFRQlPPLg2b2Oz+
Bt8TYrhCMg8uj71r2z7ForeaXJYc+B1NZ8AV2pxMjZG/yPKyoTs50DOX+U47mPR3
XJXKr+xSRz3/jcDzHLILVzGYgW9YtiFLlzIp/HLmWtbfbKcxwfXs4lInl9IosAd3
aRnuemcj0LsMiaQ+bBu4ssatujVnAgMBAAECgYEAyhvcH3B810cUPkFKATuGpsPD
8kTTJeNu3z2V0BKMM6XlLOYAt8hiPWjtiT3VmgJBDB7Wmfq0DoYdOm/GRhxfn+DV
j/kDbXIlEe0jQkwDmCgLpN0rIGaqnY22yeEkfTHyLnwnRNu0HMbOmNsY27HolkjS
2iANzJuw2Cnt8kx38AECQQDumFy4nZnGZWNJ0PV15i1a03XJH+bdopmGj+k4LErU
dcDQvdd/ZvyFAiK7VNgAxoKCmP1d09BP9FDxW9RBHgTnAkEA4JYmisJtxUUs5Oji
CVaxmczeetP+px68NnqBVLrEvrdUtDsAHU//zEhWGWkGJA6b3puayD7viDUr0861
mjO7gQJAR08MLzUTF4OH2DD2m6UOmx2mD1VUh5soLVpnhp1eQ/9pgDms5WvfPtVz
ke96m0i5CtU0rE047hyD8I7Uch3JswJAQQ8eISpLtE7iv3k7KatkjYJMnNZWucDs
kveQCaSFJB5lukQxN0yadGosDvZeogldW/JFt2aL6zBD/vqtnvsHgQJBAMYwWXEY
tH/dBGao8NGDmzokEvlninUFLuUQm2gV3Gtm+KiJ9vsqFeuEMhcwby1BI0FHUDOW
Y+U95ipVY+0cMRc=
-----END RSA PRIVATE KEY-----"""


def encrypt(pub_key_str, msg):
    pubobj = rsa.importKey(pub_key_str)
    pubobj = PKCS1_v1_5.new(pubobj)
    data = b''
    while msg:  # 分段进行加密
        input = msg[:117]
        tmp = pubobj.encrypt(input)
        data = data + tmp
        msg = msg[117:]
    data = base64.b64encode(data)
    return data

def decrypt(priv_key_str, msg):
    privobj = rsa.importKey(priv_key_str)
    privobj = PKCS1_v1_5.new(privobj)
    ctxt_pri = base64.b64decode(msg)  # 先将str转成base64
    data = b''
    while ctxt_pri:
        input = ctxt_pri[:128]
        ctxt_pri = ctxt_pri[128:]
        tmp = privobj.decrypt(input, 'decrypt error')
        data = data + tmp
    return data


if __name__ == "__main__":
    salt = "msg="
    data = {
            "subject": "现网警告,请尽快处理",
            "fromname": "告警",
            "mail": "592690719@qq.com",
            "html": "恢复, 服务器: 192.168.2.111 utilization more than 90% bj,故障:IO 已恢复!",
            "templateid": 1
    }
    ##utf-8格式化字符串,
    msg = salt + json.dumps(data, ensure_ascii=False)
    ##去掉json格式化字典后,字典元素之前的空格
    msg = msg.replace('": ', '":').replace(', "', ',"').replace(", {", ",{")
    print(msg)
    ##python3  PKCS1_v1_5.new.encrypt 只接受byte数据
    msg = bytes(msg, encoding="utf8")
    #加密
    mmsg = encrypt(pub_key_str, msg)
    enData = quote(mmsg)
    print("加密:%s" % enData)
    #解密
    mmsg = unquote(enData)
    dmsg = decrypt(priv_key_str, mmsg)
    dmsg = dmsg.decode("utf8")
    print("解密:%s" % dmsg)

补充下python2下用M2Crypto包加解密方法

yum install -y python-devel
pip2 install M2Crypto

# -*- coding: UTF-8 -*-
import M2Crypto
import base64
import sys
import json
from urllib import quote, unquote

def encrypt_pub(msg, file):
    rsaPub = M2Crypto.RSA.load_pub_key(file)
    buffer = []
    while msg:  # 分段进行加密
        input = msg[:117]
        tmp = rsaPub.public_encrypt(input, M2Crypto.RSA.pkcs1_padding)  # 加密填充方式为pkcs1_padding
        buffer.append(tmp)
        msg = msg[117:]
    data = base64.b64encode(''.join(buffer))
    return data



def decrypt_pub(msg, file):
    rsaPri = M2Crypto.RSA.load_key(file)
    ctxt_pri = msg.decode("base64")  # 先将str转成base64
    buffer = []
    while ctxt_pri:
        input = ctxt_pri[:128]
        ctxt_pri = ctxt_pri[128:]
        tmp = rsaPri.private_decrypt(input, M2Crypto.RSA.pkcs1_padding)
        buffer.append(tmp)
    return ''.join(buffer)


if __name__ == "__main__":
    prikey_file = sys.path[0] + '/rsa'
    pubkey_file = sys.path[0] + '/rsa.pub'
    salt = "msg="
    data = {
            "subject": "现网警告,请尽快处理",
            "fromname": "告警",
            "mail": "592690719@qq.com",
            "html": "恢复, 服务器:xxxxxxxxy.z utilization more than 90% bj,故障:IO 已恢复!",
            "templateid": 1
    }
    msg = salt + json.dumps(data, ensure_ascii=False, encoding='utf-8')
    msg = msg.replace('": ', '":').replace(', "', ',"').replace(", {", ",{")
    print(msg)
    enData = encrypt_pub(msg, pubkey_file)
    enData = quote(enData)
    print("加密:%s" % enData)
    data = decrypt_pub(unquote(enData), prikey_file)
    print("解密:%s" % data)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350