将下面代码修改成正确格式并加上注释 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-03-10 07:45:27 浏览: 145
下面是修改后的代码,加上了注释,更易于理解:
```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):
"""
生成公私密钥对
"""
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():
"""
主函数,调用其他函数实现RSA加密解密
"""
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()
```
阅读全文