Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python rsa加密解密

作者:整整ー世♂陰霾そ   发布日期:2025-03-26   浏览:155

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

# 生成密钥对
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

# 保存私钥和公钥到文件
with open("private.pem", "wb") as f:
    f.write(private_key)
with open("public.pem", "wb") as f:
    f.write(public_key)

# 加载公钥和私钥
with open("public.pem", "rb") as f:
    public_key = RSA.import_key(f.read())
with open("private.pem", "rb") as f:
    private_key = RSA.import_key(f.read())

# 创建加密对象
cipher_public = PKCS1_OAEP.new(public_key)
cipher_private = PKCS1_OAEP.new(private_key)

# 待加密的字符串
message = "Hello, RSA Encryption!"
encoded_message = message.encode()

# 使用公钥加密
encrypted_message = cipher_public.encrypt(encoded_message)
print("Encrypted:", binascii.hexlify(encrypted_message))

# 使用私钥解密
decrypted_message = cipher_private.decrypt(encrypted_message)
print("Decrypted:", decrypted_message.decode())

解释说明:

  1. 生成密钥对:使用 RSA.generate(2048) 生成一个 2048 位的 RSA 密钥对。然后分别导出私钥和公钥。
  2. 保存密钥:将生成的私钥和公钥保存到文件中,以便后续使用。
  3. 加载密钥:从文件中读取并导入公钥和私钥。
  4. 创建加密对象:使用 PKCS1_OAEP 算法创建加密对象,分别用于公钥加密和私钥解密。
  5. 加密消息:将待加密的消息编码为字节串,并使用公钥进行加密。
  6. 解密消息:使用私钥解密加密后的消息,并将其解码回原始字符串。

以上代码展示了如何使用 Python 的 pycryptodome 库进行 RSA 加密和解密操作。请确保已安装该库,可以使用 pip install pycryptodome 进行安装。

上一篇:python list insert

下一篇:python数组转换成字符串

大家都在看

python时间格式

python ord和chr

python中的yield

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站