jwtk/jjwt · error · InvalidKeyException

The ${keyType(signing)} key's algorithm cannot be null or em

Error message

The ${keyType(signing)} key's algorithm cannot be null or empty.

What it means

InvalidKeyException from DefaultMacAlgorithm.assertAlgorithmName (called from validateKey) when a SecretKey's JCA algorithm name is null or empty. MAC algorithms like HS256 need to verify the key's algorithm matches the Hmac family, which requires a non-empty name.

Source

Thrown at impl/src/main/java/io/jsonwebtoken/impl/security/DefaultMacAlgorithm.java:135

        if (size >= mac.getKeyBitLength()) {
            return mac;
        }

        return null; // couldn't find a suitable match
    }


    @Override
    public SecretKeyBuilder key() {
        return new DefaultSecretKeyBuilder(getJcaName(), getKeyBitLength());
    }

    private void assertAlgorithmName(SecretKey key, boolean signing) {

        String name = key.getAlgorithm();
        if (!Strings.hasText(name)) {
            String msg = "The " + keyType(signing) + " key's algorithm cannot be null or empty.";
            throw new InvalidKeyException(msg);
        }

        // We can ignore key name assertions for generic secrets, because HSM module key algorithm names
        // don't always align with JCA standard algorithm names
        boolean generic = KeysBridge.isGenericSecret(key);

        //assert key's jca name is valid if it's a JWA standard algorithm:
        if (!generic && isJwaStandard() && !isJwaStandardJcaName(name)) {
            throw new InvalidKeyException("The " + keyType(signing) + " key's algorithm '" + name +
                    "' does not equal a valid HmacSHA* algorithm name or PKCS12 OID and cannot be used with " +
                    getId() + ".");
        }
    }

    @Override
    protected void validateKey(Key k, boolean signing) {

        final String keyType = keyType(signing);

View on GitHub (pinned to fb71496164)

Solutions

  1. Specify a valid algorithm name: new SecretKeySpec(bytes, "HmacSHA256") for HS256.
  2. Let jjwt create the key: Jwts.SIG.HS256.key().build() or Keys.secretKeyFor(SignatureAlgorithm).
  3. If wrapping a raw secret, use io.jsonwebtoken.security.Keys.hmacShaKeyFor(bytes) which sets the proper algorithm.
  4. Fix the custom SecretKey implementation to return a non-empty algorithm name.

Example fix

// before
SecretKey key = new SecretKeySpec(secretBytes, "");
Jwts.parser().verifyWith(key).build().parseSignedClaims(jwt);
// after
SecretKey key = Keys.hmacShaKeyFor(secretBytes); // algorithm set automatically
Jwts.parser().verifyWith(key).build().parseSignedClaims(jwt);
Defensive patterns

Strategy: type-guard

Validate before calling

static SecretKey requireNamedSecretKey(SecretKey k) {
    if (k == null || k.getAlgorithm() == null || k.getAlgorithm().isEmpty())
        throw new IllegalArgumentException("MAC key must have a non-empty algorithm name");
    return k;
}

Type guard

boolean hasAlgorithmName(Key k) {
    return k instanceof SecretKey && k.getAlgorithm() != null && !k.getAlgorithm().isEmpty();
}

Try / catch

try {
    return Jwts.builder().signWith(key, Jwts.SIG.HS256).compact();
} catch (InvalidKeyException e) {
    logger.error("Invalid MAC key: {}", e.getMessage());
    throw e;
}

Prevention

When it happens

Trigger: Constructing a SecretKeySpec with a null/empty algorithm string and passing it to Jwts.builder().signWith(key, HS256) or parser verifyWith; deserializing a key from a store that dropped the algorithm attribute.

Common situations: new SecretKeySpec(bytes, "") or new SecretKeySpec(bytes, null); custom SecretKey implementations returning null from getAlgorithm(); keys built by third-party crypto providers with incomplete metadata.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of jwtk/jjwt@fb71496164 (2026-09-09). Data as JSON: /api/errors/96cb82dc7f3fc507. Report an issue: GitHub.