RSA算法的代码示例
时间: 2024-06-24 08:01:49 浏览: 10
RSA算法是一种非对称加密技术,由Ron Rivest, Adi Shamir和Leonard Adleman于1977年发明。它主要用于数据加密和数字签名,特点是使用一对密钥(公钥和私钥)进行操作。下面是一个简单的RSA算法的Python代码示例:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成RSA密钥对
def generate_keys(key_size=2048):
rsa_key = RSA.generate(key_size)
private_key = rsa_key.export_key()
public_key = rsa_key.publickey().export_key()
return private_key, public_key
# 加密函数,使用公钥
def encrypt(message, public_key):
rsa_pub_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_OAEP.new(rsa_pub_key)
ciphertext = cipher_rsa.encrypt(message.encode())
return ciphertext
# 解密函数,使用私钥
def decrypt(ciphertext, private_key):
rsa_priv_key = RSA.import_key(private_key)
cipher_rsa = PKCS1_OAEP.new(rsa_priv_key)
plaintext = cipher_rsa.decrypt(ciphertext)
return plaintext.decode()
# 示例使用
private_key, public_key = generate_keys()
message = "Hello, RSA!"
ciphertext = encrypt(message, public_key)
decrypted_message = decrypt(ciphertext, private_key)
print(f"Original message: {message}")
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Decrypted message: {decrypted_message}")
```
请注意,这段代码是基于`pycryptodome`库实现的,如果你没有安装这个库,需要先通过`pip install pycryptodome`来安装。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)