python调用本地openssl实现私钥和公钥的生成

import subprocess

def generate_key_pair(private_key_file, public_key_file):
    # Generate Private Key
    subprocess.run(['openssl', 'genpkey', '-algorithm', 'RSA', '-out', private_key_file])

    # Generate Public Key from Private Key
    subprocess.run(['openssl', 'pkey', '-in', private_key_file, '-pubout', '-out', public_key_file])

# 文件路径
private_key_file = 'C:\\Users\\Administrator\\Desktop\\123\\private.pem'
public_key_file = 'C:\\Users\\Administrator\\Desktop\\123\\public.pem'

# 生成私钥和公钥
generate_key_pair(private_key_file, public_key_file)

print("Private and Public keys generated successfully.")

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
首先,需要使用 OpenSSL 工具生成一个证书文件,包括公钥私钥: ``` openssl req -x509 -newkey rsa:2048 -keyout example.key -out example.crt -days 365 ``` 这个命令将生成一个 2048 位 RSA 密钥对,并将其用于创建自签名的 X.509 证书,有效期为一年。生成私钥将保存在 `example.key` 文件中,证书将保存在 `example.crt` 文件中。 接下来,我们可以使用 OpenSSL 的命令行工具来提取证书文件中的公钥: ``` openssl x509 -in example.crt -pubkey -noout > example.pub ``` 这个命令将从 `example.crt` 中提取公钥,并将其保存到 `example.pub` 文件中。 现在,我们可以使用 Python 的 Cryptography 模块来加密数据。以下是一个示例脚本: ```python from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import serialization # 读取公钥 with open('example.pub', 'rb') as f: pubkey_bytes = f.read() pubkey = serialization.load_pem_public_key(pubkey_bytes) # 加密数据 message = b'Hello, world!' ciphertext = pubkey.encrypt(message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # 打印密文 print(ciphertext) ``` 这个脚本从 `example.pub` 中读取公钥,并使用 OAEP 填充方案加密了一条消息。密文将打印到控制台上。 最后,我们可以使用 OpenSSL 的命令行工具来解密数据: ``` openssl rsautl -decrypt -inkey example.key -in ciphertext.bin ``` 这个命令将使用 `example.key` 中的私钥来解密 `ciphertext.bin` 文件中的数据。请注意,`ciphertext.bin` 文件中的数据必须是二进制格式的密文,而不是 Base64 编码的字符串。 如果解密成功,您应该会看到原始的明文消息,即 `Hello, world!`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值