rsa加解密python代码实现,要求p、q、e从控制台输入
时间: 2023-07-10 20:13:46 浏览: 42
以下是RSA加解密的Python代码实现,其中p、q、e从控制台输入:
```python
import math
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def mod_inverse(a, m):
for x in range(1, m):
if (a * x) % m == 1:
return x
return -1
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num ** 0.5) + 2, 2):
if num % n == 0:
return False
return True
def generate_keypair(p, q, e):
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)
if gcd(phi, e) != 1:
raise ValueError("e must be coprime to phi")
d = mod_inverse(e, phi)
return ((n, e), (n, d))
def encrypt(pk, plaintext):
n, e = pk
cipher = [(ord(char) ** e) % n for char in plaintext]
return cipher
def decrypt(pk, ciphertext):
n, d = pk
plain = [chr((char ** d) % n) for char in ciphertext]
return ''.join(plain)
if __name__ == '__main__':
p = int(input("Enter a prime number (p): "))
q = int(input("Enter another prime number (q): "))
e = int(input("Enter a number (e) coprime to (p-1)*(q-1): "))
public, private = generate_keypair(p, q, e)
print("Public key: ", public)
print("Private key: ", private)
message = input("Enter a message to encrypt with your public key: ")
encrypted_msg = encrypt(public, message)
print("Your encrypted message is: ")
print(''.join(map(lambda x: str(x), encrypted_msg)))
print("Decrypting message with private key: ", private)
print("Your message is:")
print(decrypt(private, encrypted_msg))
```
在运行程序时,用户需要按照提示输入p、q、e以及要加密的明文。程序将生成公钥和私钥,并使用公钥加密明文,最后使用私钥解密密文并输出原始明文。