我正在编写一个程序,在 python 中使用 RSA 算法加密文件,而不使用加密库。我已经生成了 key ,并且 e、n 和 d 存储在 .pem 文件中。现在,在另一个严格的加密过程中,我使用 e、d 和 n 值,但每次运行脚本时都会显示错误:
File "rsaencrypt.py", line 91, in <module>
main()
File "rsaencrypt.py", line 62, in main
encrypt = pow(content, e, n)
TypeError: unsupported operand type(s) for pow(): 'bytes','_io.TextIOWrapper', '_io.TextIOWrapper'
这是我如何在加密脚本中打开文件并使用 pow() 来加密文件:
n = open('nfile.pem', 'r')
c = open('cfile.pem', 'r')
d = open('dfile.pem', 'r'))
encrypt = pow(content, e, n)
我在互联网上搜索了如何从文件中读取 int 值,但一无所获。
以下是我如何将值保存在 efile、dfile 和 nfile 中:
#saving the values of n, d and e for further use
efile = open('efile.pem', 'w')
efile.write('%d' %(int(e)))
efile.close()
dfile = open('dfile.pem', 'w')
dfile.write('%d' %(int(d)))
dfile.close()
nfile = open('nfile.pem', 'w')
nfile.write('%d' % (int(n)))
nfile.close()
值的存储方式如下:564651648965132684135419864........................454
现在,为了加密文件,我需要读取 efile、dfile 和 nfile 中写入的整数值,以使用 pow() 中的值作为参数。
期待建议。谢谢。
最佳答案
open()
函数返回一个文件对象,而不是 int。您需要通过以下方式将返回的对象转换为 int
值:
n = open('nfile.pem', 'r')
n_value = int(list(n)[0])
等等
另一个选项(相同的结果)是:
n = open('nfile.pem', 'r')
n_value = int(n.read())
关于python - 在python中读取文件中存储的int值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53587904/