问题
I have a text file for which I use two write functions: 1) Normal Write, 2) Secure Write. Both the write functions take the data and offset in the file to start writing as parameters.
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.
When the user attempts to read the data written using the secure write function, then an exception should be raised. Also if some secure data is sandwiched between non-secure data then only the non-secure contents should be displayed.
Eg: If file contains "helloHOWareyou", with'hello' and 'areyou' written using normal write and 'HOW' is written using secure write,then only 'hello' and 'are you' should be read.
I tried this holding the offsets and the length of the secure data in a file header and comparing this with the offset passed to the read function.
#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)
Test Program:
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()`
Had some success with it but of little help.
来源:https://stackoverflow.com/questions/12932340/read-only-a-part-of-the-file-that-was-written-using-certain-function