使用Python实现RSA加解密的示例代码
时间: 2023-11-05 18:03:26 浏览: 135
# RSA加解密示例代码
import random
# 求最大公约数
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# 判断是否为质数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# 生成大素数
def generate_prime_number():
while True:
p = random.randint(100, 1000)
if is_prime(p):
return p
# 扩展欧几里得算法求逆元
def extended_euclidean_algorithm(a, b):
if b == 0:
return 1, 0, a
x, y, gcd = extended_euclidean_algorithm(b, a % b)
return y, x - a // b * y, gcd
# 生成RSA密钥对
def generate_rsa_key_pair():
p = generate_prime_number()
q = generate_prime_number()
n = p * q
phi_n = (p - 1) * (q - 1)
while True:
e = random.randint(2, phi_n - 1)
if gcd(e, phi_n) == 1:
break
d, _, _ = extended_euclidean_algorithm(e, phi_n)
d = d % phi_n
return (e, n), (d, n)
# RSA加密
def rsa_encrypt(plaintext, public_key):
e, n = public_key
ciphertext = [pow(ord(char), e, n) for char in plaintext]
return ciphertext
# RSA解密
def rsa_decrypt(ciphertext, private_key):
d, n = private_key
plaintext = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(plaintext)
# 测试
plaintext = 'Hello, world!'
public_key, private_key = generate_rsa_key_pair()
ciphertext = rsa_encrypt(plaintext, public_key)
decrypted_plaintext = rsa_decrypt(ciphertext, private_key)
print('Plaintext:', plaintext)
print('Ciphertext:', ciphertext)
print('Decrypted plaintext:', decrypted_plaintext)
阅读全文