发过来实现RSA的完整源代码
时间: 2024-05-15 11:14:26 浏览: 8
以下是Python实现RSA加密解密的完整源代码:
```python
import random
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def extended_gcd(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = extended_gcd(b, a % b)
return d, y, x - (a // b) * y
def generate_keypair(p, q):
n = p * q
phi = (p - 1) * (q - 1)
e = random.randint(1, phi - 1)
g = gcd(e, phi)
while g != 1:
e = random.randint(1, phi - 1)
g = gcd(e, phi)
d, _, _ = extended_gcd(e, phi)
d = d % phi
return (e, n), (d, n)
def encrypt(msg, public_key):
e, n = public_key
cipher = [(ord(char) ** e) % n for char in msg]
return cipher
def decrypt(cipher, private_key):
d, n = private_key
msg = [chr((char ** d) % n) for char in cipher]
return ''.join(msg)
if __name__ == '__main__':
p = 61
q = 53
public_key, private_key = generate_keypair(p, q)
msg = 'Hello World!'
cipher = encrypt(msg, public_key)
print('Cipher text:', cipher)
decrypted_msg = decrypt(cipher, private_key)
print('Decrypted message:', decrypted_msg)
```
这个实现使用了Python的内置函数和库。在此代码中,我们生成了一个RSA公钥和私钥,然后使用公钥加密消息,使用私钥解密密文。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)