Spam protection without a CAPTCHA: an invisible proof of work in ASP.NET Core
On this page
- Spam protection without a CAPTCHA: an invisible proof of work in ASP.NET Core
- Try it first
- How it works
- Step 1: A form with nothing in front of it
- Step 2: A challenge the server doesn't remember
- Step 3: Verify an answer in one pass
- Step 4: An answer works once
- Step 5: The solver, in a Web Worker
- Step 6: Make it invisible
- Step 7: How hard should it be?
- Step 8: Tests that keep it working
- What a proof of work can't do
- What's dev-only
A public form gets spam. The usual answer is a CAPTCHA, and it has a price: your visitors solve puzzles, another company's script runs on your page, and people who can't see or hear the puzzle are locked out.
A proof of work asks a different question. It doesn't try to find out who is human. It makes every sender pay a little computing time before the server accepts a message: a fraction of a second for someone who writes one message, a real bill for someone who sends a hundred thousand. The visitor sees nothing, because their browser pays while they type.
The one idea to keep through this article: the server hands out a small puzzle that it can check later without having stored it. In this tutorial we will build that for a contact form in ASP.NET Core, with no library for the proof itself, and measure what it costs a visitor and what it costs a bot.

The whole example is on GitHub: gergodrazsdik/example-aspnet-pow. Each step below is one commit and one tag, step-01 to step-08. I only show the code that matters here; the rest is in the repository.
Try it first
You need the .NET 11 SDK (the example also builds and passes its tests on .NET 10; the README says what to change), and bash with curl for the script that plays the bot. There is no database, no container and no cloud.
git clone https://github.com/gergodrazsdik/example-aspnet-pow
cd example-aspnet-pow
dotnet run --project src/PowForm.WebOpen http://localhost:5200, write a message and send it. It lands on the Messages page, and nothing else seems to happen: the proof was solved while you typed. Now be the bot, in a second terminal:
scripts/flood.shHTTP 403: 100 postsThe script posts 100 messages with curl, without the proof, and the server refuses every one.
How it works
The server picks a secret number and sends the SHA-256 hash of a salt followed by that number: the challenge. The browser finds the number the only way there is, by trying 0, 1, 2, … until a hash matches, and sends it back in a hidden form field. The server checks it with one hash, and it needs no stored challenge for that, because the challenge came with a signature only the server can make.
The idea is old: Hashcash proposed it against email spam in 1997. The scheme here follows the first version of ALTCHA, an open-source CAPTCHA alternative. I wrote it from scratch so that every line can be explained; it isn't compatible with ALTCHA's widget.
Step 1: A form with nothing in front of it
The example starts as a plain Razor Pages app (step-01): a contact form with a name, an email address and a message, and a page that lists the accepted messages from memory. scripts/flood.sh posts 100 messages with curl, 20 at a time, and every one is accepted, in about a tenth of a second on my laptop.

