Python開發【模組】:M2Crypto RSA加密、解密,m2cryptorsa

來源:互聯網
上載者:User

Python開發【模組】:M2Crypto RSA加密、解密,m2cryptorsa
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/buuIfwlykV1d5Wg5PRu4Qu14LssRhZH9E9pVbXlGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJqbivUJCY/5b9zSwVSnDhFfGajLY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQABAoGATYKhP9XDNKJa79jD/9Az8qk6bQlzuFV2LJMtECQddiQVSdaVbio3HZvgQ5+qNiO5ttjARfmb+nYZKf9fIQxHOX9GJeepzkvltZJO0LheS0+ZsX2ab62cv8ThUndfyp/thuqHHXt7ERYIHS7CzvzPUQ303OEA9a6WLDaTL/MpjEECQQD5G5cJrEAL1rGF0ELSRl0YRRRyywmGmc0Wlx0VHCyqG0/5GgmPJmB+8t7k7CtTgRhzStYSmwExziohylL3vpgTAkEA58SKxKezIGcuFbCB54yuWEtgauYNrBYauQLC7+Z9d6NjFUrcHO001cVJ0cvIK++hvvOrCIUpq/86N8JFUyWYuQJACnH5t1IdrWFnODEvXBnPNYFQBjA1SguQ6e2ULppr1QYoKE3LMNFvImOUrQyqFGpJWCw/JbCSMEBwy9HsAK9hOQJAIV6vDDmJFPVGMWFEku4yfAv+SeXtugVEu7amEpyBHCSuM3af0ppkrRLG2ioZHBpYk4HJ8mQZ5+XLoBOcn6geIQJBAIcFTwZETKFs1h6dov3Bp6EPq8zZBABvy7fhCsQk9uX66lI0pty9E3KUWGTw4AVp3EwGTc7OqLfiZQTgV65eBcA=-----END RSA PRIVATE KEY-----
key.pem
-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhhyVxmY/TU/buuIfwlykV1d5Wg5PRu4Qu14LssRhZH9E9pVbXlGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJqbivUJCY/5b9zSwVSnDhFfGajLY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQAB-----END PUBLIC KEY-----
pubkey.pem

 

如何使用

1、私密金鑰加密:

import M2Cryptoimport 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_priprikey_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 M2Cryptoimport 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 M2Cryptoimport 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私密金鑰解密

  

 

  

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.