Search code examples
c#xml-deserializationcopy-protection

Deserialization fail when using themida protection


As the title says the deserialization fail after protecting my application with themida with the following exception :

Unable to generate a temporary class (result=1). error CS0009: Metadata file 'c:\Path\to\protected.exe' could not be opened -- 'An attempt was made to load a program with an incorrect format. '

Here's the code I'm using for the deserialization (It works when the exe is not protected):

MyClass myClass;
try
{
    using (var stream = new MemoryStream(Data))
    {
        var serializer = new XmlSerializer(typeof(ComSec.MyClass));
        myClass = serializer.Deserialize(stream) as MyClass;
    }
}
catch (Exception e)
{
    return null;
}

Weird thing is that the code + themida protection works fine on my machine but it fails on the VM and on a co-worker's machine

I'm using (same config as my co-worker) :

  • VS2012 Professional
  • Windows 7 x64 Ultimate
  • Themida 2.1.2.0 x86 (With .Net support)

The VM is a fresh install of Windows 7 x86.


Solution

  • I ended up using the DataContract attribute and using a DataContractSerializer to Serialize and deserialize the object (It works now everywhere and with/without the protection ).

    My research:

    [DataContract(Name = "TestClass")]
    public class TestClass
    {
        [DataMember(Name = "Name")]
        public string Name { get; set; }
        [DataMember(Name = "Age")]
        public int Age { get; set; }
    }
    

    Serialization/Deserialization :

    var serializer = new DataContractSerializer(typeof(TestClass));
    
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, this);
        File.WriteAllBytes("TestClass.xml", stream.ToArray());
    }
    
    TestClass o = null;
    using (var stream = new MemoryStream(File.ReadAllBytes("TestClass.xml")))
    {
        o = serializer.ReadObject(stream) as TestClass;
    }