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()
到此這篇關(guān)于python實現(xiàn)對數(shù)據(jù)公鑰加密與私鑰解密的文章就介紹到這了,更多相關(guān)python數(shù)據(jù)加密解密內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實現(xiàn)通過pil模塊對圖片格式進行轉(zhuǎn)換的方法
這篇文章主要介紹了python實現(xiàn)通過pil模塊對圖片格式進行轉(zhuǎn)換的方法,涉及Python中pil模塊的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
conda將python低版本環(huán)境升級到高版本的完整步驟
這篇文章主要給大家介紹了關(guān)于conda將python低版本環(huán)境升級到高版本的完整步驟,包括激活環(huán)境、升級Python版本、驗證升級、處理依賴問題和測試環(huán)境等步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04
解決pycharm導(dǎo)入numpy包的和使用時報錯:RuntimeError: The current Numpy ins
這篇文章主要介紹了解決pycharm導(dǎo)入numpy包的和使用時報錯:RuntimeError: The current Numpy installation (‘D:\\python3.6\\lib\\site-packa的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
python list使用示例 list中找連續(xù)的數(shù)字
這篇文章主要介紹了list中找連續(xù)的數(shù)字的示例,大家參考使用吧2014-01-01

