Secure and Encrypted File I/O
We packaged and extended the original protected_fs function of SGX to support secure storage in multiple binding modes such as mrsigner and mrenclave, ensuring that only specific enclaves can access data in protected files.
// The size of data to read/write each time.
// For small files, the recommended size is 4KB;
// For big files, the recommended size is 64KB;
// Don't set SIZE_PER_TIME > 256KB.
constexpr uint32_t SIZE_PER_TIME = 4 * 1024; // 4KB each time
uint8_t buffer[SIZE_PER_TIME] = {0};
std::string content = "hello world!";
// write
size_t written_size = 0;
size_t left_size = content.size();
ProtectedFileWriter writer("./test_protected_file", FileMode::CreateNew, SGX_KEYPOLICY_MRENCLAVE);
while (left_size > 0) {
size_t write_size = (left_size > SIZE_PER_TIME) ? SIZE_PER_TIME : left_size;
writer.Write(content.c_str() + written_size, write_size);
left_size -= write_size;
}
writer.Close();
// read
size_t read_size = 0;
std::string test_data;
ProtectedFileReader reader("./test_protected_file");
while ((read_size = reader.Read(buffer, SIZE_PER_TIME)) > 0) {
test_data.append((char*)buffer, read_size);
}
reader.Close();
note
Writing in this way will generate two files xxx
(data ciphertext) and xxx.pfsmeta
(metadata used for decryption), so when you move or copy the protected file, you must also bring its metadata file.