用python语言写一个RSA的加解密算法程序
时间: 2023-10-19 13:07:45 浏览: 76
密码学加解密python程序
好的,以下是一个基于Python语言的RSA加解密算法程序:
```python
from math import gcd
from random import randint
def generate_keys(prime1, prime2):
n = prime1 * prime2
phi = (prime1 - 1) * (prime2 - 1)
e = 65537 # a commonly used value for e
while gcd(phi, e) != 1:
e = randint(2, phi - 1)
d = pow(e, -1, phi)
public_key = (n, e)
private_key = (n, d)
return (public_key, private_key)
def encrypt(message, public_key):
n, e = public_key
encrypted_message = [pow(ord(c), e, n) for c in message]
return encrypted_message
def decrypt(encrypted_message, private_key):
n, d = private_key
decrypted_message = ''.join([chr(pow(c, d, n)) for c in encrypted_message])
return decrypted_message
prime1 = 6709
prime2 = 17573
public_key, private_key = generate_keys(prime1, prime2)
message = "Hello, world!"
encrypted_message = encrypt(message, public_key)
decrypted_message = decrypt(encrypted_message, private_key)
print("Public Key is: ", public_key)
print("Private Key is: ", private_key)
print("Original Message is:", message)
print("Encrypted Message is:", encrypted_message)
print("Decrypted Message is:", decrypted_message)
```
请注意,此仅为简单示例代码,RSA算法的安全性依赖于使用足够大的素数作为密钥。
阅读全文