Avatar billede ndesoft Nybegynder
16. april 2010 - 12:32 Der er 7 kommentarer og
1 løsning

Serialisering/deserialisering af krypterede filer Forum Forum Opret nyt emne Nyt emne Følg ikke med i denne tråd Følg ikke med <<1>>

Hej,

Jeg har to metoder, der henholdsvis skal serialisere og deserialisere filer.

Mit problem er så blot at jeg skal kryptere filerne, så man ikke umiddelbart kan få adgang til indholdet.

Filerne bliver rigtigt nok krypteret og serialiseret og også deserialiseret, med mindre jeg genstarter programmet. Så vil den nemlig ikke deserialisere.

Min kode ser således ud:

// Nøgle:
static DESCryptoServiceProvider key = new DESCryptoServiceProvider() { Key = System.Text.ASCIIEncoding.ASCII.GetBytes("Hejsa du")  };

// Serialiser. Ikke noget problem.
        public static void SerializeObject<T>(string filename, T objectToSerialize)
        {
            CheckDir();

            using (FileStream fs = File.Open(dir + filename + ".dbdat", FileMode.Create))
            {
                using (CryptoStream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    BinaryFormatter bFormatter = new BinaryFormatter();
                    bFormatter.Serialize(cs, objectToSerialize);
                }
            }
        }

// Deserialiser, problem når programmet åbnes igen.
        public static T DeSerializeObject<T>(string filename)
        {
            string file = dir + filename + ".dbdat";
            CheckDir();
            if (File.Exists(file))
            {
                using (FileStream fs = File.Open(file, FileMode.Open))
                {
                    using (CryptoStream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        return (T)bf.Deserialize(cs);
                    }
                }
            }
            else
            {
                return default(T);
            }
        }

Når jeg kalder metoden DeSerializeObject, efter genstart af programmet, får jeg en af to fejl meddelser:
ArgumentNullException:
Value must not be null
Argument: Converter

Og
DeserializationException:
No Top object.

Hvad er det lige, der går galt?
Avatar billede ndesoft Nybegynder
16. april 2010 - 12:35 #1
Der skete vist en fejl med titlen... Hvorfor er der ikke en rediger-knap?

" Forum Forum Opret nyt emne Nyt emne Følg ikke med i denne tråd Følg ikke med <<1>>" skulle ikke have været med...
Avatar billede Syska Mester
16. april 2010 - 14:17 #2
Kan ikke se hele din kode ... formatering er vist også lidt fucked.

Logiske svar ... du har en value som ikke skal være null.

Hvad linje henviser til exceptions til ?

Er det kode du har fundet på nettet at du skal gøre sådan eller?

mvh
Avatar billede ndesoft Nybegynder
16. april 2010 - 14:42 #3
Her er hele min kode:

// Nøgle:
static DESCryptoServiceProvider key = new DESCryptoServiceProvider() { Key = System.Text.ASCIIEncoding.ASCII.GetBytes("Hejsa du")  };

// Serialiser. Ikke noget problem.
        public static void SerializeObject<T>(string filename, T objectToSerialize)
        {
            CheckDir();

            using (FileStream fs = File.Open(dir + filename + ".dbdat", FileMode.Create))
            {
                using (CryptoStream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    BinaryFormatter bFormatter = new BinaryFormatter();
                    bFormatter.Serialize(cs, objectToSerialize);
                }
            }
        }

// Deserialiser, problem når programmet åbnes igen.
        public static T DeSerializeObject<T>(string filename)
        {
            string file = dir + filename + ".dbdat";
            CheckDir();
            if (File.Exists(file))
            {
                using (FileStream fs = File.Open(file, FileMode.Open))
                {
                    using (CryptoStream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        return (T)bf.Deserialize(cs);
                    }
                }
            }
            else
            {
                return default(T);
            }
        }


Jeg fandt en bid på nettet til hvordan det kan gøres, og jeg har så tilpasset det lidt.

Den kode jeg fandt er her: http://stackoverflow.com/questions/965042/c-serializing-deserializing-a-des-encrypted-file-from-a-stream

