将下面代码修改成正确格式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 Truedef generate_key(length): 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 = p * q phi_n = (p - 1) * (q - 1) while True: e = random.randint(2, phi_n - 1) if math.gcd(e, phi_n) == 1: break d = pow(e, -1, phi_n) public_key = (n, e) private_key = (n, d) return public_key, private_keydef 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') def main(): message = "Hello, this is a test message!" print("Original message:", message) public_key, private_key = generate_key(512) print("Public key:", public_key) print("Private key:", private_key) encrypted_message = encrypt(message, public_key) print("Encrypted message:", encrypted_message) decrypted_message = decrypt(encrypted_message, private_key) print("Decrypted message:", decrypted_message.decode()) if __name__ == "__main__": main()
时间: 2024-04-26 10:20:54 浏览: 133
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):
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 = p * q
phi_n = (p - 1) * (q - 1)
while True:
e = random.randint(2, phi_n - 1)
if math.gcd(e, phi_n) == 1:
break
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')
def main():
message = "Hello, this is a test message!"
print("Original message:", message)
public_key, private_key = generate_key(512)
print("Public key:", public_key)
print("Private key:", private_key)
encrypted_message = encrypt(message, public_key)
print("Encrypted message:", encrypted_message)
decrypted_message = decrypt(encrypted_message, private_key)
print("Decrypted message:", decrypted_message.decode())
if __name__ == "__main__":
main()
阅读全文