首先介绍背景:有一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 = """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GDmzokEvlninUFLuUQm2gV3Gtm+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)