【问题标题】:Read int values stored in a file in python读取存储在python文件中的int值
【发布时间】:2019-05-04 09:38:38
【问题描述】:

我正在编写一个程序来在 python 中使用 RSA 算法加密文件,而不使用 Crypto 库。我已经生成了密钥,并且 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() 中的值作为参数。

期待建议。谢谢。

【问题讨论】:

  • 您是否尝试将读取的值转换为 int?就像您在写入文件时所做的一样 int(value)
  • 是的,我确实喜欢这个 n=int(open('filename', 'r')) ,但是另一个错误是显示 int() 参数必须是字符串、类似字节的对象或一个数字,而不是 '_io.TextIOWrapper'

标签: python python-3.x rsa file-handling public-key-encryption


【解决方案1】:

open() 函数返回一个文件对象,而不是 int。您需要通过以下方式将返回的对象转换为int 值:

n = open('nfile.pem', 'r')
n_value = int(list(n)[0])

等等

另一个选项(相同的结果)是:

n = open('nfile.pem', 'r')
n_value = int(n.read())

【讨论】:

  • 它在 pow() 中显示错误,例如:TypeError: pow() 的不支持的操作数类型:'bytes'、'int'、'int'
  • 因为我将值用作 pow() 的参数,所以我需要写入文件中的整数形式的内容
  • 没错 :) 这个答案可能有用:stackoverflow.com/questions/444591/…
  • 哦,谢谢你,我怎么能错过它。错误在“内容”中,而不是在 e 或 n 中
【解决方案2】:

推荐的方法是使用with,这样可以确保您的文件在完成后关闭,而不是等待垃圾回收或显式调用f.close() 来关闭您的文件。

n_results = []

with open('nfile.pem', 'r') as f:
    for line in f:
        #do something
        try:
            n.append(int(i))
        except TypeError:
            n.append(0) #you can replace 0 with any value to indicate a processing error

此外,使用try-except 块以防文件中存在无法转换为整数的噪声。 n_results 返回文件中所有值的列表,您可以使用这些值来聚合或组合它们以生成单个输出。

随着您的项目规模扩大以及处理更多数据,这将是一个更好的基础。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    相关资源
    最近更新 更多