python - 在python中读取文件中存储的int值

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

我正在编写一个程序,在 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/

相关文章:

python - 基于类别的聚合值

python - df.apply(sorted, axis=1) 删除列名称?

python - os.execv 返回 OSError : [Errno 8] Exec format error

python - django.core.exceptions.ImproperlyConfigured

java - 将字符串转换为私钥和公钥 (RSA)

python - __repr__() 函数的最佳输出类型和编码实践?

python - 在 Cython 中外部定义 _Dcomplex

python - 为扭曲的记录器注册多个观察者

cryptography - 如何使用 OpenSSL 计算 RSA-SHA1(sha1WithRSAEncryption) 值

java - Grails 密码使用 rsa 加密