views:

57

answers:

2

Given the example source code below, is it possible for someone to see the value of _secret using a disassembler? I didn't see a way to get at the value via Reflector, but I haven't used it very much. Assume the code is not obfuscated in any way.

class Foo
{
    private string _secret = @"all your base are belong to us";

    public void Foo()
    {
        ...
    }
}

Thanks!

+2  A: 

Yes, it is possible. The hard-coded value will be present in the IL and will be viewable via any .NET disassembler. Since this is a field, its initialization from the literal will be viewable in the constructor in Reflector.

Nicole Calinoiu
+2  A: 

It's visible in the constructor in Reflector.

class Foo { private string _secret = @"all your base are belong to us"; }

translates to having constructor

public Foo() { this._secret = "all your base are belong to us"; }

which is visible in Reflector under Foo in method .ctor.

You can also see this information in ildasm (ships with Microsoft Visual Studio) in Foo::.ctor : void:

.method public hidebysig specialname rtspecialname instance void .ctor() cil managed {
    // Code size       19 (0x13)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  ldstr      "all your base are belong to us"
    IL_0006:  stfld      string Playground.Foo::_secret
    IL_000b:  ldarg.0
    IL_000c:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0011:  nop
    IL_0012:  ret
} // end of method Foo::.ctor

Finally, if someone knows the name of your type and the name of your private field, you can obtain the value as such:

object o = typeof(Foo).GetField(
    "_secret",
    BindingFlags.Instance | BindingFlags.NonPublic
).GetValue(f);
Console.WriteLine(o); // writes "all your base are belong to us" to the console

Of course, I can always see all of your private fields with

var fields = typeof(Foo).GetFields(
    BindingFlags.Instance | BindingFlags.NonPublic
);
Jason
I figured it was in there, but I couldn't find it. Thanks so much!
Rob Sobers