python3.11,如何使用RSA加密解密?
时间: 2023-07-20 13:43:34 浏览: 40
Python 3.11 中可以使用 `pycryptodome` 库来实现 RSA 加密解密。
首先需要安装 `pycryptodome` 库,可以使用以下命令进行安装:
```
pip install pycryptodome
```
接下来,可以使用以下代码实现 RSA 加密解密:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成 RSA 密钥对
key = RSA.generate(2048)
# 加密
message = b"Hello, world!"
cipher = PKCS1_OAEP.new(key.publickey())
encrypted_message = cipher.encrypt(message)
# 解密
cipher = PKCS1_OAEP.new(key)
decrypted_message = cipher.decrypt(encrypted_message)
print("原始消息:", message)
print("加密后消息:", encrypted_message)
print("解密后消息:", decrypted_message)
```
需要注意的是,RSA 加密解密需要使用公钥和私钥,其中公钥可以用来加密数据,私钥则用于解密数据。在上面的代码中,首先使用 `RSA.generate()` 方法生成了一个 2048 位的 RSA 密钥对,然后使用公钥进行加密,私钥进行解密。在加密时,需要使用 `PKCS1_OAEP` 进行填充,以提高安全性。