公钥私钥的生成
这一部分,使用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")
使用公钥加密
这一部分随机生成一个字符串,作为信息的明文内容,然后使用公钥加密:
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)  # 要发送的信息
    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()
数据加密之后,保存在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):
    """从文件加载私钥"""
    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数据加密解密内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
            
                                            
                                            
                                            
                                            
                                            
                                            
发表评论