Skip to content
← All posts
· Delta1 Labs Nebula.NETObfuscationSecurity

The method body a decompiler never sees

Nebula Pro can strip a sensitive method to an encrypted blob plus a stub, and only decrypt and install the real IL the first time the method runs. Here is how that works in the CLR, what is honestly possible in managed code versus what needs a JIT hook, and where the technique still leaks.

Open any .NET assembly in a decompiler and the thing that makes you wince is how little work it takes. Managed binaries carry their methods as IL, and IL carries enough metadata that a decompiler can reconstruct readable C# almost verbatim. Renaming helps — a.b(c) is harder to follow than License.Validate(key) — but the logic is still right there on the screen, line for line. For the one or two methods that are the actual product — a license gate, a key-derivation routine, a pricing formula you spent years on — “harder to read” is not the bar you want.

So here is the real question: can you ship a method whose body a decompiler simply cannot show, without rewriting it into something that runs slower forever? The answer Nebula Pro gives is to leave the method as real IL but keep that IL encrypted right up until the runtime is about to execute it — decrypt it on the first call, install it, and from then on run it as ordinary JIT-compiled native code. This post is how that actually works in the CLR, where it is honestly possible in pure managed code and where it is not, and the places it still leaks.

What the decompiler sees today

Start with the method you want to protect:

public bool Validate(LicenseToken token)
{
    var expected = Hmac(token.Payload, _secret);
    return FixedTimeEquals(expected, token.Signature)
        && token.Expiry > DateTime.UtcNow;
}

Compiled, its body is a short run of IL sitting in the assembly’s method table, reachable from the type’s metadata by RVA. A decompiler reads exactly that:

.method public hidebysig instance bool Validate(class LicenseToken token) cil managed
{
  ldarg.0
  ldarg.1
  callvirt   instance uint8[] LicenseToken::get_Payload()
  ldarg.0
  ldfld      uint8[] Licensing::_secret
  call       instance uint8[] Licensing::Hmac(uint8[], uint8[])
  // … the whole method, in the clear
}

Nothing here is secret from the tools. The signature, the locals, every instruction — all readable. That is the surface we want to remove.

Replacing the body with a blob and a stub

At protect time, Nebula does two things to a selected method. First it serialises the original method body — the IL stream, the local-variable signature, the exception-handling clauses, the stack size — and encrypts that package into a blob stored in a resource. Second it overwrites the on-disk method body with a tiny stub that carries no real logic:

// What the shipped method body actually is now.
public bool Validate(LicenseToken token)
    => ProtectedBodies.Invoke<bool>(0x0600_0042, token);

Decompile the shipped assembly and that stub — or a bare throw placeholder, depending on how the stub is emitted — is all you get. The real instruction stream is no longer in the method table in any readable form; it is ciphertext in a resource, indexed by the metadata token 0x06000042. Static analysis is now looking at an encrypted byte array and a dispatcher call, and there is nothing to decompile into your algorithm.

The decrypt-on-first-call sequence

The real IL has to come back before the method can run. The honest, portable version of the mechanism is: the stub’s dispatcher, on the first invocation for a given token, decrypts the body blob, rebuilds it as an executable method, caches the result, and from then on calls straight through.

static class ProtectedBodies
{
    static readonly ConcurrentDictionary<int, Delegate> _installed = new();

    public static T Invoke<T>(int token, params object[] args)
    {
        var body = _installed.GetOrAdd(token, Install);   // decrypt + build ONCE
        return (T)body.DynamicInvoke(args);
    }

    static Delegate Install(int token)
    {
        byte[] il = Decrypt(BlobFor(token), DeriveKey());  // key is derived, not stored
        var dm = BuildDynamicMethod(token, il);            // real IL → DynamicMethod
        return dm.CreateDelegate(DelegateTypeFor(token));  // JIT compiles it normally
    }
}

The decrypted IL is handed to a DynamicMethod (or emitted into a dynamic module via ModuleBuilder), and CreateDelegate makes the CLR JIT it like any other method — real native code, running at full speed on every call after the first. GetOrAdd guarantees the decrypt-and-build happens once per method; subsequent calls are a dictionary lookup and a delegate call.

