M2Crypto RSA加密、解密的实例介绍
程序员文章站
2022-04-16 20:37:39
...
M2Crypto 模块
快速安装:
# 环境centos7.0,提前装好openssl(自行百度安装),windows装不上,暂不考虑了 [root@localhost ~]# pip install m2crypto # 验证 >>> import M2Crypto >>>
先做准备工作:
# centos系统上执行以下命令生成公钥和私钥 [root@localhost ~]# openssl genrsa -out key.pem 1024 [root@localhost ~]# openssl rsa -in key.pem -pubout -out pubkey.pem
-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQDhhyVxmY/TU/buuIfwlykV1d5Wg5PRu4Qu14LssRhZH9E9pVbX lGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJqbivUJCY/5b9zSwVSnDhFfGaj LY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQAB AoGATYKhP9XDNKJa79jD/9Az8qk6bQlzuFV2LJMtECQddiQVSdaVbio3HZvgQ5+q NiO5ttjARfmb+nYZKf9fIQxHOX9GJeepzkvltZJO0LheS0+ZsX2ab62cv8ThUndf yp/thuqHHXt7ERYIHS7CzvzPUQ303OEA9a6WLDaTL/MpjEECQQD5G5cJrEAL1rGF 0ELSRl0YRRRyywmGmc0Wlx0VHCyqG0/5GgmPJmB+8t7k7CtTgRhzStYSmwExzioh ylL3vpgTAkEA58SKxKezIGcuFbCB54yuWEtgauYNrBYauQLC7+Z9d6NjFUrcHO00 1cVJ0cvIK++hvvOrCIUpq/86N8JFUyWYuQJACnH5t1IdrWFnODEvXBnPNYFQBjA1 SguQ6e2ULppr1QYoKE3LMNFvImOUrQyqFGpJWCw/JbCSMEBwy9HsAK9hOQJAIV6v DDmJFPVGMWFEku4yfAv+SeXtugVEu7amEpyBHCSuM3af0ppkrRLG2ioZHBpYk4HJ 8mQZ5+XLoBOcn6geIQJBAIcFTwZETKFs1h6dov3Bp6EPq8zZBABvy7fhCsQk9uX6 6lI0pty9E3KUWGTw4AVp3EwGTc7OqLfiZQTgV65eBcA= -----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhhyVxmY/TU/buuIfwlykV1d5W g5PRu4Qu14LssRhZH9E9pVbXlGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJq bivUJCY/5b9zSwVSnDhFfGajLY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQAB-----END PUBLIC KEY-----
如何使用
1、私钥加密:
import M2Crypto import json # 私钥加密 def pri_encrypt(msg, file_name): rsa_pri = M2Crypto.RSA.load_key(file_name) # 导入秘钥 <M2Crypto.RSA.RSA instance at 0x24da8c0> ctxt_pri = rsa_pri.private_encrypt(msg, M2Crypto.RSA.pkcs1_padding) # 这里的方法选择加密填充方式,所以在解密的时候 要对应。 print(ctxt_pri,type(ctxt_pri)) ctxt64_pri = ctxt_pri.encode('base64') # 密文是base64 只能写base64 方便保存 encode成str print ('密文:%s'% ctxt64_pri,type(ctxt64_pri)) return ctxt64_pri prikey_file = 'key.pem' data = {'name':'Jefrey'} message = json.dumps(data) pri_encrypt(message,prikey_file) # 打印 # ("\x8e\xc8 \x98\xea\xd5%&\xe3\xfa\xa5\xbbu];zZ\xf0\xc1\xdd\xf3\x8f\xaa\xdc\xfa\xbc\xacg\xfd\x0b3\xbba\x94K\x91ta\xda # \xdf\xd05\xecV\xb1\xff\xf0\xc4\x07\xbf\x1c\xe0\xfc\x84&\xfcp\xf5\\\xab\xd8\xf2#\xfc\xce:]\xbae]W47\xf7\xc9\x9aXt\xff\ # xe9\xda\x19\x82\xecDP\xb2\xcb\xd3\x8d@\x81F'\x9f}\xfb\x8b\xb1o>\x91\xf0G\xc36\x19Q\xf8\x7f\xaf\xbe\xa2\xee\xf0V\x88\ # xbd[\x1e3\xaf\xf0\xd3\xebu\xa9", <type 'str'>) # ('\xe5\xaf\x86\xe6\x96\x87:jsggmOrVJSbj+qW7dV07elrwwd3zj6rc+rysZ/0LM7thlEuRdGHaIN/QNexWsf/wxAe/HOD8hCb8\ncPVcq9jyI/zO # Ol26ZV1XNDf3yZpYdP/p2hmC7ERQssvTjUCBRiefffuLsW8+kfBHwzYZUfh/r76i\n7vBWiL1bHjOv8NPrdak=\n', <type 'str'>)
2、公钥解密(文件路径):
import M2Crypto import json # 私钥加密 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) # 进行加密 pkcs1_padding加密填充方式,解密的时候要对应。 ctxt64_pri = ctxt_pri.encode('base64') # 密文是base64 只能写base64 方便保存 encode成str print ('密文:%s'% ctxt64_pri,type(ctxt64_pri)) return ctxt64_pri # 公钥解密传入文件路径 def pub_decrypt(msg, file_name): rsa_pub = M2Crypto.RSA.load_pub_key(file_name) ctxt_pri = msg.decode("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('明文:%s'% output,type(output)) print('Json:%s'% json.loads(output),type(json.loads(output))) prikey_file = 'key.pem' pubkey_file = 'pubkey.pem' data = {'name':'Jefrey'} message = json.dumps(data) primsg = pri_encrypt(message,prikey_file) pub_decrypt(primsg,pubkey_file) # 打印 # ('\xe6\x98\x8e\xe6\x96\x87:{"name": "Jefrey"}', <type 'str'>) # ("Json:{u'name': u'Jefrey'}", <type 'dict'>)
3、公钥解密(字符串):
import M2Crypto import json # 私钥加密 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) # 进行加密 pkcs1_padding加密填充方式,解密的时候要对应。 ctxt64_pri = ctxt_pri.encode('base64') # 密文是base64 只能写base64 方便保存 encode成str # print ('密文:%s'% ctxt64_pri,type(ctxt64_pri)) return ctxt64_pri # 公钥解密传入字符串 def pub_decrypt(msg, pub_key): bio = M2Crypto.BIO.MemoryBuffer(pub_key) rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio) ctxt_pri = msg.decode("base64") # 先将str转成base64 output = rsa_pub.public_decrypt(ctxt_pri, M2Crypto.RSA.pkcs1_padding) #解密 print('明文:%s'% output,type(output)) print('Json:%s'% json.loads(output),type(json.loads(output))) prikey_file = 'key.pem' pubkey_file = 'pubkey.pem' data = {'name':'Jefrey'} message = json.dumps(data) primsg = pri_encrypt(message,prikey_file) with open(pubkey_file,'r+') as f: pub_key = f.read() pub_decrypt(primsg,pub_key) # 打印 # ('\xe6\x98\x8e\xe6\x96\x87:{"name": "Jefrey"}', <type 'str'>) # ("Json:{u'name': u'Jefrey'}", <type 'dict'>)
小结:上面写的是私钥加密,公钥解密;反过来也一样,public_encrypt公钥加密,private_decrypt私钥解密;
以上就是M2Crypto RSA加密、解密的实例介绍的详细内容,更多请关注其它相关文章!