i , having trouble deserializing object des cryptography.
i getting exception says "bad data." in deserializedesobjectfromfile
function.
can please have working?
here code:
public sub serializedesobjecttofile(filename string, item object) dim fs filestream dim formatter new binaryformatter dim deskey() byte = {200, 5, 78, 232, 9, 6, 0, 4} dim desinitializationvector() byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} dim mystreamencrypter cryptostream = nothing fs = new filestream(filename, filemode.create) dim desalgorithm des desalgorithm = new descryptoserviceprovider mystreamencrypter = new cryptostream(fs, desalgorithm.createencryptor(deskey, desinitializationvector), cryptostreammode.write) try formatter.serialize(mystreamencrypter, item) catch e exception console.writeline("failed serialize. reason: " & e.message) fs.close() end try end sub public function deserializedesobjectfromfile(filename string) object dim fs new filestream(filename, filemode.open) dim itemtoreturn new object dim deskey() byte = {200, 5, 78, 232, 9, 6, 0, 4} dim desinitializationvector() byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} dim mystreamdecrypter cryptostream = nothing dim desalgorithm des desalgorithm = new descryptoserviceprovider mystreamdecrypter = new cryptostream(fs, desalgorithm.createdecryptor(deskey, desinitializationvector), cryptostreammode.read) try dim formatter new binaryformatter itemtoreturn = directcast(formatter.deserialize(mystreamdecrypter), object) return itemtoreturn catch e exception msgbox(e.message) return nothing fs.close() end try end function
it important make sure last block in stream flushed. block ciphers modes such ecb mode , cbc mode need padded because block cipher can encrypt full blocks of plaintext. stream not know serialized data object last data has encrypt, cannot pad , encrypt last block itself.
the flushfinalblock should called after have written last plain text data cryptostream
. alternatively call close()
on upper cryptostream
instead of underlying stream, or make sure disposed before call close()
on underlying stream.
Comments
Post a Comment