A bot doesn't need a browser for this, only the names of the fields.
Step 2: A challenge the server doesn't remember
The server side is one class, ProofOfWork (step-02). This is how it makes a challenge:
public ProofChallenge Create(string purpose)
{
// …
var expires = time.GetUtcNow() + Lifetime;
var random = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(12));
var salt = string.Create(CultureInfo.InvariantCulture, $"{purpose}.{expires.ToUnixTimeSeconds()}.{random}");
var number = RandomNumberGenerator.GetInt32(0, MaxNumber + 1);
var challenge = HashOf(salt, number);
return new ProofChallenge("SHA-256", challenge, salt, MaxNumber, _protector.Protect($"{challenge}\n{salt}"));
}The salt says which form the challenge is for and when it expires (after 10 minutes), and 12 random bytes make every challenge different. HashOf is the SHA-256 of the salt followed by the number, as lowercase hex. The number is thrown away as soon as the hash is made. MaxNumber is the difficulty, 100,000 by default; step 7 is about that number. GET /challenge?for=contact returns the result as JSON.
The signature comes from ASP.NET Core Data Protection, which is part of the framework:
builder.Services.AddDataProtection()
.SetApplicationName("PowForm")
.PersistKeysToFileSystem(new DirectoryInfo(keys));"Signature" is the scheme's word, and it undersells what Protect does: it encrypts the payload and authenticates it. Only the second half is needed here, so an HMAC would do. Data Protection brings what an HMAC doesn't: a key ring that rotates by itself and that several instances can share.
Why sign, and not store the challenge in a table? Because handing out a challenge would then be a write, and anyone can ask for challenges all day without answering one. This way a challenge costs the server one hash and one encryption, and no memory.
Step 3: Verify an answer in one pass
The browser sends back number:signature. Checking it (step-03) reads like a list of reasons to say no:
private (string Challenge, DateTimeOffset Expires)? Check(string purpose, string? answer)
{
if (!TryRead(answer, out var number, out var signature) || Unprotect(signature) is not { } payload)
{
return null;
}
// The payload is what Create signed: "challenge\nsalt". Only the signed salt is used from here on.
var lines = payload.Split('\n');
var parts = lines.Length == 2 ? lines[1].Split('.') : [];
if (parts.Length != 3
|| !string.Equals(parts[0], purpose, StringComparison.Ordinal)
|| !long.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var seconds))
{
return null;
}
var expires = DateTimeOffset.FromUnixTimeSeconds(seconds);
var (challenge, salt) = (lines[0], lines[1]);
if (expires < time.GetUtcNow()
|| !CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(HashOf(salt, number)), Encoding.ASCII.GetBytes(challenge)))
{
return null;
}
return (challenge, expires);
}- Only the number and the signature come from the client. The salt, the expiry and the hash to match are read from the signed payload, so editing them in the browser changes nothing.
- The purpose is inside the signed salt. The example has a second form, a newsletter sign-up, to show why: an answer solved for one form is refused by the other.
- Garbage is refused, not thrown.
Unprotectcatches theCryptographicExceptionthat Data Protection raises for anything it didn't produce. A tampered signature never reaches the hash. - The compare is constant-time. It matters little here, since the browser already holds the hash, but the day a similar check guards a secret it is already right.
All this costs the server one decryption and one SHA-256. It cost the browser 50,000 hashes on average. That asymmetry is the point.
Step 4: An answer works once
So far a solved challenge is good for as many posts as fit into its ten minutes. The fix is the only state the proof of work keeps (step-04), and it is kept only for challenges that were used:
public interface IUsedChallenges
{
Task<bool> TryUseAsync(string challenge, DateTimeOffset expires, CancellationToken cancellationToken = default);
}public async Task<bool> VerifyAsync(string purpose, string? answer, CancellationToken cancellationToken = default)
{
return Check(purpose, answer) is var (challenge, expires)
&& await used.TryUseAsync(challenge, expires, cancellationToken);
}TryUseAsync returns true the first time it sees a challenge and false after that. It is asked last, so a wrong answer never spends a challenge. The example's store is a ConcurrentDictionary, where TryAdd is the atomic "first time", and it sweeps expired entries when it is used. It stays small: an entry lives only a little longer than its challenge, and putting one there costs the sender a solved challenge.
"A little longer" is deliberate. If an entry is dropped at the instant its challenge expires, a replay that passed the expiry check a moment earlier finds it gone and is accepted. The example keeps entries one minute past the expiry.
Scaling out
With several instances, two things have to be shared, and the two failures look nothing alike:
- The Data Protection keys. Without a shared key ring (and the same
SetApplicationName), a replica can't read a signature another one made and refuses the answer. This failure is loud: forms fail for real visitors, at random. - The used-challenge store. If each replica has its own, an answer spent on one is fresh on the next. This failure is silent: one solved challenge buys one message per replica, and no log tells you. The example has a test for exactly this.
For the keys, use one of the PersistKeysTo… providers. For the store, implement the interface over anything with an atomic "insert if absent": a table with a unique key, or Redis SET with NX and an expiry. Let the entry outlive the challenge here too, because the replicas' clocks never agree exactly.
Step 5: The solver, in a Web Worker
The browser's part is a loop (step-05). It runs in a Web Worker so that typing never stutters:
async function solve(salt, challenge, maxNumber, batch) {
const encoder = new TextEncoder();
const target = Uint8Array.from(challenge.match(/../g), (pair) =>
parseInt(pair, 16),
);
for (let start = 0; start <= maxNumber; start += batch) {
const end = Math.min(start + batch - 1, maxNumber);
const digests = [];
for (let number = start; number <= end; number++) {
digests.push(
crypto.subtle.digest("SHA-256", encoder.encode(salt + number)),
);
}
const results = await Promise.all(digests);
for (let i = 0; i < results.length; i++) {
if (same(new Uint8Array(results[i]), target)) {
return start + i;
}
}
}
return null;
}crypto.subtle.digest is asynchronous, so the loop starts a batch of 256 hashes and awaits them together. I expected a lot from that and measured little: in Chromium, batches were about 12 percent faster than one hash at a time.
The page starts the worker with new Worker(new URL("./proof-worker.js", import.meta.url)) and falls back to the same loop on the main thread when a worker can't be started. The example runs under a strict Content Security Policy with no inline script or style. A worker needs worker-src 'self' there (or script-src, which browsers fall back to), and the policy it runs under is the one on the response that delivered its script, so the header has to be on static files too.
crypto.subtleexists only in a secure context: HTTPS, orlocalhost. Open the form over plain HTTP at a LAN address, to try it on your phone for example, andcrypto.subtleisundefined, in the page and in the worker. The example then posts without an answer, and the server refuses with a message that says why. To test on another device, serve the app over HTTPS.
Step 6: Make it invisible
One function, guard(form, purpose) in proof.js, wires the solver to a form (step-06). It starts solving on the first focusin or input event and puts the answer in the form's hidden proof field. By the time someone has typed a name, an address and a sentence, the answer has been there for a while, and Send is an ordinary form post. The submit handler covers the other cases:
- The answer isn't ready. The handler prevents the submit, writes "Just a moment, checking that you are not a bot…" into an
aria-liveregion, waits, and submits withrequestSubmit. - The answer is stale. A challenge lives 10 minutes, so the page solves again on Send when its answer is older than 9. A form left open over lunch still goes through.
- There is no answer. No secure context, or the network is down: the form posts without one, and the server decides.

