python编写一个RSA加密工具用于数据加密
时间: 2023-11-23 21:49:22 浏览: 92
以下是一个简单的Python程序,用于RSA加密和解密数据:
```python
import random
import math
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def mod_inverse(a, m):
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
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 = mod_inverse(e, phi)
return ((e, n), (d, n))
def encrypt(pk, plaintext):
key, n = pk
cipher = [(ord(char) ** key) % n for char in plaintext]
return cipher
def decrypt(pk, ciphertext):
key, n = pk
plain = [chr((char ** key) % n) for char in ciphertext]
return ''.join(plain)
if __name__ == '__main__':
p = int(input("Enter a prime number (17, 19, 23, etc): "))
q = int(input("Enter another prime number (Not one you entered above): "))
public, private = generate_keypair(p, q)
print("Your public key is ", public, " and your private key is ", private)
message = input("Enter a message to encrypt with your private key: ")
encrypted_msg = encrypt(private, message)
print("Your encrypted message is: ")
print(''.join(map(lambda x: str(x), encrypted_msg)))
print("Decrypting message with public key ", public, " . . .")
print("Your message is:")
print(decrypt(public, encrypted_msg))
```
该程序生成RSA密钥对,并使用私钥加密和公钥解密消息。您可以使用以下命令运行Python程序:
```python
python rsa.py
```
接下来,您需要按照程序提示进行操作,输入两个质数和要加密的消息。程序将输出加密后的消息以及解密后的消息。
阅读全文