c# - Serializing object at specific byte index -


in vs2015, serialize data table file, beginning @ byte 16, since file encrypted , iv uses bytes 0-15. have not yet found serialization method taking offset parameter, should convert table byte array? there must cleaner approach. here 1 of functions:

internal static void encryptdata(datatable dtable, string username, string password, string filename) {     using (filestream fs = new filestream(filename, filemode.openorcreate, fileaccess.write, fileshare.none))     {         using (aes aes = setaes(username, password)) // performs aes initialization         {             fs.write(aes.iv, 0, 16); // writing iv             using (cryptostream cs = new cryptostream(fs, aes.createencryptor(), cryptostreammode.write))             {                 dtable.writexml(cs, xmlwritemode.writeschema); // overwriting bytes 0-15 :(             }         }     } } 

edit: adding deserialization function, throws exception "length of data decrypt invalid"

internal static void decryptdata(datatable dtable, string username, string password, string filename) {     using (filestream fs = new filestream(filename, filemode.open))     {         byte[] iv = new byte[16];         fs.read(iv, 0, 16);         using (aes aes = setaes(username, password, iv)) // setting aes         {             using (cryptostream cs = new cryptostream(fs, aes.createdecryptor(), cryptostreammode.read))             {                 dtable.readxml(cs);             }         }     } } 

final edit: solution: add iv bytes file.writeallbytes , use filestream filemode.append in serializing method(encryptdata):

    using (aes aes = setaes(username, password))     {         file.writeallbytes(filename, aes.iv);         using (filestream fs = new filestream(filename, filemode.append, fileaccess.write, fileshare.none))         {                                                    using (cryptostream cs = new cryptostream(fs, aes.createencryptor(), cryptostreammode.write))             {                 dtable.writexml(cs, xmlwritemode.writeschema);                                                                                                                                                    }         }     } 


Comments

Popular posts from this blog

xcode - CocoaPod Storyboard error: -

c# - AutoMapper - What's difference between Condition and PreCondition -