本文主要是介绍python实现对数据公钥加密与私钥解密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...
公钥私钥的生成
这一部分,使用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"私钥已保存到:{priwww.chinasem.cnvate_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")
使用公钥加密
这一部分随机生成一个字符串,作为信息的明文内容,然后使用公钥加密:
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 imhttp://www.chinasem.cnport 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.reajavascriptd() 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) # 要发送的信息 logger.debug(f"明文:{send_message}") public_key_object = load_public_key("my_public_key.pem") php 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()
数据加密之后,保存在encrypted_message.bin
文件中
使用私钥解密
这一部分,使用私钥对明文数据进行解密:
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): """从文件加android载私钥""" with open(filename, "rb") as f: pem_data = f.read() # 密码需要编码为字节 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实现对数据公钥加密与私钥解密的文章就介绍到这了,更多相关python数据加密解密内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!
这篇关于python实现对数据公钥加密与私钥解密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!