Course contentsShow
← Node.js
Lesson 958 of 1,9809. Authentication and Identity ManagementFree lesson

Signature Verification with HMAC vs RSA

Choose between symmetric and asymmetric signing algorithms for token validation.

In this lesson, you will learn how to choose between symmetric (HMAC) and asymmetric (RSA) algorithms to ensure the integrity and authenticity of your JSON Web Tokens.

When you issue a token, you must sign it so the receiver can verify it hasn't been tampered with. The choice between HMAC and RSA depends on how your architecture handles trust.

HMAC (Symmetric Signing)

HMAC uses a single "shared secret" to both sign and verify the token.

  • How it works: Your authentication server and your resource server both need access to the same secret string.
  • The trade-off: It is computationally fast, but if you have a microservices architecture, you must distribute that secret to every service that needs to verify the token. If one service is compromised, the entire security chain is broken.
// Using symmetric HS256 (HMAC with SHA-256)
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'your-very-secret-shared-key');

RSA (Asymmetric Signing)

RSA uses a key pair: a private key to sign the token and a public key to verify it.

  • How it works: The authentication server holds the private key (strictly secret), while any resource server only needs the public key.
  • The trade-off: Verification is slightly more intensive for the CPU, but it is significantly more secure in distributed systems. A resource server with the public key can verify that a token came from your auth server, but it cannot create new, valid tokens.
// Using asymmetric RS256 (RSA with SHA-256)
const privateKey = fs.readFileSync('private.pem');
const token = jwt.sign({ userId: 123 }, privateKey, { algorithm: 'RS256' });

Which should you choose?

If you are building a small, monolithic application where only one service handles both auth and data access, HMAC is perfectly efficient and easy to manage. However, if your application involves multiple services or distributed systems, RSA is the industry standard because it isolates the power to "sign" tokens to a single, secure location.

Key Takeaway: Use HMAC for simple, monolithic apps where sharing a secret is safe, and use RSA for distributed systems to ensure that only the authentication authority can generate valid tokens.