On the server, the order of the checks matters:
public async Task<IActionResult> OnPostAsync(CancellationToken cancellationToken)
{
// Fields first: a post refused for its text keeps its answer (verifying uses it up).
if (!ModelState.IsValid)
{
Response.StatusCode = StatusCodes.Status422UnprocessableEntity;
return Page();
}
// The proof last, just before saving.
if (await proof.ProblemAsync("contact", Proof, cancellationToken) is { } problem)
{
ProofProblem = problem;
Proof = null;
Response.StatusCode = StatusCodes.Status403Forbidden;
return Page();
}
board.Add(Name!, Email!, Message!);
// …
}Verifying an answer spends it. Do that first, and a typo in the email address burns the answer: the visitor fixes the typo, sends again, and is told that the check "expired or was already used". With the fields first, the form comes back with its answer still in the hidden field, and the second Send works.
That hidden field is written by hand, <input type="hidden" name="proof" value="@Model">, and not with asp-for. Tag helpers prefer the posted value in ModelState to the model, so Proof = null after a refusal would not have cleared it.
A post without an answer gets a refusal the visitor can act on, and keeps what they wrote:

Four traps on the way
Each of these cost time, and each has a test now.
requestSubmit()can silently do nothing. When the solve fails at once (nocrypto.subtle), the code after theawaitstill runs inside the submit event's dispatch, whererequestSubmitreturns without submitting: no error, no request, a dead button. AsetTimeoutbefore it leaves the dispatch first.- A double click. With the answer ready, both clicks post it. The first post is saved, the second is refused as already used, and the refusal is the page the visitor sees. They send again, and you get the message twice.
guardignores further submits for a few seconds once one is under way. - The Back button. A page shown again from history can still hold the spent answer.
guarddrops it on aback_forwardnavigation and onpageshowwithpersisted. - A failure that sticks. A failed solve is not remembered, so the next Send tries again. Remembering the failure would make every later Send fail too.
None of this asks anything of the visitor's eyes, ears or patience, which is half the reason to do it. The W3C's note on the inaccessibility of CAPTCHA lists proof of work among the approaches that need no interaction, and names its cost: it can be slow on old hardware. Which brings us to the number.
Step 7: How hard should it be?
The difficulty is one setting, Proof:MaxNumber (step-07). The secret number is uniform between 0 and MaxNumber, so the work is a matter of luck: half of the challenges need less than half of the maximum, and one in ten needs more than 90 percent of it. Plan for the unlucky visitor, not the average one.
I measured how fast each kind of client hashes, on one laptop (an Intel Core i7-11850H under WSL2, headless Chromium 156 and Firefox 157): a worker in Chromium does about 210,000 hashes per second, in Firefox about 77,000, and a .NET solver written for speed about 2.1 million on one core. As a stand-in for a slow device I pinned Chromium to one core and shared that core four ways: about 53,000. From those rates, the time one solve takes, as median / 95th percentile:
MaxNumber |
Chromium | Four times slower | Firefox | Native, one core |
|---|---|---|---|---|
| 10,000 | 40 ms / 60 ms | 0.13 s / 0.21 s | not measured | 2 ms / 5 ms |
| 100,000 | 0.25 s / 0.47 s | 1.0 s / 1.8 s | 0.65 s / 1.2 s | 24 ms / 45 ms |
| 1,000,000 | 2.4 s / 4.5 s | 9.5 s / 18 s | not measured | 0.24 s / 0.45 s |
These numbers are from one machine, and I did not measure a real phone. The table is computed from the hash rates because the rates are stable and single runs are not: with 30 runs of a workload this random, the measured median at 100,000 was 238 ms, with a 95 percent interval from 159 to 342 ms.
One warning if you measure your own: Chrome's CPU throttling doesn't reach workers. Emulation.setCPUThrottlingRate at 4x slowed the main thread about five times and the worker by about 12 percent.
Now read the last column as an attacker. A challenge costs a bot what it costs a visitor, per message. A bot that drives a headless browser pays a quarter of a second of CPU per message: about 4 messages per second per core. A bot with a native solver pays 24 ms: about 40 per second per core, on every core it has. Picking only the easy challenges doesn't help it: the number is uniform, so giving up on a slow one and starting over costs more hashes on average than finishing it.
My recommendation is the default, 100,000. The solve almost always finishes while the person is still typing, and the unlucky visitor on a slow device waits under two seconds at the Send button. At 1,000,000 that visitor waits around 18 seconds, and the native bot still pays only a quarter of a second. If the default isn't enough, a bigger number is the wrong tool.
Step 8: Tests that keep it working
The last commit (step-08) is tests: unit and endpoint tests with TUnit, and browser tests with Playwright in Chromium and Firefox (I could not run WebKit, so Safari is untested). Two habits from them are worth copying. The tests set MaxNumber between 500 and 20,000, so they test the logic and not the hashing, and one test keeps the default and only checks that solving and posting stay under 20 seconds. And every browser test fails on a Content Security Policy violation, so a worker that stops loading is caught by the build and not by a visitor.
What a proof of work can't do
The technique is easy to oversell, so:
- It doesn't tell people from bots. It prices a message. The flood from step 1, a script that knows only the field names, is stopped completely. A spammer who writes a solver is slowed to a few dozen messages per second per core, which is still a lot of spam.
- It taxes everyone the same, and a slow phone pays the most.
- Plain SHA-256 favours the attacker's hardware. Native code was ten times faster than the browser in my measurements, and GPUs are far better at it than that. ALTCHA's current version moved from a plain hash to key derivation functions, with memory-hard ones (scrypt, Argon2id) to narrow that gap.
So treat it as one layer. It is a good first one: invisible, accessible, private, and it stops the cheapest attacks at almost no cost to you. Real sites put more behind it:
- A honeypot field that people don't see and simple bots fill in.
- A signed form token that says when the form was shown, refused when it comes back too fast or too late. It is the same idea as the challenge, a signed payload the server doesn't store, and it can reuse the used-challenge store.
- Rate limits per address, and moderation for what gets through.
With such layers you also get a choice the example doesn't have. It refuses a post without an answer, because the proof is its only defence. A site with other signals can hold that post for review instead, and not lose the visitor whose browser couldn't solve.
What's dev-only
| Here | In production |
|---|---|
| Data Protection keys in a local folder, unencrypted | A shared key store, keys encrypted at rest (ProtectKeysWith…), the same application name on every replica |
| Used challenges in memory | A shared store with an atomic insert |
Plain HTTP on localhost |
HTTPS, which crypto.subtle needs anyway |
| Antiforgery off, because the form has no cookie or session to protect | On, wherever a form acts for a signed-in user |
| Messages in memory and in the log | Mail or a database, and no message text in the log |
The code is at github.com/gergodrazsdik/example-aspnet-pow, under the MIT No Attribution licence: copy what you need. It's a companion to this article, not a maintained project, so it isn't open for issues, but you're welcome to fork it.
Read it online: https://gergodrazsdik.com/blog/spam-protection-without-captcha-proof-of-work-aspnet-core
Comments
No comments yet.
Leave a comment