Back Home

What Is a Hardware Security Key? A Complete Guide to WebAuthn and Passwordless Login

Starting from everything wrong with passwords, this article systematically unpacks hardware security keys and WebAuthn — their history (U2F, FIDO2), the underlying technology (public-key cryptography, challenge-response, origin binding, with real API code), and why they fundamentally defeat phishing to become the most secure authentication method available today.

Mason Zheng avatar
  • Mason Zheng
What Is a Hardware Security Key? A Complete Guide to WebAuthn and Passwordless Login
Hardware keys and WebAuthn are sending the "password" into history.

If you asked a security expert to name “the weakest link on the Internet,” the answer would almost certainly be: passwords. We’re asked to set passwords that are long, complex, and unique — yet nearly impossible to remember. Meanwhile, phishing sites, credential-stuffing attacks, and database breaches harvest those passwords in bulk every single day.

The industry’s ultimate answer to this dilemma is an authentication method that barely depends on “what you remember” and instead relies on “what you possess” — the hardware security key, along with the open standard that powers it: WebAuthn. This article walks you through it end to end: history, technical principles (with real code), and security.


1. Understand the Problem First: What’s Actually Wrong with Passwords?

Before diving into hardware keys, we need to see the fundamental flaws of the password model clearly:

  1. The Shared-Secret model: Your password exists both in your head and on the server. The moment the server is breached, that secret leaks. Even if the server only stores hashes, weak passwords still fall to credential stuffing or rainbow tables.
  2. They’re phishable: A password is “tellable.” A convincing enough phishing site can trick you into typing it in yourself. SMS codes and TOTP (time-based one-time passwords) are equally tellable — so they fall too.
  3. They get reused: People tend to reuse the same password across many sites. One leak, and everything falls.

The two-factor authentication (2FA) that later became popular — SMS codes and Google Authenticator — did raise the bar, but it never solved the core “phishable” problem: an attacker can simply run a real-time relay phishing site, forwarding both your password and your one-time code to the genuine website.

The design goal of the hardware key is to eliminate these two flaws at the cryptographic level.


2. What Is a Hardware Security Key?

A hardware security key is a standalone physical device, usually about the size of a USB stick, that connects to your computer or phone via USB, NFC, or Bluetooth. The most famous product is Yubico’s YubiKey; others include Google Titan, SoloKeys, and Feitian.

It has exactly one core duty: to securely generate and guard a private key inside the device, and to prove your identity using that private key — while the private key never leaves the chip.

It differs fundamentally from every other verification method you’ve seen:

MethodBased onPhishable?Consequence of server breach
PasswordA secret you rememberYesSecret leaks
SMS codeA temporary code you receiveYes (and SIM-swappable)—
TOTPA code derived from a shared seedYesSeed leak allows cloning
Hardware key / WebAuthnA private key you holdNoOnly a public key leaks — worthless

The two entries in the last row — “No” and “worthless” — are the entire value proposition of the hardware key. We’ll explain technically how it pulls this off.


3. History: The Standards Journey from U2F to FIDO2

Hardware keys became today’s industry standard not because of any single company, but through a series of standards driven by an open alliance.

  • 2012–2013 | The FIDO Alliance is founded: The FIDO (Fast IDentity Online) Alliance was founded by PayPal, Lenovo, and others, with the goal of replacing passwords with open standards. Google, Microsoft, and Apple all joined later.
  • 2014 | U2F is born: FIDO released the U2F (Universal 2nd Factor) standard, led by Google and Yubico. This was the first generation of hardware keys — as a “second lock” beyond the password, it delivered phishing-resistant second-factor authentication for the first time.
  • 2018–2019 | FIDO2 and WebAuthn: The FIDO Alliance partnered with the W3C (World Wide Web Consortium) to launch the next-generation standard, FIDO2. In March 2019, WebAuthn became an official W3C Recommendation, meaning all major browsers would support it natively.
  • 2022–present | Passkeys: Apple, Google, and Microsoft, together with the FIDO Alliance, introduced Passkeys — repackaging FIDO2 technology into a form friendlier to ordinary users, with cross-device cloud sync, finally bringing passwordless login to the masses.

A few often-confused terms need clarifying here:

FIDO2 = WebAuthn + CTAP

  • WebAuthn: The API standard between the browser and the website, defining how a web page invokes the authenticator.
  • CTAP (Client to Authenticator Protocol): The protocol between your computer/phone and the hardware key. CTAP1 is the old U2F; CTAP2 is the new FIDO2 protocol.

