{"record":{"id":"11d5a8b205e5567d","repo":"jwtk/jjwt","slug":"cannot-obtain-required-encoded-bytes-from-key-k","errorCode":null,"errorMessage":"Cannot obtain required encoded bytes from key [${KeysBridge.toString(key)}]: ${t.getMessage()}","messagePattern":"Cannot obtain required encoded bytes from key \\[(.+?)\\]: (.+?)","errorType":"exception","errorClass":"InvalidKeyException","httpStatus":null,"severity":"error","filePath":"impl/src/main/java/io/jsonwebtoken/impl/security/KeysBridge.java","lineNumber":151,"sourceCode":"            bitlen = ecKey.getParams().getOrder().bitLength();\n        } else {\n            // We can check additional logic for EdwardsCurve even if the current JDK version doesn't support it:\n            EdwardsCurve curve = EdwardsCurve.findByKey(key);\n            if (curve != null) bitlen = curve.getKeyBitLength();\n        }\n\n        return bitlen;\n    }\n\n    public static byte[] getEncoded(Key key) {\n        Assert.notNull(key, \"Key cannot be null.\");\n        byte[] encoded;\n        try {\n            encoded = key.getEncoded();\n        } catch (Throwable t) {\n            String msg = \"Cannot obtain required encoded bytes from key [\" + KeysBridge.toString(key) + \"]: \" +\n                    t.getMessage();\n            throw new InvalidKeyException(msg, t);\n        }\n        if (Bytes.isEmpty(encoded)) {\n            String msg = \"Missing required encoded bytes for key [\" + toString(key) + \"].\";\n            throw new InvalidKeyException(msg);\n        }\n        return encoded;\n    }\n\n    public static String toString(Key key) {\n        if (key == null) {\n            return \"null\";\n        }\n        if (key instanceof PublicKey) {\n            return key.toString(); // safe to show internal key state as it's a public key\n        }\n        // else secret or private key, don't show internal key state, just public attributes\n        return \"class: \" + key.getClass().getName() +\n                \", algorithm: \" + key.getAlgorithm() +","sourceCodeStart":133,"sourceCodeEnd":169,"githubUrl":"https://github.com/jwtk/jjwt/blob/fb71496164c71442d08adec4571d9616ed5e1b8d/impl/src/main/java/io/jsonwebtoken/impl/security/KeysBridge.java#L133-L169","documentation":"KeysBridge.getEncoded retrieves the platform-encoded bytes of a Key. If key.getEncoded() throws (provider error, hardware key refusing export), the method wraps it in InvalidKeyException with this message. jjwt requires the encoded bytes for many operations (e.g. deriving key material for MAC/AES keys), and a key whose provider fails during encoding is unusable.","triggerScenarios":"Calling jjwt APIs that require encoded key bytes (e.g. Keys桥 conversions, MAC/AES key normalization) with a key whose getEncoded() throws — commonly hardware/HSM- or PKCS#11-backed keys, or keys from providers that restrict export.","commonSituations":"Smartcard/HSM keys where export is forbidden by security policy; Android Keystore keys that cannot be encoded; keys wrapped in custom Provider implementations with buggy getEncoded().","solutions":["Read the cause to identify the provider-level failure and check the key's provider logs.","Use a software key (KeyGenerator/KeyFactory) when the operation requires exported bytes.","For HSM keys, perform signing/verification inside the token instead of extracting bytes, using provider-specific APIs.","Check the cause's message in the exception to see the exact provider error and consult its documentation."],"exampleFix":"// before\nSecretKey hsmKey = keystore.getKey(alias, null); // PKCS11, getEncoded throws\nJwts.builder().signWith(hsmKey); // InvalidKeyException\n\n// after\nSecretKey softwareKey = KeyGenerator.getInstance(\"HmacSha256\").generateKey();\nJwts.builder().signWith(softwareKey); // software key with accessible encoded bytes","handlingStrategy":"try-catch","validationCode":"boolean canExportBytes(Key key) {\n    try { return key.getEncoded() != null && key.getEncoded().length > 0; }\n    catch (Throwable t) { return false; }\n}","typeGuard":null,"tryCatchPattern":"try {\n    jjwtOperation(key);\n} catch (InvalidKeyException e) {\n    if (e.getMessage().startsWith(\"Cannot obtain required encoded bytes\")) {\n        // swap to a software key or perform the operation inside the HSM\n    } else throw e;\n}","preventionTips":["Test key.getEncoded() early at startup for any key you plan to use with jjwt.","Prefer software-generated keys for MAC/AES-based jjwt operations.","Document that HSM/smartcard keys may not be exportable and design around provider-side crypto."],"tags":["key","encoded-bytes","invalidkey","hsm","jsonwebtoken"],"backgroundTag":"invalid-key-material","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"}