Det der siges er null, har følgende stacktrace:
  at System.Runtime.Serialization.SerializationInfo..ctor(Type type, IFormatterConverter converter)
  at System.Runtime.Serialization.Formatters.Binary.ReadObjectInfo.InitDataStore(SerializationInfo& si, Object[]& memberData)
  at System.Runtime.Serialization.Formatters.Binary.ObjectMap.CreateObjectInfo(SerializationInfo& si, Object[]& memberData)
  at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
  at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
  at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
  at DBTesting.Library.FileHandlers.Serializer.DeSerializeObject[T](String filename) in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting.Library\FileHandlers\Serializer.cs:line 49
  at DBTesting.Library.Controller.get_Servers() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting.Library\Controller.cs:line 59
  at DBTesting.ServerWindows.ConnectToServer..ctor() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\ServerWindows\ConnectToServer.xaml.cs:line 34
  at DBTesting.MainWindow.ConnectToServer() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\MainWindow.xaml.cs:line 183
  at DBTesting.MainWindow.Window_Loaded(Object sender, RoutedEventArgs e) in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\MainWindow.xaml.cs:line 54
  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
  at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
  at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
  at MS.Internal.LoadedOrUnloadedOperation.DoWork()
  at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
  at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
  at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
  at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
  at System.Windows.Threading.DispatcherOperation.InvokeImpl()
  at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
  at System.Threading.ExecutionContext.runTryCode(Object userData)
  at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Windows.Threading.DispatcherOperation.Invoke()
  at System.Windows.Threading.Dispatcher.ProcessQueue()
  at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
  at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
  at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
  at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
  at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
  at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
  at System.Windows.Threading.Dispatcher.Run()
  at System.Windows.Application.RunDispatcher(Object ignore)
  at System.Windows.Application.RunInternal(Window window)
  at System.Windows.Application.Run(Window window)
  at System.Windows.Application.Run()
  at DBTesting.App.Main() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\obj\x86\Debug\App.g.cs:line 0
  at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
  at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
  at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ThreadHelper.ThreadStart()

og No Top object-fejlen har følgende:
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
  at DBTesting.Library.FileHandlers.Serializer.DeSerializeObject[T](String filename) in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting.Library\FileHandlers\Serializer.cs:line 49
  at DBTesting.Library.Controller.get_Servers() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting.Library\Controller.cs:line 59
  at DBTesting.ServerWindows.ConnectToServer..ctor() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\ServerWindows\ConnectToServer.xaml.cs:line 34
  at DBTesting.MainWindow.ConnectToServer() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\MainWindow.xaml.cs:line 183
  at DBTesting.MainWindow.Window_Loaded(Object sender, RoutedEventArgs e) in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\MainWindow.xaml.cs:line 54
  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
  at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
  at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
  at MS.Internal.LoadedOrUnloadedOperation.DoWork()
  at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
  at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
  at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
  at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
  at System.Windows.Threading.DispatcherOperation.InvokeImpl()
  at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
  at System.Threading.ExecutionContext.runTryCode(Object userData)
  at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Windows.Threading.DispatcherOperation.Invoke()
  at System.Windows.Threading.Dispatcher.ProcessQueue()
  at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
  at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
  at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
  at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
  at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
  at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
  at System.Windows.Threading.Dispatcher.Run()
  at System.Windows.Application.RunDispatcher(Object ignore)
  at System.Windows.Application.RunInternal(Window window)
  at System.Windows.Application.Run(Window window)
  at System.Windows.Application.Run()
  at DBTesting.App.Main() in C:\Users\Nick\Documents\Visual Studio 2010\Projects\DBTestingSol\DBTesting\obj\x86\Debug\App.g.cs:line 0
  at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
  at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
  at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ThreadHelper.ThreadStart()

Håber det hjælper lidt.
Avatar billede arne_v Ekspert
17. april 2010 - 03:55 #4
static DESCryptoServiceProvider key = new DESCryptoServiceProvider() { Key = System.Text.ASCIIEncoding.ASCII.GetBytes("Hejsa du")  };

->

static DESCryptoServiceProvider key = new DESCryptoServiceProvider() { Key = System.Text.ASCIIEncoding.ASCII.GetBytes("Hejsa du"), IV = new byte[] { 1,2,3,4,5,6,7,8 }  };

Fordi hvis man ikke selv sætter IV, så sættes IV til en random værdi. Og den er så forskellig mellem forskellige kørsler.
Avatar billede ndesoft Nybegynder
17. april 2010 - 12:12 #5
Tusind tak for det. Det var faktisk det, der manglede.
Avatar billede arne_v Ekspert
17. april 2010 - 14:21 #6
så smider jeg et svar
Avatar billede arne_v Ekspert
17. april 2010 - 14:22 #7
Bemærk at hvis det skal være "helt rigtigt", så skal der bruges forskellig og tilfældig IV fra gang til gang og IV kan så overføres ukrypteret sammen med det krypterede.
Avatar billede ndesoft Nybegynder
17. april 2010 - 15:38 #8
Jeg finder nok en løsning på IV-problemet, lige PT har det anden prioritet.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
IT-kurser om Microsoft 365, sikkerhed, personlig vækst, udvikling, digital markedsføring, grafisk design, SAP og forretningsanalyse.

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester