当前位置: 首页 > article >正文

Python 实现非对称加密的 A 端和 B 端软件的详细步骤及代码示例

以下是使用 Python 实现非对称加密的 A 端和 B 端软件的详细步骤及代码示例,并且会说明如何将其打包为可执行的 .exe 文件。这里我们使用 cryptography 库来实现 RSA 非对称加密算法。

1. 安装依赖库

首先,确保你已经安装了 cryptography 库。如果没有安装,可以使用以下命令进行安装:

pip install cryptography

2. 编写 A 端软件代码(a_end.py

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
import base64

def encrypt_message(public_key_pem, plaintext):
    # 加载公钥
    public_key = serialization.load_pem_public_key(
        public_key_pem.encode(),
        backend=default_backend()
    )
    # 加密明文
    ciphertext = public_key.encrypt(
        plaintext.encode(),
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    # 将加密后的字节数据转换为 Base64 编码的字符串,方便复制
    encrypted_base64 = base64.b64encode(ciphertext).decode()
    return encrypted_base64

if __name__ == "__main__":
    # 读取公钥文件
    try:
        with open('public_key.pem', 'r') as f:
            public_key_pem = f.read()
    except FileNotFoundError:
        print("未找到公钥文件 'public_key.pem',请确保文件存在。")
        exit(1)

    # 输入明文
    plaintext = input("请输入要加密的明文: ")

    # 加密明文
    encrypted_text = encrypt_message(public_key_pem, plaintext)

    # 输出可复制的密文
    print("加密后的密文(可复制):")
    print(encrypted_text)

3. 编写 B 端软件代码(b_end.py

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
import base64

def generate_key_pair():
    # 生成私钥
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    # 生成公钥
    public_key = private_key.public_key()

    # 保存私钥到文件
    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    with open('private_key.pem', 'wb') as f:
        f.write(private_pem)

    # 保存公钥到文件
    public_pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    with open('public_key.pem', 'wb') as f:
        f.write(public_pem)

    print("密钥对生成成功,私钥保存为 'private_key.pem',公钥保存为 'public_key.pem'。")

def decrypt_message(private_key_pem, encrypted_base64):
    # 加载私钥
    private_key = serialization.load_pem_private_key(
        private_key_pem.encode(),
        password=None,
        backend=default_backend()
    )
    # 将 Base64 编码的密文转换为字节数据
    ciphertext = base64.b64decode(encrypted_base64)
    # 解密密文
    plaintext = private_key.decrypt(
        ciphertext,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    return plaintext.decode()

if __name__ == "__main__":
    # 生成密钥对
    generate_key_pair()

    # 读取私钥文件
    try:
        with open('private_key.pem', 'r') as f:
            private_key_pem = f.read()
    except FileNotFoundError:
        print("未找到私钥文件 'private_key.pem',请确保文件存在。")
        exit(1)

    # 输入密文
    encrypted_text = input("请输入要解密的密文: ")

    # 解密密文
    decrypted_text = decrypt_message(private_key_pem, encrypted_text)

    # 输出解密后的明文
    print("解密后的明文:")
    print(decrypted_text)

4. 打包为 .exe 文件

我们可以使用 PyInstaller 库将 Python 脚本打包为可执行的 .exe 文件。首先,确保你已经安装了 PyInstaller

pip install pyinstaller
打包 A 端软件

在命令行中,进入包含 a_end.py 文件的目录,然后运行以下命令:

pyinstaller --onefile a_end.py

打包完成后,在 dist 目录下会生成 a_end.exe 文件。

打包 B 端软件

同样,在命令行中进入包含 b_end.py 文件的目录,运行以下命令:

pyinstaller --onefile b_end.py

打包完成后,在 dist 目录下会生成 b_end.exe 文件。

5. 使用说明

  • B 端软件(b_end.exe:运行该软件会生成密钥对,将私钥保存为 private_key.pem,公钥保存为 public_key.pem。然后提示你输入要解密的密文,输入后会输出解密后的明文。
  • A 端软件(a_end.exe:运行该软件前,需要确保 public_key.pem 文件存在。运行后,输入要加密的明文,软件会输出加密后的密文,该密文可以复制并提供给 B 端进行解密。

通过以上步骤,你就可以实现一个简单的非对称加密的 A 端和 B 端软件,并将其打包为可执行的 .exe 文件。


http://www.kler.cn/a/579964.html

相关文章:

  • 电脑维修保养售后服务跟踪软件到哪里下载,佳易王电脑保养维护记录查询可导入图片管理系统操作教程
  • 零成本短视频爆款制造手册
  • gdb调试以及常用相关工具(hexdump\objdump等)
  • U1.【UVA】块问题-The Blocks Problem(补充了pair的使用)
  • c语言笔记 内存管理之栈内存
  • GPT-4 Turbo的重大升级与深远影响
  • Java反射与动态代理:框架设计的基石
  • Android Retrofit 框架注解定义与解析模块深度剖析(一)
  • 利用LLMs准确预测旋转机械(如轴承)的剩余使用寿命(RUL)
  • 【开源】OpenAL、OpenCL、OpenCV 和 OpenGL
  • Git Fast-forward 合并详解:原理、场景与最佳实践
  • 安全保障:渲染101如何守护用户数据?
  • BT-Basic函数之首字母C
  • 数据结构第六节:二叉搜索树(BST)的基本操作与实现
  • C++设计模式-简单工厂模式:从原理、应用、实践指南与常见问题和解决方案深度解析
  • 洛谷P1109 学生分组
  • [Unity3D] 动态立方体贴图系统
  • Android JNI性能优化与字符串加载实践
  • ctf-WEB: 关于 GHCTF Message in a Bottle plus 与 Message in a Bottle 的非官方wp解法
  • 我的GraphQL工具实战:用Apipost提升开发效率的真实体验