1. 程式人生 > >Python程式設計:Crypto模組RSA非對稱加密

Python程式設計:Crypto模組RSA非對稱加密

pycrypto模組支援的加密方式

  1. 對稱加密方式:

    AES
    DES
    ARC4

  2. 雜湊值計算:

    MD5
    SHA
    HMAC

  3. 公鑰加密和簽名:

    RSA
    DSA

RSA加密演算法是一種非對稱加密演算法

安裝

pip install pycrypto

程式碼示例

# -*- coding: utf-8 -*-

from pprint import pprint

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import
base64 # rsa演算法生成例項 def get_key(): rsa = RSA.generate(1024, Random.new().read) # master的祕鑰對的生成 private_pem = rsa.exportKey() public_pem = rsa.publickey().exportKey() return { "public_key": public_pem.decode(), "private_key": private_pem.decode() } # 生成的公鑰私鑰對
private_key = """-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDfEQ82qUrto7h4BL3TsA/DFXSdM44cbeY4kPccD7gLGhaZRClz YKIh5zYdfjBGF+0HXfMa1u9b7GNs2AjVIsx8Kx0QLnMfmtkmGWGhOXz/9IDLKJOx 0weKv61gysKItgzVKn2mbLool4R/PQBc3AjDyHw+io1KpVz+3kRTaGs1fQIDAQAB AoGAWB4kFWLA/6k6OOcemd4mC9mQ7HyuOdrMJDJX+5TWDkSrArajbTmSMrRkczgj F71h3BQn8cVQXs695ARfUNrjTbi2Y0LjN7ScK7ExzTLdoMEFw5JsHggJZ0zBQY6w mwOdGfqzA6tZPXgkn+jqEha+CD6GrwnTM1oDGJC/aKG2OmECQQDkO9IhUhFc/PSU 0zvGE6AOcqk5wlOuvMg+oAFHJHJZ9XW7+X/Nx0ZoVDFq/cZQj+46t+fiwUwhdW7l IfCvNGKFAkEA+jRQmWGKrbf1ns4S0SezJvysd5O6otRGJXr+Ex2uDhc39ZTeUsyg kjrLhp8STLMOmql+8g5fghct17EuCX1EmQJBAJz9BNnEkIrst/OSpH/nyeWGOx6u q077LaXd+2MLD9kO/O/Se3V5B9YFa4STkJCjoBMloswXd51gIGpdgSeSmd0CQQCL PrwwcGmWfo+ynqs4PajlpK9zKQMwhYS4bTejedwZOXDKOtx0Ji+i0hfcxwCPMQOK rZPZsIgUxUOdC508aLvZAkBDkHxunCzDm0w4DdTUN7S9YSpVvQEjK/xUQiWaKV12 8QgskhU2DNdYK2NxifnWrKtx3uQmqMxX5aLuJZ4493yr -----END RSA PRIVATE KEY-----"""
public_key = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfEQ82qUrto7h4BL3TsA/DFXSd M44cbeY4kPccD7gLGhaZRClzYKIh5zYdfjBGF+0HXfMa1u9b7GNs2AjVIsx8Kx0Q LnMfmtkmGWGhOXz/9IDLKJOx0weKv61gysKItgzVKn2mbLool4R/PQBc3AjDyHw+ io1KpVz+3kRTaGs1fQIDAQAB -----END PUBLIC KEY----- """ # 公鑰加密 def rsa_encode(message, public_key): rsakey = RSA.importKey(public_key) # 匯入讀取到的公鑰 cipher = PKCS1_v1_5.new(rsakey) # 生成物件 # 通過生成的物件加密message明文,注意,在python3中加密的資料必須是bytes型別的資料,不能是str型別的資料 cipher_text = base64.b64encode( cipher.encrypt(message.encode(encoding="utf-8"))) # 公鑰每次加密的結果不一樣跟對資料的padding(填充)有關 return cipher_text.decode() # 公鑰解密 def rsa_decode(cipher_text, private_key): rsakey = RSA.importKey(private_key) # 匯入讀取到的私鑰 cipher = PKCS1_v1_5.new(rsakey) # 生成物件 # 將密文解密成明文,返回的是一個bytes型別資料,需要自己轉換成str text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR") return text.decode() if __name__ == '__main__': message = "你好,世界!" cipher = rsa_encode(message, public_key) print(cipher) # 輸出是一行,天長了,折行顯示 # vyuQHYhjYrPZK6pJMbbcjb1Q7JTLyRDPIoV7z6OkMQsuBNk0++C # tb3dzo0EvjUhaSOZnE9LjODgEqeTR7I459cDp8izmb970BnKj74 # 6SBtGunK24nudW86ek0JXdYsF5T/IPaphU8d56rdjW+wZv7OfSL # m2HgXLXCI6NbJuJXhg= msg = rsa_decode(cipher, private_key) print(msg) # 你好,世界!