Search code examples
serializationencryptioncompact-framework.net-2.0protocol-buffers

What's the best method of Encryption whilst using ProtoBuf?


I've migrated my database on my mobile device away from VistaDB because it's just too slow. I'm now using ProtoBuf instead to create a series of flat files on a Storage Card, the only issue is there's obviously no encryption.

Which encryption method works best with ProtoBuf? I'm basically serializing a collection of data entities to a file, then deserializing from the File back into my collections. I figure the best place to put the encryption would be in the FileStream on the read/write.

The data will contain NI numbers, names and addresses, so this has to be secure. Any idea anyone?


Solution

  • I think you're on the right track. You should just be able to do something like:

    ICryptoTransform encryptor = ...
    Stream encStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write);
    Serializer.Serialize(encStream, obj);
    encStream.FlushFinalBlock()
    encStream.Close();
    
    ICryptoTransform decryptor = ...
    Stream decStream = new CryptoStream(inputputFileStream, decryptor, CryptoStreamMode.Read);
    Serializer.Deserialize<Type>(decStream);
    decStream.FlushFinalBlock()
    decStream.Close();
    

    For the basics of .NET's encryption framework (including how to get the ICryptoTransform objects, see other questions like What’s the best way to encrypt short strings in .NET?.