{"record":{"id":"513acdf464243212","repo":"jwtk/jjwt","slug":"unable-to-encode-secretkey-to-jwk-t-getmessage","errorCode":null,"errorMessage":"Unable to encode SecretKey to JWK: ${t.getMessage()}","messagePattern":"Unable to encode SecretKey to JWK: (.+?)","errorType":"exception","errorClass":"InvalidKeyException","httpStatus":null,"severity":"error","filePath":"impl/src/main/java/io/jsonwebtoken/impl/security/SecretJwkFactory.java","lineNumber":58,"sourceCode":" */\nclass SecretJwkFactory extends AbstractFamilyJwkFactory<SecretKey, SecretJwk> {\n\n    SecretJwkFactory() {\n        super(DefaultSecretJwk.TYPE_VALUE, SecretKey.class, DefaultSecretJwk.PARAMS);\n    }\n\n    @Override\n    protected SecretJwk createJwkFromKey(JwkContext<SecretKey> ctx) {\n        SecretKey key = Assert.notNull(ctx.getKey(), \"JwkContext key cannot be null.\");\n        String k;\n        byte[] encoded = null;\n        try {\n            encoded = KeysBridge.getEncoded(key);\n            k = Encoders.BASE64URL.encode(encoded);\n            Assert.hasText(k, \"k value cannot be null or empty.\");\n        } catch (Throwable t) {\n            String msg = \"Unable to encode SecretKey to JWK: \" + t.getMessage();\n            throw new InvalidKeyException(msg, t);\n        } finally {\n            Bytes.clear(encoded);\n        }\n\n        MacAlgorithm mac = DefaultMacAlgorithm.findByKey(key);\n        if (mac != null) {\n            ctx.put(AbstractJwk.ALG.getId(), mac.getId());\n        }\n\n        ctx.put(DefaultSecretJwk.K.getId(), k);\n\n        return createJwkFromValues(ctx);\n    }\n\n    private static void assertKeyBitLength(byte[] bytes, MacAlgorithm alg) {\n        long bitLen = Bytes.bitLength(bytes);\n        long requiredBitLen = alg.getKeyBitLength();\n        if (bitLen < requiredBitLen) {","sourceCodeStart":40,"sourceCodeEnd":76,"githubUrl":"https://github.com/jwtk/jjwt/blob/fb71496164c71442d08adec4571d9616ed5e1b8d/impl/src/main/java/io/jsonwebtoken/impl/security/SecretJwkFactory.java#L40-L76","documentation":"Thrown as InvalidKeyException when a SecretKey cannot be encoded to bytes (KeysBridge.getEncoded) and Base64URL-encoded into the JWK 'k' parameter while building a SecretJwk. The original throwable's message is included as the cause.","triggerScenarios":"Building a JWK from a SecretKey whose getEncoded() returns null or fails, e.g. hardware/PKCS11-backed or destroyable keys, or keys from providers that refuse export when calling JwkBuilder/JWK creation APIs.","commonSituations":"Using keys stored in an HSM/keystore that prohibit key export; keys already destroyed (DestroyFailedException paths); platform-specific providers (Android Keystore) returning null encodings.","solutions":["Use an exportable SecretKey (e.g. generated with Keys.secretKeyFor or SecretKeySpec) when building a JWK.","If the key lives in an HSM/keystore, do not build a JWK from it; reference it by key ID instead of embedding key material.","Check the cause for the exact provider failure and ensure the key is not destroyed or cleared before JWK creation."],"exampleFix":"// before\nSecretKey key = keystore.getKey(alias, null); // non-exportable HSM key\nJwk jwk = Jwts.builder().keys().build(key);\n// after\nSecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256); // exportable\nJwk jwk = Jwts.builder().keys().build(key);","handlingStrategy":"validation","validationCode":"byte[] encoded = secretKey.getEncoded();\nif (encoded == null || encoded.length == 0) throw new IllegalStateException(\"SecretKey is not exportable\");","typeGuard":"boolean isExportableSecretKey(SecretKey k) { return k.getEncoded() != null && k.getEncoded().length > 0; }","tryCatchPattern":"try { /* build SecretJwk */ } catch (InvalidKeyException e) { throw new IllegalStateException(\"Key not exportable; use an in-memory SecretKey\", e); }","preventionTips":["Only build JWKs from in-memory, exportable SecretKeys (SecretKeySpec / Keys.secretKeyFor).","Never attempt to embed HSM/Android-Keystore keys into JWKs.","Ensure keys are not destroyed/cleared before JWK creation."],"tags":["secretkey","jwk","encoding","invalid-key"],"backgroundTag":"invalid-argument-value","analyzedSha":"fb71496164c71442d08adec4571d9616ed5e1b8d","analyzedAt":"2026-09-09T00:33:09.982Z","contentChangedAt":"2026-09-09T00:33:09.982Z","schemaVersion":2},"datasetVersion":"2026-09-17T15:17:12.973Z"}