In short: WebAuthn governs “browser ↔ server,” CTAP governs “browser ↔ hardware key,” and together they form complete FIDO2.


4. How It Works: How Public-Key Cryptography Replaces Passwords

The foundation of the hardware key is asymmetric encryption (public-key cryptography) — a mathematically related key pair: the private key signs, the public key verifies, and you cannot derive the private key from the public key. (If you’re curious about encryption algorithms themselves, start with What Is AES Encryption for a symmetric-encryption counterpoint.)

The whole flow consists of two “ceremonies”: Registration and Authentication. Let’s pull each step apart using the browser’s native WebAuthn API.

4.1 Registration: navigator.credentials.create()

When you first bind a hardware key to a site, the front end issues a request to create a credential. The server first sends down a random challenge; the front end then assembles the parameters below:

// challengeFromServer / userIdBytes both come from the server, as raw binary (ArrayBuffer)
const credential = await navigator.credentials.create({
  publicKey: {
    // ① Challenge: must be server-generated, random, and single-use — prevents replay
    challenge: challengeFromServer,

    // ② Relying Party (your website). id must be the current domain or a parent domain
    rp: { id: "example.com", name: "Example Inc." },

    // ③ User info. id should be random bytes unrelated to email, to avoid leaking PII
    user: {
      id: userIdBytes,
      name: "[email protected]",
      displayName: "Alice",
    },

    // ④ Accepted signing algorithms, in priority order (COSE algorithm identifiers)
    //    -7 = ES256 (ECDSA P-256), -257 = RS256 (RSA), -8 = EdDSA
    pubKeyCredParams: [
      { type: "public-key", alg: -7 },
      { type: "public-key", alg: -257 },
    ],

    // ⑤ Authenticator selection policy
    authenticatorSelection: {
      // platform = built-in (fingerprint/Face ID); cross-platform = external hardware key
      authenticatorAttachment: "cross-platform",
      residentKey: "required",        // create a "discoverable credential" — enables usernameless login
      userVerification: "preferred",  // whether to require PIN / biometrics
    },

    attestation: "direct",   // request an attestation statement (see 4.6)
    excludeCredentials: [],  // IDs of already-registered credentials, to prevent re-registering the same key
    timeout: 60000,
  },
});

After the user presses the key’s button (or verifies via fingerprint/PIN), credential is a PublicKeyCredential object with these key fields:

credential.id                          // base64url-encoded credential ID
credential.rawId                       // same, as an ArrayBuffer
credential.response.clientDataJSON     // client data (see 4.2)
credential.response.attestationObject  // CBOR-encoded attestation object (contains the public key)

4.2 Dissecting the Registration Response

This is the key to understanding WebAuthn’s security model. The front end base64-encodes the two ArrayBuffers above and sends them back to the server, which decodes two things.

(1) clientDataJSON — a UTF-8 JSON string recording “the context the browser saw”:

{
  "type": "webauthn.create",
  "challenge": "p5aV2uHXr0AOqUk7HQitvi-Ny1k...",  // base64url, must match the value sent down
  "origin": "https://example.com",                 // the actual origin the browser is at
  "crossOrigin": false
}

Note: challenge and origin are both filled in by the browser and folded into the subsequent signature — page scripts cannot forge them. This is exactly the bedrock of replay resistance and phishing resistance.

(2) attestationObject — a chunk of CBOR (binary JSON) that decodes to:

{
  "fmt":     "packed",            // attestation format
  "attStmt": { alg, sig, x5c },   // attestation signature + certificate chain
  "authData": <bytes>             // authenticator data — see the byte layout below
}

Here, authData (authenticator data) is a compact binary blob with a fixed byte layout:

OffsetLength (bytes)FieldNotes
032rpIdHashSHA-256(rpId), binds the domain
321flagsFlag bits, see below
334signCountSignature counter (big-endian)
3716aaguidAuthenticator model identifier (registration only)
532credIdLen (L)Credential ID length (registration only)
55LcredentialIdCredential ID (registration only)
55+LvariablecredentialPublicKeyThe public key, in COSE_Key format (CBOR)

The flags byte is defined bit by bit; the most commonly used ones:

