将代码修改成正确的格式 import random def is_prime(number): if number < 2: return False for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def generate_key(length): # 生成p、q两个大质数 while True: p = random.randint(2 ** (length//2 - 1), 2 ** (length//2)) if is_prime(p): break while True: q = random.randint(2 ** (length//2 - 1), 2 ** (length//2)) if is_prime(q) and q != p: break # 计算n和φ(n) n = p * q phi_n = (p - 1) * (q - 1) # 选择一个与φ(n)互质的正整数e while True: e = random.randint(2, phi_n - 1) if math.gcd(e, phi_n) == 1: break # 计算e的逆元d d = pow(e, -1, phi_n) # 返回公钥和私钥 public_key = (n, e) private_key = (n, d) return public_key, private_key def encrypt(message, public_key): n, e = public_key # 将消息转换为整数 m = int.from_bytes(message.encode(), 'big') # 加密并返回密文 c = pow(m, e, n) return c.to_bytes((c.bit_length() + 7) // 8, 'big') def decrypt(ciphertext, private_key): n, d = private_key # 解密并返回明文 c = int.from_bytes(ciphertext, 'big') m = pow(c, d, n) return m.to_bytes((m.bit_length() + 7) // 8, 'big')
时间: 2024-01-15 08:05:27 浏览: 107
代码已经被格式化了,您可以直接复制使用:
```python
import random
import math
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
def generate_key(length):
# 生成p、q两个大质数
while True:
p = random.randint(2 ** (length//2 - 1), 2 ** (length//2))
if is_prime(p):
break
while True:
q = random.randint(2 ** (length//2 - 1), 2 ** (length//2))
if is_prime(q) and q != p:
break
# 计算n和φ(n)
n = p * q
phi_n = (p - 1) * (q - 1)
# 选择一个与φ(n)互质的正整数e
while True:
e = random.randint(2, phi_n - 1)
if math.gcd(e, phi_n) == 1:
break
# 计算e的逆元d
d = pow(e, -1, phi_n)
# 返回公钥和私钥
public_key = (n, e)
private_key = (n, d)
return public_key, private_key
def encrypt(message, public_key):
n, e = public_key
# 将消息转换为整数
m = int.from_bytes(message.encode(), 'big')
# 加密并返回密文
c = pow(m, e, n)
return c.to_bytes((c.bit_length() + 7) // 8, 'big')
def decrypt(ciphertext, private_key):
n, d = private_key
# 解密并返回明文
c = int.from_bytes(ciphertext, 'big')
m = pow(c, d, n)
return m.to_bytes((m.bit_length() + 7) // 8, 'big')
```
阅读全文