Windows 10 Python M2Crypto RSA私钥加密 ,公钥解密

前段时间,在进行某个产品测试的时候,需要使用到私钥加密,公钥解密技术。为了能够使用M2Crypto模块来进行加密,安装路上,走了不少弯路,折腾了很久。
下面将M2Crypto模块的安装过程,记录在此:
1 一直使用的是Python 3.6.1 ,于是很理所当然使用 pip install M2Crypto
但是报错:
Windows 10 Python M2Crypto RSA私钥加密 ,公钥解密
文章图片

2.这种方法行不通,于是想着去下载 M2Crypto 模块的安装文件,解压,进入到待安装的文件夹路径下,使用 python setup.py install
仍然报上面的错。

  1. 试了各种方法,安装VC++插件,不得而终。
    后来才得知,因为M2Crypto 在Python3.x不再适用了。
    于是另外安装了Python2.7 ,不再报错,但是在运行脚本时,报错:
    Windows 10 Python M2Crypto RSA私钥加密 ,公钥解密
    文章图片

    从报错信息看,是因为OPENSSL link链接失败。
  2. M2Crypto 是最完整的为 Python 包装 OpenSSL 的 RSA,DSA,DH,EC,HMACs,消息摘要,对称密码算法(包括AES)的一个库工具。
    并且,M2Crypto需要安装openssl , swig .
    下载http://www.swig.org/ 安装swig
    解压后,将swig.exe文件所在的目录添加到环境变量中。安装完成后,检查是否安装成功
    Windows 10 Python M2Crypto RSA私钥加密 ,公钥解密
    文章图片

    5.安装openssl,待安装成功后,方可进行RSA 私钥加密,公钥解密了~~
    测试脚本如下:
#encoding=utf-8 import urllib from urllib import urlencode import M2Crypto import json import parse import requests # 私钥加密 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 = ctxt_pri.encode(u'base64')# 密文是base64 只能写base64方便保存 encode成str 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, file_name): rsa_pub = M2Crypto.RSA.load_pub_key(file_name) ctxt_pri = msg.decode(u"base64")# 先将str转成base64 #分块解密 maxlength = 128# 128位 output = '' while ctxt_pri: input = ctxt_pri[:128] ctxt_pri = ctxt_pri[128:] out = rsa_pub.public_decrypt(input, M2Crypto.RSA.pkcs1_padding)# 解密 output = output + out print (u'解密后的明文:%s' % output) if __name__ == '__main__': prifile='./private.pem'#私钥文件 pubfile='./public.pem'#公钥文件 test_data = https://www.it610.com/article/{"data": {"user_id": "tester"}, "timestamp": 1565860950} primsg=pri_encrypt(test_data,prifile) print "私钥加密后得到的结果是:",primsg DecryptResult=pub_decrypt(primsg,pubfile) print "公钥解密后得到的结果是:",DecryptResult

运行后得到:
pWDWBnd9OBYLPqW2BiZCX6qYjJPH6i2X3JKR70qa6O0iAskN831R4lFY2FsWVDjlq6pcAFzSedZd45n2FRBHtSgNhumafUEVI9sq49tvXTLTY9UwbjvGzF0DqT5HF7IXWIGAq8KsnODOkpOPsxAottqM17tjfy98qNpPBI3D0A
检验私钥加密以及公钥解密是否正确,可以通过此在线工具验证:
http://tool.chacuo.net/cryptrsaprikey
注意:并且需要做到:对于同一个字符串,进行RSA 私钥加密后所得到的字符串是固定的,不会改变的。也可以通过公钥解密检验是否是被加密的数据。
到此为止,通过不同的产品的接口测试,经历了 RSA 公钥加密,私钥解密,RSA 私钥加密,公钥解密,AES加密解密,HAMC SHA256 签名,并且都使用python脚本实现。
在这期间,被折腾的主要是加密模块的安装,比如pycrypto 模块,M2Crypto模块等的安装很麻烦。
参考:https://blog.csdn.net/nyist327/article/details/48496595
参考:https://blog.csdn.net/tty521/article/details/79518373
【Windows 10 Python M2Crypto RSA私钥加密 ,公钥解密】更多,可以加好友
Windows 10 Python M2Crypto RSA私钥加密 ,公钥解密
文章图片


    推荐阅读