编写代码实现RSA加密解密程序
时间: 2024-05-16 09:11:59 浏览: 39
RSA加密解密程序是一种非常安全的数据加密方式,实现起来需要一些数学基础和算法。以下是一个简单的Python示例代码,可以帮助你理解RSA加密解密的原理并实现程序。
```python
import random
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def extended_euclid(a, b):
x, y = 0, 1
lastx, lasty = 1, 0
while b != 0:
quotient = a // b
a, b = b, a % b
lastx, x = x, lastx - quotient * x
lasty, y = y, lasty - quotient * y
return lastx, lasty, a
def generate_keypair(p, q):
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_euclid(e, phi)[0]
if d < 0:
d += 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 = 61
q = 53
public, private = generate_keypair(p, q)
print("公钥:", public)
print("私钥:", private)
message = "Hello World"
ciphertext = encrypt(public, message)
print("加密后的信息:", ciphertext)
plaintext = decrypt(private, ciphertext)
print("解密后的信息:", plaintext)
```
这个程序中,`generate_keypair`函数用于生成公钥和私钥,`encrypt`函数用于加密明文,`decrypt`函数用于解密密文。在这个示例代码中,我们使用了非常简单的素数61和53来生成公钥和私钥,实际使用时应该使用更大的素数。