python实现RSA加密算法
时间: 2023-12-04 07:40:24 浏览: 63
以下是Python实现RSA加密算法的示例代码:
```python
import random
import math
def is_prime(num):
"""
判断一个数是否为素数
"""
if num <= 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def gcd(a, b):
"""
求两个数的最大公约数
"""
if b == 0:
return a
else:
return gcd(b, a % b)
def generate_key(p, q):
"""
生成RSA公钥和私钥
"""
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
d = inverse(e, phi)
return ((e, n), (d, n))
def inverse(a, m):
"""
求a在模m意义下的逆元
"""
x, y, r = 0, 1, m
u, v, s = 1, 0, a
while s != 0:
q = r // s
r, s = s, r - q * s
x, u = u, x - q * u
y, v = v, y - q * v
return x % m
def encrypt(pk, plaintext):
"""
RSA加密
"""
key, n = pk
cipher = [pow(ord(char), key, n) for char in plaintext]
return cipher
def decrypt(pk, ciphertext):
"""
RSA解密
"""
key, n = pk
plain = [chr(pow(char, key, n)) for char in ciphertext]
return ''.join(plain)
# 生成RSA公钥和私钥
p = 61
q = 53
public_key, private_key = generate_key(p, q)
print("公钥:", public_key)
print("私钥:", private_key)
# 加密数据
plaintext = "Hello, world!"
ciphertext = encrypt(public_key, plaintext)
print("加密后的数据:", ciphertext)
# 解密数据
plaintext = decrypt(private_key, ciphertext)
print("解密后的数据:", plaintext)
```
相关推荐
![](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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)