RSA加密算法代码实现
时间: 2023-08-21 09:25:46 浏览: 53
以下是 Python 代码实现 RSA 加密算法:
```python
import random
from math import gcd
def generate_keypair(p, q):
n = p * q
phi = (p - 1) * (q - 1)
# choose e such that e and phi(n) are coprime
e = random.randrange(1, phi)
while gcd(e, phi) != 1:
e = random.randrange(1, phi)
# compute d such that d*e = 1 (mod phi(n))
d = pow(e, -1, phi)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
e, n = public_key
ciphertext = [pow(ord(char), e, n) for char in plaintext]
return ciphertext
def decrypt(private_key, ciphertext):
d, n = private_key
plaintext = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(plaintext)
```
其中,`generate_keypair` 用于生成公钥和私钥;`encrypt` 用于加密明文,返回密文列表;`decrypt` 用于解密密文,返回明文字符串。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)