python实现RSA加密
时间: 2023-07-12 09:19:39 浏览: 105
RSA 是一种非对称加密算法,可以用于加密和解密数据。以下是 Python 中使用 RSA 加密算法的示例代码:
首先,需要安装 `pycryptodome` 库来生成 RSA 密钥对和进行加密解密操作。可以使用以下命令安装:
```
pip install pycryptodome
```
接下来,我们可以使用以下代码生成 RSA 密钥对:
```python
from Crypto.PublicKey import RSA
# 生成 2048 位的 RSA 密钥对
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)
```
上述代码将生成一个 2048 位的 RSA 密钥对,并将私钥和公钥保存到 `private.pem` 和 `public.pem` 文件中。
接下来,我们可以使用以下代码来进行加密和解密操作:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 加载公钥和私钥
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 = PKCS1_OAEP.new(public_key)
encrypted_data = cipher.encrypt(b'Hello, world!')
# 解密数据
cipher = PKCS1_OAEP.new(private_key)
decrypted_data = cipher.decrypt(encrypted_data)
print(decrypted_data.decode())
```
上述代码将加载保存在 `public.pem` 和 `private.pem` 文件中的公钥和私钥,并使用公钥加密一条消息,然后使用私钥解密该消息。
需要注意的是,RSA 加密算法有一个最大加密数据的长度限制。因此,如果要加密的数据长度超过了限制,可以考虑使用对称加密算法来对数据进行加密,然后再使用 RSA 加密对称加密算法的密钥。
阅读全文
相关推荐














