python實現(xiàn)對數(shù)據(jù)公鑰加密與私鑰解密
公鑰私鑰的生成
這一部分,使用python生成公鑰與私鑰,然后保存在兩個文件中,其中:
- 公鑰:public_key.pem
- 私鑰:private_key.pem
私鑰密碼是:“my_secret_password”
from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend from loguru import logger def generate_and_save_keys(private_key_filename: str = "private_key.pem", public_key_filename: str = "public_key.pem", password: str = None): """生成RSA公鑰和私鑰對,并將它們保存到本地文件,私鑰可以選擇性地使用密碼加密。 :param private_key_filename: 私鑰保存的文件名。 :param public_key_filename: 公鑰保存的文件名。 :param password: 用于加密私鑰的密碼。如果為None,私鑰將不加密。 """ # 1. 生成密鑰對 private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, # 推薦使用2048位或更高 backend=default_backend() ) public_key = private_key.public_key() # 2. 私鑰加密 if password: encryption_algorithm = serialization.BestAvailableEncryption(password.encode('utf-8')) else: encryption_algorithm = serialization.NoEncryption() # 生成私鑰 private_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=encryption_algorithm ) with open(private_key_filename, "wb") as f: f.write(private_pem) logger.debug(f"私鑰已保存到:{private_key_filename}") # 生成公鑰 public_pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) with open(public_key_filename, "wb") as f: f.write(public_pem) logger.debug(f"公鑰已保存到:{public_key_filename}") if __name__ == "__main__": generate_and_save_keys("my_private_key.pem", "my_public_key.pem", password="my_secret_password")
使用公鑰加密
這一部分隨機生成一個字符串,作為信息的明文內(nèi)容,然后使用公鑰加密:
import os from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from loguru import logger from cryptography.hazmat.backends import default_backend def generate_random_message(length=100): """隨機生成一段信息""" return ''.join(os.urandom(1).hex() for _ in range(length // 2)) def load_public_key(filename): """加載公鑰""" with open(filename, "rb") as f: pem_data = f.read() return serialization.load_pem_public_key(pem_data, backend=default_backend()) def encrypt_data(public_key, message): """使用公鑰加密消息""" encoded_message = message.encode('utf-8') ciphertext = public_key.encrypt( encoded_message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) return ciphertext def main(): send_message = generate_random_message(100) # 要發(fā)送的信息 logger.debug(f"明文:{send_message}") public_key_object = load_public_key("my_public_key.pem") encrypted_msg = encrypt_data(public_key_object, send_message) logger.debug(f"密文: {encrypted_msg.hex()}") # 以十六進制顯示密文 # 這里保存密文 with open("encrypted_message.bin", "wb") as f: f.write(encrypted_msg) if __name__ == "__main__": main()
數(shù)據(jù)加密之后,保存在encrypted_message.bin
文件中
使用私鑰解密
這一部分,使用私鑰對明文數(shù)據(jù)進行解密:
from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from loguru import logger def load_private_key(filename, password=None): """從文件加載私鑰""" with open(filename, "rb") as f: pem_data = f.read() # 密碼需要編碼為字節(jié) password_bytes = password.encode('utf-8') if password else None return serialization.load_pem_private_key( pem_data, password=password_bytes, backend=default_backend() ) def decrypt_data(private_key, ciphertext): """使用私鑰解密密文""" # 使用OAEP填充模式進行解密,與加密時使用的填充模式保持一致 plaintext = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) return plaintext.decode('utf-8') def main(): private_key_object = load_private_key("my_private_key.pem", password="my_secret_password") # 加載私鑰 with open("encrypted_message.bin", "rb") as f: encrypted_msg_from_alice = f.read() logger.debug(f"密文:{encrypted_msg_from_alice.hex()}") decrypted_message = decrypt_data(private_key_object, encrypted_msg_from_alice) logger.debug(f"明文:{decrypted_message}") if __name__ == "__main__": main()
到此這篇關于python實現(xiàn)對數(shù)據(jù)公鑰加密與私鑰解密的文章就介紹到這了,更多相關python數(shù)據(jù)加密解密內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python sklearn CountVectorizer使用詳解
這篇文章主要介紹了Python_sklearn_CountVectorizer使用詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03關于Django框架的關系模型序列化和一對多關系中的序列化解析
序列化的意思是把字典的形式轉(zhuǎn)化成Json格式。當我們展示數(shù)據(jù)的時候需要使用,反序列化的話,就是Json轉(zhuǎn)成字典形式,存儲數(shù)據(jù)時候使用,需要的朋友可以參考下2023-05-05Pyinstaller打包.py生成.exe的方法和報錯總結(jié)
今天小編就為大家分享一篇關于Pyinstaller打包.py生成.exe的方法和報錯總結(jié),小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04DjangoRestFramework 使用 simpleJWT 登陸認證完整記錄
Djangorestframework-simplejwt是Django REST Framework框架的一個jwt插件,使用 python http 工具進行接口測試的方法文中給大家提到,重點給大家分享djangorestframework-simplejwt 使用記錄及登陸認證的完成過程,感興趣的朋友跟隨小編一起看看吧2021-06-06一文教你Python如何使用sqlparse玩轉(zhuǎn)SQL解析
sqlparse?是一個?Python?第三方庫,專門用于解析和格式化?SQL?語句,它提供了強大的?SQL?解析功能,下面小編就來為大家詳細介紹一下它的具體使用吧2025-02-02