bit 0 (0x01)  UP  User Present   —— user is present (pressed the button)
bit 2 (0x04)  UV  User Verified  —— user was verified (PIN / biometric passed)
bit 6 (0x40)  AT  Attested data  —— attestedCredentialData included (1 at registration)
bit 7 (0x80)  ED  Extension data —— extension data included

The server extracts the public key from credentialPublicKey and stores it in the database along with the credentialId. Registration is now complete. Throughout, the server only ever holds a public key — no secret that could be used to impersonate the user.

4.3 Authentication: navigator.credentials.get()

For every subsequent login, the server sends a fresh challenge and the front end calls:

const assertion = await navigator.credentials.get({
  publicKey: {
    challenge: challengeFromServer,   // yet another brand-new random value
    rpId: "example.com",
    allowCredentials: [{
      type: "public-key",
      id: storedCredentialIdBytes,    // the credential ID saved at registration
      transports: ["usb", "nfc", "ble", "internal"],
    }],
    userVerification: "preferred",
    timeout: 60000,
  },
});

// After signing with the private key, the authenticator returns:
assertion.response.authenticatorData  // same as authData in 4.2 (no public key during auth)
assertion.response.clientDataJSON     // this time type is "webauthn.get"
assertion.response.signature          // the crucial part: the digital signature over the challenge
assertion.response.userHandle         // i.e. the user.id from registration (optional)

4.4 How the Server Verifies the Signature

This is the “referee” step of the whole flow. What the authenticator signs is a fixed concatenation: authenticatorData ‖ SHA-256(clientDataJSON). The server simply verifies it with the public key saved at registration. Here is the core logic in Node.js:

import crypto from "node:crypto";

// 0. clientDataJSON / authenticatorData / signature are sent back by the front end
const clientData = JSON.parse(clientDataJSON.toString("utf8"));

// 1. Verify context: type, challenge, origin
assert(clientData.type === "webauthn.get");
assert(clientData.challenge === base64url(expectedChallenge)); // anti-replay
assert(clientData.origin === "https://example.com");           // anti-phishing

// 2. Verify authenticatorData
const rpIdHash = authData.subarray(0, 32);
assert(rpIdHash.equals(crypto.createHash("sha256").update("example.com").digest()));
const flags = authData[32];
assert(flags & 0x01);            // UP: user must be present
// If your business requires strong verification: assert(flags & 0x04);  // UV
const signCount = authData.readUInt32BE(33);

// 3. Reconstruct the signed data and verify
const clientDataHash = crypto.createHash("sha256").update(clientDataJSON).digest();
const signedData = Buffer.concat([authData, clientDataHash]);

const ok = crypto.verify(
  "sha256",            // ES256 uses SHA-256
  signedData,
  storedPublicKey,     // the public key saved at registration (KeyObject)
  signature,           // for ES256 the signature is ASN.1 DER-encoded
);
assert(ok);            // verification passes = the device holding the private key is present

// 4. Anti-clone: the counter must strictly increase (unless the authenticator always reports 0)
assert(signCount === 0 || signCount > storedSignCount);
storedSignCount = signCount;     // update the stored value

As long as all of these steps pass, you can be cryptographically certain that “the physical device holding the correct private key, bound to this domain, is present in front of the user right now.”

In production, do not hand-roll the low-level logic above. Use a battle-tested library to handle CBOR parsing, attestation verification, algorithm compatibility, and other details — for example: @simplewebauthn/server (JS), webauthn4j (Java), py_webauthn (Python), or go-webauthn (Go).

4.5 The Key Mechanism: Origin Binding

Looking back at 4.2 / 4.4, you’ll notice that origin and rpIdHash are always folded into the signature check. This is the soul of WebAuthn’s phishing resistance: from the moment a credential is created, it is tightly bound to a specific domain (RP ID), and the browser also writes the current page’s real origin into the signed data.

So: even if the phishing site g00gle.com looks exactly like google.com, the origin the browser hands to the authenticator is g00gle.com, the server’s comparison fails, and verification is rejected outright. Even if the user is fooled into clicking the link, it is technically impossible to hand the credential to the fake site — something passwords, SMS, and TOTP can never achieve.

4.6 Signature Counter and Attestation

  • Signature counter: see step 4 of 4.4. The authenticator increments an internal counter on every signature; the server uses it to detect “the credential was cloned and replayed” anomalies (two copies cause the count to regress or repeat).
  • Attestation: at registration, attestationObject.attStmt carries a statement signed by a manufacturer certificate, telling the server “I am a genuine authenticator of brand X, model Y.” High-security scenarios such as banks and governments can rely on this to trust only hardware of a specific certification level.

