我有一个文本文件,我使用两个写函数:1)正常写入,2)安全写入。 两个写函数都将文件中的数据和偏移量作为参数开始写入。
现在,当我想从文件中读取数据时,我应该只能读取使用“正常写入”功能写入的数据,并且不应该能够读取使用“安全写入”功能写入的数据。
当用户尝试读取使用安全写入功能写入的数据时,应该引发异常。此外,如果某些安全数据夹在非安全数据之间,则只应显示非安全内容。
例如:如果文件包含“helloHOWareyou”,使用正常写入写入“hello”和“areyou”,使用安全写入写入“HOW”,则只能读取“hello”和“are you”。
我试着在文件头中保存安全数据的偏移量和长度,并将其与传递给读取函数的偏移量进行比较。
#Normal Write
def writeat(self,data,offset):
self.file.writeat(data,offset)
#Secure Write
def securewrite(self,data,offset):
#Global dict to store the offset and length of secure data
#Have to use this since it is a spec
myvar['offset']=(offset,offset+len(data))
self.file.writeat(data,offset)
#Read function
def readata(self,bytes,offset):
secureRange=mycontext['offset']
if offset in range(secureRange[0],secureRange[1]):
raise ValueError
else:
return self.file.readat(bytes,offset)
测试程序:
myfile=openfile("sample.txt",a) #Open a file
#Write some data to file
myfile.writeat("abcd",0)
#Write private data to file
myfile.securewrite("efgh",4)
# This read is in the region written by writeat and should not be blocked...
x=myfile.readat(4,0)
print x
try:
#Try to read the secure data from the file
y=myfile.readat(4,4)
print y
except ValueError:
print ("Value Error Handled")
pass
else:
print ("Secure data compromised!")
finally:
#Close the file
myfile.close()`
虽然取得了一些成功但却没什么帮助。