{"record":{"id":"e3dc21bd15ab1a9b","repo":"jwtk/jjwt","slug":"msgprefix-type-key-must-be-an-instance-of-c","errorCode":null,"errorMessage":"${msgPrefix}${type} key must be an instance of ${clazz.getName()}. Type found: ${key.getClass().getName()}","messagePattern":"(.+?)(.+?) key must be an instance of (.+?)\\. Type found: (.+?)","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"impl/src/main/java/io/jsonwebtoken/impl/security/KeyPairs.java","lineNumber":57,"sourceCode":"        }\n    }\n\n    public static <K> K getKey(KeyPair pair, Class<K> clazz) {\n        Assert.notNull(pair, \"KeyPair cannot be null.\");\n        String prefix = familyPrefix(clazz) + \"KeyPair \";\n        boolean isPrivate = PrivateKey.class.isAssignableFrom(clazz);\n        Key key = isPrivate ? pair.getPrivate() : pair.getPublic();\n        return assertKey(key, clazz, prefix);\n    }\n\n    public static <K> K assertKey(Key key, Class<K> clazz, String msgPrefix) {\n        Assert.notNull(key, \"Key argument cannot be null.\");\n        Assert.notNull(clazz, \"Class argument cannot be null.\");\n        String type = key instanceof PrivateKey ? \"private\" : \"public\";\n        if (!clazz.isInstance(key)) {\n            String msg = msgPrefix + type + \" key must be an instance of \" + clazz.getName() +\n                \". Type found: \" + key.getClass().getName();\n            throw new IllegalArgumentException(msg);\n        }\n        return clazz.cast(key);\n    }\n}\n","sourceCodeStart":39,"sourceCodeEnd":62,"githubUrl":"https://github.com/jwtk/jjwt/blob/fb71496164c71442d08adec4571d9616ed5e1b8d/impl/src/main/java/io/jsonwebtoken/impl/security/KeyPairs.java#L39-L62","documentation":"KeyPairs.assertKey verifies that a key handed to a KeyPairBuilder (via getKey) is an instance of the expected key class (e.g. RSAPrivateKey, ECPublicKey). If not, it throws IllegalArgumentException stating the required class and the actual type found. The 'private'/'public' prefix in the message identifies which half of the pair failed the check.","triggerScenarios":"Calling KeyPairs (e.g. Jwks.builder().keyPair(...).privateKey(key) or .publicKey(key)) with a key of the wrong type/interface, such as passing a generic PrivateKey or a DH key where an RSA key is required, or swapping private/public arguments.","commonSituations":"Passing keys loaded from a keystore under the wrong algorithm (EC key where RSA expected); using a PKCS11 provider key that implements a different interface; accidentally passing the public key to the privateKey slot; keys of unsupported algorithms (Edwards vs EC confusion).","solutions":["Read the required class name in the message and ensure the key implements it (e.g. java.security.interfaces.RSAPrivateKey).","Generate/load keys with the correct algorithm: KeyPairGenerator.getInstance(\"RSA\") for RSA, \"EC\" for EC.","Swap the arguments if private/public were transposed.","If the key is from a provider wrapper, extract the underlying key via its getFormat/encoding or use the provider's native interface."],"exampleFix":"// before\nKeyPair kp = KeyPairGenerator.getInstance(\"EC\").generateKeyPair();\nJwks.builder().keyPair(kp).privateKey(kp.getPublic()); // wrong slot\n\n// after\nJwks.builder().keyPair(kp)\n    .privateKey((ECPrivateKey) kp.getPrivate())\n    .publicKey((ECPublicKey) kp.getPublic()).build();","handlingStrategy":"type-guard","validationCode":"boolean isRsaKeyPair(KeyPair kp) {\n    return kp.getPublic() instanceof java.security.interfaces.RSAPublicKey\n        && kp.getPrivate() instanceof java.security.interfaces.RSAPrivateKey;\n}","typeGuard":"if (key instanceof java.security.interfaces.RSAPrivateKey rsa) {\n    builder.privateKey(rsa);\n} else {\n    throw new IllegalArgumentException(\"Expected RSAPrivateKey, got \" + key.getClass().getName());\n}","tryCatchPattern":"try {\n    jwk = builder.build();\n} catch (IllegalArgumentException e) {\n    if (e.getMessage().contains(\"key must be an instance of\")) {\n        // regenerate or cast keys to the expected interface\n    } else throw e;\n}","preventionTips":["Generate keys with KeyPairGenerator using the algorithm matching your intended JWK family (RSA/EC/EdDSA).","Never pass generic Key/PrivateKey references; hold typed interfaces (RSAPublicKey, ECPrivateKey).","Assert key types in unit tests before building JWKs."],"tags":["keypair","type-mismatch","cryptography","jsonwebtoken"],"backgroundTag":"type-mismatch","analyzedSha":"fb71496164c71442d08adec4571d9616ed5e1b8d","analyzedAt":"2026-09-09T00:33:09.982Z","contentChangedAt":"2026-09-09T00:33:09.982Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}