5. Security: Why It’s “Practically Unbreakable”

Pulling the principles together, the security advantages of hardware keys over traditional methods become crystal clear:

  1. Fully phishing-resistant: thanks to origin binding — its most celebrated property, and one SMS / TOTP can never match.
  2. Zero sensitive data on the server: the server stores only public keys. Even if the entire user database is exfiltrated, the attacker gets nothing usable for login — fundamentally dismantling “credential stuffing” and “mass leaks.”
  3. The private key never leaves the hardware: it’s sealed in a dedicated secure chip, unreadable and uncopyable by software, and unstealable by malware.
  4. Replay-proof: every challenge is random and single-use, so an intercepted old signature can’t be reused.
  5. Requires physical presence: even if an attacker remotely controls your computer, they can’t “press” the key for you.

In effect, hardware keys raise the cost of attack from “remote bulk harvesting” to “physically steal the specific key from your hand and pass your biometric/PIN check” — exactly the goal good security design strives for.


6. Passkeys: Putting the Hardware Key Inside Your Phone

Hardware keys are great, but carrying a physical device that can be lost raises the barrier to entry. Passkeys were created to lower that barrier — they’re still FIDO2 credentials at heart, but the “authenticator” role is handed to your phone or computer (unlocked with fingerprint, Face ID, or PIN).

Passkeys come in two main forms:

  • Synced passkeys: the private key is end-to-end encrypted and synced across all your devices via iCloud Keychain, Google Password Manager, etc. The upside is you don’t lose it when you switch phones, and the experience is seamless; the trade-off is that security partly depends on your cloud account’s security.
  • Device-bound passkeys: the private key is strictly locked inside a single device (such as a hardware key itself) and never synced. Highest security, but losing the device means losing that credential.

Either way, passkeys inherit WebAuthn’s core advantages — phishing resistance and no shared secret — and are currently the most promising “password replacement.”


7. Limitations and Caveats

Hardware keys are no silver bullet. Know their real-world constraints before adopting:

  • Loss and backup: a physical key can be lost or damaged. Best practice is to register at least two keys (one to carry, one backed up somewhere safe) to avoid a single point of failure locking you out.
  • Cost: a hardware key typically costs anywhere from a few to a few hundred yuan — a real expense for individuals and large-scale deployments alike. Passkeys are free, which is why they’re spreading faster.
  • Coverage: although major vendors already support it widely, plenty of smaller sites still don’t support WebAuthn, so passwords will coexist with it for the foreseeable future.

Conclusion

From U2F to FIDO2 to today’s passkeys, hardware keys and WebAuthn use one elegant public-key-cryptography design to systematically cure the two chronic diseases of the password era — “shared secrets” and “phishability”: the private key never leaves your possession, the server only ever stores a harmless public key, and credentials are bound tightly to the domain. That’s what makes it the most secure authentication method recognized today.

Authentication solves the problem of “proving you are you,” while data encryption solves “making data unreadable even if it falls into someone else’s hands” — two complementary sides of digital security. While you guard the entrance to your accounts with a hardware key, don’t forget to add a layer of encryption to your truly confidential files. LocalFileEncrypt.com is exactly that kind of tool: it encrypts your files locally in your browser with AES-256-GCM, never uploading anything to a server, so your data always stays firmly in your own hands.

Recommended For You

What Is HTTPS?

What Is HTTPS?

A comprehensive deep dive into the principles of HTTPS and its value in modern Internet security, covering HTTP features, the reasons behind HTTPS, encryption mechanisms, certificate systems, security measures, and potential weaknesses, providing systematic guidance for network communication and privacy protection.

HTTPS Encryption
Author: Mason Zheng
Exploring the Digital World’s Ironclad Defense: AES Encryption Algorithm

Exploring the Digital World’s Ironclad Defense: AES Encryption Algorithm

In the digital era, data security is a necessity for everyone. Whether it is online banking, instant messaging, or cloud storage, our privacy and sensitive information rely on encryption technologies. Among numerous algorithms, AES (Advanced Encryption Standard) stands out for its efficiency and security, and is globally recognized as an information security “guardian.”

AES Encryption Pinned Post
Author: Mason Zheng