python RSA
时间: 2023-06-22 19:25:11 浏览: 54
RSA是一种非对称加密算法,它可以用来加密、解密数据以及生成数字签名。在Python中,可以使用pycryptodome或cryptography库实现RSA加密和解密。下面是一个简单的RSA加密和解密的示例代码:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成密钥对
key = RSA.generate(2048)
# 获取公钥和私钥
private_key = key.export_key()
public_key = key.publickey().export_key()
# RSA加密
def rsa_encrypt(public_key, message):
rsa_key = RSA.import_key(public_key)
cipher = PKCS1_OAEP.new(rsa_key)
ciphertext = cipher.encrypt(message.encode())
return ciphertext
# RSA解密
def rsa_decrypt(private_key, ciphertext):
rsa_key = RSA.import_key(private_key)
cipher = PKCS1_OAEP.new(rsa_key)
message = cipher.decrypt(ciphertext).decode()
return message
# 示例
message = "Hello, RSA!"
ciphertext = rsa_encrypt(public_key, message)
plaintext = rsa_decrypt(private_key, ciphertext)
print("明文:", message)
print("密文:", ciphertext.hex())
print("解密后明文:", plaintext)
```
注意:RSA加密和解密的性能较低,对于大量数据的加密和解密,建议使用对称加密算法。