1

I have a text file for which I use two write functions: 1) Normal Write, 2) Secure Write.

Now when I want to read the data from the file, I should be only be able to read the data written using the "Normal Write" function and should not be able to read the data written using "Secure Write" function.

My idea was to use a dictionary for this using the key as a flag to check if the value was written using normal write or secure write.

How can I do this in Python?

4

1 回答 1

1

这完全取决于您希望数据的安全性。最好的解决方案是使用加密,或多个文件,或两者兼而有之。

如果您只是想要一个标志,您的程序可以使用它来判断文件中的数据是正常的还是安全的,有几种方法可以做到这一点。

  • 您可以在每次编写时添加标题。
  • 您可以以指示安全级别的标志开始每一行,然后只读取具有正确标志的行。
  • 您可以为整个文件设置一个标题,指示文件中安全的部分和不安全的部分。

这是我使用第一个选项实现它的一种方式。

normal_data = "this is normal data, nothing special"
secure_data = "this is my special secret data!"

def write_to_file(data, secure=False):
    with open("path/to/file", "w") as writer:
        writer.write("[Secure Flag = %s]\n%s\n[Segment Splitter]\n" % (secure, data))

write_to_file(normal_data)
write_to_file(secure_data, True) 

def read_from_file(secure=False):
    results = ""
    with open("path/to/file", "r") as reader:
        segments = reader.read().split("\n[Segment Splitter]\n")
    for segment in segments:
        if "[Secure Flag = %s]" % secure in segment.split("\n", 1)[0]:
            results += segment.split("\n", 1)[0]
    return results

new_normal_data = read_from_file()
new_secure_data = read_from_file(True)

这应该有效。但它不是保护数据的最佳方式。

于 2012-10-16T13:06:18.943 回答