# The method body a decompiler never sees


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:

```csharp
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:

```il
.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:

```csharp
// 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.

```csharp
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.

<figure class="my-8"><svg viewBox="0 0 700 330" role="img" aria-label="Two-phase diagram. At protect time the original method IL is split into an encrypted blob stored in a resource and a tiny stub that replaces the on-disk method body. At run time the first call to the stub triggers a decrypt step that turns the blob back into real IL, which is built into a dynamic method and JIT-compiled once; the result is cached, so every later call runs native code directly."><title>Protect-time split and run-time decrypt-on-first-call</title><defs><style>.bx{fill:#fff;stroke:#64748b;stroke-width:1}.enc{fill:#6366f1}.dec{fill:#0891b2}.ok{fill:#10b981}.t{font:600 12px system-ui;fill:#64748b}.tw{font:600 12px system-ui;fill:#fff}.s{font:11px system-ui;fill:#64748b}.ar{stroke:#64748b;stroke-width:1.5;fill:none;marker-end:url(#a)}</style><marker id="a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" fill="#64748b"/></marker></defs><text class="t" x="20" y="26">Protect time</text><rect class="bx" x="20" y="40" width="130" height="46" rx="4"/><text class="t" x="85" y="62" text-anchor="middle">original</text><text class="t" x="85" y="78" text-anchor="middle">method IL</text><path class="ar" d="M150 63 L196 63"/><rect class="enc" x="200" y="34" width="150" height="26" rx="4"/><text class="tw" x="275" y="52" text-anchor="middle">encrypted blob (resource)</text><rect class="bx" x="200" y="68" width="150" height="26" rx="4"/><text class="t" x="275" y="85" text-anchor="middle">stub replaces body</text><line x1="360" y1="110" x2="360" y2="130" stroke="#64748b" stroke-width="1" stroke-dasharray="3 3"/><text class="s" x="20" y="150">Run time</text><rect class="bx" x="20" y="164" width="120" height="44" rx="4"/><text class="t" x="80" y="182" text-anchor="middle">first call</text><text class="s" x="80" y="198" text-anchor="middle">hits the stub</text><path class="ar" d="M140 186 L186 186"/><rect class="dec" x="190" y="164" width="120" height="44" rx="4"/><text class="tw" x="250" y="182" text-anchor="middle">decrypt blob</text><text class="s" x="250" y="198" text-anchor="middle" fill="#fff">key derived</text><path class="ar" d="M310 186 L356 186"/><rect class="bx" x="360" y="164" width="130" height="44" rx="4"/><text class="t" x="425" y="182" text-anchor="middle">real IL rebuilt</text><text class="s" x="425" y="198" text-anchor="middle">DynamicMethod</text><path class="ar" d="M490 186 L536 186"/><rect class="ok" x="540" y="164" width="140" height="44" rx="4"/><text class="tw" x="610" y="182" text-anchor="middle">JIT once + cache</text><text class="s" x="610" y="198" text-anchor="middle" fill="#fff">native code</text><path class="ar" d="M610 208 L610 246 L250 246 L250 214"/><text class="s" x="430" y="242" text-anchor="middle">later calls: cached delegate, no decrypt</text><rect class="enc" x="20" y="292" width="13" height="13"/><text class="s" x="40" y="303">encrypted</text><rect class="dec" x="150" y="292" width="13" height="13"/><text class="s" x="170" y="303">decrypt step</text><rect class="ok" x="280" y="292" width="13" height="13"/><text class="s" x="300" y="303">native, cached</text></svg><figcaption class="text-sm text-muted mt-2">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.</figcaption></figure>

## 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](https://delta1labs.com/blog/nebula-string-decryption-hot-path-cost-and-scoping) so key material and resource names are not literals, and with [control-flow flattening](https://delta1labs.com/blog/nebula-control-flow-flattening-dispatch-loop) 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](https://delta1labs.com/blog/nebula-1-1-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](https://delta1labs.com/products/nebula) for the full transform set, or the [docs](https://delta1labs.com/docs/nebula/) for the `nebula.config.json` reference and per-method scoping.

