本代碼引入Pycryptodome基於Python3.50版本編譯庫
1 #!/usr/bin/env python3 2 # coding=utf-8 3 # Author: Luosu201803 4 """ 5 create_rsa_key() - 創建RSA密鑰 6 my_encrypt_and_decrypt() - 測試加密解密功能 7 rsa_sign() & rsa_signverify() - 測試簽名與驗簽功能 8 """ 9 10 from binascii import unhexlify 11 from Crypto.PublicKey import RSA 12 from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5 13 import base64 14 from Crypto.Hash import SHA1 15 from Crypto.Signature import pkcs1_15 16 17 def create_rsa_key(password="123456"): 18 """ 19 創建RSA密鑰,步驟說明: 20 1、從 Crypto.PublicKey 包中導入 RSA,創建一個密碼(此密碼不是RSA秘鑰對) 21 2、生成 1024/2048 位的 RSA 密鑰對(存儲在私鑰文件和公鑰文件) 22 3、調用 RSA 密鑰實例的 exportKey 方法(傳入"密碼"、"使用的 PKCS 標准"、"加密方案"這三個參數)得到私鑰。 23 4、將私鑰寫入磁盤的文件。 24 5、使用方法鏈調用 publickey 和 exportKey 方法生成公鑰,寫入磁盤上的文件。 25 """ 26 key = RSA.generate(1024) 27 encrypted_key = key.exportKey(passphrase=password, pkcs=8,protection="scryptAndAES128-CBC") 28 # encrypted_key = key.exportKey(pkcs=1) 29 print('encrypted_key:',encrypted_key) 30 with open("my_private_rsa_key.pem", "wb") as f: 31 f.write(encrypted_key) 32 with open("my_rsa_public.pem", "wb") as f: 33 f.write(key.publickey().exportKey()) 34 35 36 def encrypt_and_decrypt_test(password="123456"): 37 # 加載私鑰用於加密 38 recipient_key = RSA.import_key( 39 open("my_rsa_public.pem").read() 40 ) 41 cipher_rsa = PKCS1_v1_5.new(recipient_key) 42 #使用base64編碼保存數據方便查看,同樣解密需要base64解碼 43 en_data = base64.b64encode(cipher_rsa.encrypt(b"123456,abcdesd")) 44 print("加密數據信息:",type(en_data),'\n',len(en_data),'\n',en_data) 45 46 # 加載公鑰用於解密 47 encoded_key = open("my_private_rsa_key.pem").read() 48 private_key = RSA.import_key(encoded_key,passphrase=password) 49 cipher_rsa = PKCS1_v1_5.new(private_key) 50 data = cipher_rsa.decrypt(base64.b64decode(en_data), None) 51 print(data) 52 53 def rsa_sign(message,password="123456"): 54 #讀取私鑰信息用於加簽 55 private_key = RSA.importKey(open("my_private_rsa_key.pem").read(),passphrase=password) 56 hash_obj = SHA1.new(message) 57 # print(pkcs1_15.new(private_key).can_sign()) #check wheather object of pkcs1_15 can be signed 58 #base64編碼打印可視化 59 signature = base64.b64encode(pkcs1_15.new(private_key).sign(hash_obj)) 60 return signature 61 62 def rsa_signverify(message,signature): 63 #讀取公鑰信息用於驗簽 64 public_key = RSA.importKey(open("my_rsa_public.pem").read()) 65 #message做“哈希”處理,RSA簽名這么要求的 66 hash_obj = SHA1.new(message) 67 try: 68 #因為簽名被base64編碼,所以這里先解碼,再驗簽 69 pkcs1_15.new(public_key).verify(hash_obj,base64.b64decode(signature)) 70 print('The signature is valid.') 71 return True 72 except (ValueError,TypeError): 73 print('The signature is invalid.') 74 75 if __name__ == '__main__': 76 # create_rsa_key() 77 encrypt_and_decrypt_test() 78 # message = b'Luosu is a Middle-aged uncle.' 79 # signature = rsa_sign(message) 80 # print('signature:',signature) 81 # print(rsa_signverify(message,signature))