模拟实现非对称密码算法rsa的加密解密功能
时间: 2023-08-06 20:10:09 浏览: 117
好的,下面是模拟实现非对称密码算法RSA的加密解密功能的代码,代码中使用了Python语言实现:
```python
import random
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def extended_gcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = extended_gcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise Exception('No modular inverse')
else:
return x % m
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5)+1):
if num % 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 = modinv(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))
```
使用方法:
1. 首先输入两个不同的质数 p 和 q;
2. 程序会自动生成公钥和私钥,分别保存在 public 和 private 变量中;
3. 输入要加密的信息 message;
4. 程序会用私钥加密信息,并输出加密后的密文 encrypted_msg;
5. 程序会用公钥解密密文,并输出解密后的明文 message。
需要注意的是,这里生成的密文是数字序列,需要转换成字符序列,才能正确地输出解密后的明文。
阅读全文