Protect-time split and run-time decrypt-on-first-callProtect timeoriginalmethod ILencrypted blob (resource)stub replaces bodyRun timefirst callhits the stubdecrypt blobkey derivedreal IL rebuiltDynamicMethodJIT once + cachenative codelater calls: cached delegate, no decryptencrypteddecrypt stepnative, cached
Protect time splits the method into an encrypted blob and a stub; the first call decrypts and JITs the real IL once, then every later call runs cached native code.

Be honest about the CLR: what managed code can and cannot do

It is tempting to describe this as “swapping the real method’s body at runtime.” Be precise about what the CLR actually allows, because the limits shape the design.

A method loaded from a static PE image has its IL fixed in the module the JIT reads from. There is no managed API that replaces the body of an already-loaded, statically-compiled method with new IL. MethodRental.SwapMethodBody exists, but it operates only on a ModuleBuilder — a dynamic module you are emitting at runtime — not on methods loaded from disk. That is exactly why the portable design above does not try to overwrite Validate in place: it builds the decrypted IL into a new DynamicMethod and routes callers through the stub to that delegate. The stub is the indirection that makes an un-swappable method effectively swappable.

The genuinely transparent move — leave callers untouched and redirect the original method’s entry point to the freshly JIT-compiled body — is possible, but it means patching the runtime’s internal method table (the native code slot a MethodDesc points at, the same mechanism detour libraries use after RuntimeHelpers.PrepareMethod). That works, but it reaches into undocumented runtime layout and is fragile across CLR versions. The fully general, robust version of “the JIT compiles decrypted IL for the original method” is a native profiler using the JIT hook (ICorProfilerCallback::JITCompilationStarted), which hands the runtime replacement IL as each method is compiled. That is a different, heavier deployment than a managed transform. The managed stub-plus-DynamicMethod route is the one that ships without a native component, at the cost of the extra indirection — and that is the honest trade.

The key has to be reachable — so hide it well

There is an unavoidable tension: to decrypt the body at runtime, the key must be derivable at runtime, which means it is present, in some form, inside the very assembly an attacker is studying. Storing the key as a plain byte[] constant would hand it over immediately — a decompiler reads static arrays as easily as it reads IL.

This is why method-body encryption is not a standalone feature; it is only as strong as what hides its decryptor. Nebula Pro pairs it with string encryption so key material and resource names are not literals, and with control-flow flattening over the decryptor itself so DeriveKey is not a tidy function an attacker can read and lift. The key is derived — assembled from scattered computation, not stored — so that recovering it means understanding flattened, string-encrypted code rather than reading a constant. The encryption of the body raises the cost of static analysis to infinity; the obfuscation of the decryptor is what stops that cost collapsing back to “find the key, decrypt the blob offline.”

Where it leaks, and how to scope it

Three honest limits decide where this technique belongs.

The plaintext exists in memory, once. The JIT needs real IL to compile, so after the first call the decrypted body is materialised in the process. An attacker who runs the method and dumps the process afterward can capture it. This is why the right framing is cost, not a wall: you convert a trivial static decompile into a dynamic attack that requires running the target, timing the dump, and reassembling the captured body — far more work, and far more detectable, but not impossible.

Ahead-of-time compilation changes the picture. ReadyToRun and NativeAOT precompile IL to native code at build time. A method whose body is an encrypted blob at build time has no IL for an AOT compiler to precompile, so the decrypt-and-JIT path assumes a JIT is present at runtime. On a NativeAOT target the model does not apply as described; scope and target accordingly.

Per-call versus once. Decrypt-and-install must happen once per method, cached as above. Decrypting on every call turns a one-time startup cost into a permanent tax — ruinous on anything hot. Which is the last rule: scope method-body encryption to the few methods that carry real value, never to inner-loop or per-request code. Configure it per method in nebula.config.json or by attribute, exactly as you would scope code virtualization — the two techniques protect the same short list of methods by opposite means.

Takeaway

Renaming raises the cost of reading your assembly; encrypting a method body removes the body from the decompiler’s screen entirely and restores it only at the instant the runtime needs it. In pure managed code the mechanism is a stub plus a decrypted DynamicMethod, because the CLR will not swap a loaded method’s IL in place — the transparent swap needs a native JIT hook, and that is the honest line between the two deployments. Used on the handful of methods that are genuinely your product, paired with string encryption and control-flow flattening so the key is derived rather than stored, and scoped away from hot paths, it turns a one-click decompile into a dynamic attack that most adversaries will not pay for.

See Nebula.NET for the full transform set, or the docs for the nebula.config.json reference and per-method scoping.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.