Example introduction of M2Crypto RSA encryption and decryption

零下一度
Release: 2017-06-30 13:34:54
Original
6341 people have browsed it

M2Crypto 模块

快速安装:

# 环境centos7.0,提前装好openssl(自行百度安装),windows装不上,暂不考虑了

[root@localhost ~]# pip install m2crypto

# 验证
>>> import M2Crypto
>>>
Copy after login

先做准备工作:

# centos系统上执行以下命令生成公钥和私钥

[root@localhost ~]# openssl genrsa -out key.pem 1024
[root@localhost ~]# openssl rsa -in key.pem -pubout -out pubkey.pem
Copy after login
-----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-----
Copy after login
key.pem
-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhhyVxmY/TU/buuIfwlykV1d5W
g5PRu4Qu14LssRhZH9E9pVbXlGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJq
bivUJCY/5b9zSwVSnDhFfGajLY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQAB-----END PUBLIC KEY-----
Copy after login
pubkey.pem

如何使用

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(&#39;base64&#39;)  # 密文是base64 只能写base64  方便保存 encode成str
    print (&#39;密文:%s&#39;% ctxt64_pri,type(ctxt64_pri))
    return ctxt64_pri

prikey_file = &#39;key.pem&#39;
data = {&#39;name&#39;:&#39;Jefrey&#39;}
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&#39;\x9f}\xfb\x8b\xb1o>\x91\xf0G\xc36\x19Q\xf8\x7f\xaf\xbe\xa2\xee\xf0V\x88\
# xbd[\x1e3\xaf\xf0\xd3\xebu\xa9", <type &#39;str&#39;>)
# (&#39;\xe5\xaf\x86\xe6\x96\x87:jsggmOrVJSbj+qW7dV07elrwwd3zj6rc+rysZ/0LM7thlEuRdGHaIN/QNexWsf/wxAe/HOD8hCb8\ncPVcq9jyI/zO
# Ol26ZV1XNDf3yZpYdP/p2hmC7ERQssvTjUCBRiefffuLsW8+kfBHwzYZUfh/r76i\n7vBWiL1bHjOv8NPrdak=\n&#39;, <type &#39;str&#39;>)
Copy after login

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(&#39;base64&#39;)        # 密文是base64 只能写base64  方便保存 encode成str
    print (&#39;密文:%s&#39;% 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 = &#39;&#39;
    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(&#39;明文:%s&#39;% output,type(output))
    print(&#39;Json:%s&#39;% json.loads(output),type(json.loads(output)))

prikey_file = &#39;key.pem&#39;
pubkey_file = &#39;pubkey.pem&#39;
data = {&#39;name&#39;:&#39;Jefrey&#39;}
message = json.dumps(data)

primsg = pri_encrypt(message,prikey_file)
pub_decrypt(primsg,pubkey_file)

# 打印
# (&#39;\xe6\x98\x8e\xe6\x96\x87:{"name": "Jefrey"}&#39;, <type &#39;str&#39;>)
# ("Json:{u&#39;name&#39;: u&#39;Jefrey&#39;}", <type &#39;dict&#39;>)
Copy after login

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(&#39;base64&#39;)        # 密文是base64 只能写base64  方便保存 encode成str
    # print (&#39;密文:%s&#39;% 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(&#39;明文:%s&#39;% output,type(output))
    print(&#39;Json:%s&#39;% json.loads(output),type(json.loads(output)))

prikey_file = &#39;key.pem&#39;
pubkey_file = &#39;pubkey.pem&#39;
data = {&#39;name&#39;:&#39;Jefrey&#39;}
message = json.dumps(data)

primsg = pri_encrypt(message,prikey_file)
with open(pubkey_file,&#39;r+&#39;) as f:
    pub_key = f.read()
pub_decrypt(primsg,pub_key)

# 打印
# (&#39;\xe6\x98\x8e\xe6\x96\x87:{"name": "Jefrey"}&#39;, <type &#39;str&#39;>)
# ("Json:{u&#39;name&#39;: u&#39;Jefrey&#39;}", <type &#39;dict&#39;>)
Copy after login

小结:上面写的是私钥加密,公钥解密;反过来也一样,public_encrypt公钥加密,private_decrypt私钥解密

The above is the detailed content of Example introduction of M2Crypto RSA encryption and decryption. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!