嗨
我有一个简单的代码,它使用ECC加密。我想写一个加密的文本,同时在里面放一行。
from ecies.utils import generate_eth_key, generate_key
from ecies import encrypt, decrypt
keyPair = generate_key()
secretKey = keyPair.secret
publicKey = keyPair.public_key.format(True)
with open(pathToFile, 'wb') as fp:
fp.write(encrypt(publicKey, b"Hi!nI want to put a new line here."))
fp.close()
当我解密文件时,我会得到这个:
b"Hi!nI want to put a new line here."
解密过程如下:
with open(pathToFile, 'rb') as fp:
global fileText
fileText = fp.read()
print(decrypt(secretKey, fileText))
所以问题很简单,如何在加密文本的同时用新行写出一些文本
我检查了你的代码,它按预期工作:
from ecies.utils import generate_eth_key, generate_key
from ecies import encrypt, decrypt
keyPair = generate_key()
secretKey = keyPair.secret
publicKey = keyPair.public_key.format(True)
with open('example.txt', 'wb') as fp:
fp.write(encrypt(publicKey, b"Hi!nI want to put a new line here."))
with open('example.txt', 'rb') as fp:
decrypted_contents = decrypt(secretKey, fp.read())
print(decrypted_contents.decode('utf-8'))
输出:
Hi!
I want to put a new line here.
b"你好\我想在这里加一行">
b
表示二进制数据。如果您将文件读取为二进制数据(open(... 'rb')
),则必须对其进行解码
open(pathToFile,'wb')为fp:
fp.write(encrypt(publicKey,b"嗨!\n我想在这里放一个新行。")
fp.close()
fp.close()
在这里是不必要的。with
上下文管理器在with
块结束时自动执行此操作(关闭文件)。