【发布时间】:2021-11-24 09:34:49
【问题描述】:
此代码运行并将我的输出文本文件中的所有值保存到d,但不保存我的 public_key 和 private_key 的值。这是一个简单的代码,我在其中尝试复制 RSA 算法并尝试保存所有带有 open.write() 的文本文件中的值。谁能告诉我哪里错了?
它看起来像这样:
import random
import time
import os
max_PrimLength = 1000000000000
output_folder_name=f"output/{int(time.time()*100)}"
os.makedirs(f"{output_folder_name}")
details_file=open(f"{output_folder_name}/details.txt","a+")
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
def generateRandomPrim():
while(1):
ranPrime = random.randint(0,99999)
if is_prime(ranPrime):
return ranPrime
p = generateRandomPrim()
q = generateRandomPrim()
h = p*q
phi = (p-1) * (q-1)
e = random.randint(1, phi)
g = gcd(e,phi)
while g != 1:
e = random.randint(1, phi)
g = gcd(e, phi)
d = egcd(e, phi)[1]
d = d % phi
if(d < 0):
d += phi
print("First Prime Number(p): %d" % p)
details_file.write("First Prime Number(p): %d\n" % p)
print("Second Prime Number(q): %d" % q)
details_file.write("Second Prime Number(q): %d\n" % q)
print("h: %d" %h)
details_file.write("h: %d\n" %h)
print("phi(p-1)(q-1): %d" % phi)
details_file.write("phi(p-1)(q-1): %d\n" % phi)
print("e: %d" % e)
details_file.write("e: %d\n" %e)
print("d: %d" % d)
details_file.write("d: %d\n" % d)
def generate_keyPairs():
return ((e,h),(d,h))
if _name_ == 'main':
public_key,private_key = generate_keyPairs()
print("Public_Key(Traditional_RSA): ",public_key)
details_file.write("Public_Key(Traditional_RSA): \n",public_key)
print("Private_Key(Traditional_RSA): ",private_key)
details_file.write("Private_Key(Traditional_RSA): \n",private_key)
details_file.close()
发生引用错误:
TypeError Traceback (most recent call last)
<ipython-input-4-3018b2703be1> in <module>
144 public_key,private_key = generate_keyPairs()
145 print("Public_Key(Traditional_RSA): " ,public_key)
--> 146 details_file.write("Public_Key(Traditional_RSA): \n" ,public_key)
147 print("Private_Key(Traditional_RSA): " ,private_key)
148 details_file.write("Private_Key(Traditional_RSA): \n" ,private_key)
TypeError: write() takes exactly one argument (2 given)
【问题讨论】:
-
你没有提到错误是什么原因吗?
-
@sayse 它不会给出任何错误,但不会打印文本文件中的所有值。我已经用最近的引用错误编辑了我的问题,请参阅。
-
试试去掉“if name == 'main'”这个条件,把代码去掉就行了。
-
正如错误消息所说:您不能像使用
print那样只为.write指定多个内容。因为这个错误首先出现,所以它隐藏了程序中的另一个错字:if _name_ == 'main':应该改为if __name__ == '__main__',每边有两个下划线,用于“name”和“main”。另外,请记住,该块的要点 是包含如果有人imports 您的文件应该不发生的内容。您应该按照教程进行操作,并确保您了解 Python 中如何正确组织脚本文件。
标签: python python-3.x text time jupyter-notebook