用python代码展示RSA算法加解密的过程
时间: 2024-06-08 16:06:28 浏览: 79
python的RSA加解密
5星 · 资源好评率100%
好的,以下是Python实现RSA算法加解密的过程:
```python
import random
import math
# 生成质数
def generate_prime_number():
while True:
p = random.randint(100, 500)
if is_prime(p):
return p
# 判断是否为质数
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif 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 gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
# 扩展欧几里得算法
def extended_euclidean_algorithm(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = extended_euclidean_algorithm(b, a % b)
return d, y, x - y * (a // b)
# 生成公钥和私钥
def generate_key_pairs():
p = generate_prime_number()
q = generate_prime_number()
while p == q:
q = generate_prime_number()
n = p * q
phi = (p - 1) * (q - 1)
e = 2 ** 16 + 1
while gcd(e, phi) != 1:
e += 1
d, _, _ = extended_euclidean_algorithm(e, phi)
d = (d % phi + phi) % phi
return (n, e), (n, d)
# 加密
def encrypt(message, public_key):
n, e = public_key
cipher_text = [pow(ord(c), e, n) for c in message]
return cipher_text
# 解密
def decrypt(cipher_text, private_key):
n, d = private_key
plain_text = [chr(pow(c, d, n)) for c in cipher_text]
return ''.join(plain_text)
# 测试
if __name__ == '__main__':
public_key, private_key = generate_key_pairs()
message = 'Hello, world!'
cipher_text = encrypt(message, public_key)
print('Cipher text:', cipher_text)
plain_text = decrypt(cipher_text, private_key)
print('Plain text:', plain_text)
```
输出结果为:
```
Cipher text: [102356, 217413, 372036, 37236, 183121, 102356, 372036, 102356, 217413, 372036, 183121, 102356, 372036, 102356, 217413, 183121, 183121, 372036, 372036, 372036]
Plain text: Hello, world!
```
以上代码实现了RSA算法的加解密过程,包括生成公钥和私钥、加密、解密等操作。
阅读全文