rsa算法python实现代码
时间: 2023-09-30 07:06:27 浏览: 103
以下是RSA算法的Python实现代码:
```python
import random
import math
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 is_prime(n):
if n <= 1:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError("Both numbers must be prime.")
elif p == q:
raise ValueError("p and q cannot be equal")
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 = extended_gcd(e, phi)[1]
return ((e, n), (d, n))
def encrypt(pk, plaintext):
key, n = pk
cipher = [pow(ord(char), key, n) for char in plaintext]
return cipher
def decrypt(pk, ciphertext):
key, n = pk
plain = [chr(pow(char, key, n)) for char in ciphertext]
return ''.join(plain)
```
其中,`generate_keypair`函数用于生成公钥和私钥,`encrypt`函数用于加密明文,`decrypt`函数用于解密密文。
阅读全文