import com.nimbusds.jose.jwk.JWK;import java.nio.file.Files;import java.nio.file.Path; public class Thumbprint { public static void main(String[] args) throws Exception { // From a JWK: computeThumbprint() hashes the required members only (SHA-256) for (String file : new String[] {"ec.jwk.json", "rsa.jwk.json", "okp.jwk.json"}) { JWK jwk = JWK.parse(Files.readString(Path.of(file))); System.out.println(file + ": " + jwk.computeThumbprint()); } // From a PEM public key (this parser needs Bouncy Castle's bcpkix on the class path) for (String file : new String[] {"ec.pub.pem", "rsa.pub.pem"}) { JWK jwk = JWK.parseFromPEMEncodedObjects(Files.readString(Path.of(file))); System.out.println(file + ": " + jwk.computeThumbprint()); } System.out.println(JWK.parse(Files.readString(Path.of("ec.jwk.json"))).computeThumbprintURI()); // RFC 9278 }} How it works
JWK.parse(json)returns anECKey,RSAKeyorOctetKeyPair;kid,useandalgare kept but play no part in the thumbprint.computeThumbprint()uses SHA-256 and returns aBase64URLwhosetoString()is the thumbprint;computeThumbprint("SHA-384")selects another hash.JWK.parseFromPEMEncodedObjects(pem)reads PEM public keys, private keys and certificates.computeThumbprintURI()gives the RFC 9278urn:ietf:params:oauth:jwk-thumbprint:sha-256:…form.
Gotchas
parseFromPEMEncodedObjectsneeds Bouncy Castle (bcpkix-jdk18on, withbcprovandbcutil) on the class path; without it the call fails withNoClassDefFoundError: org/bouncycastle/openssl/jcajce/JcaPEMKeyConverter. Nimbus declares these dependencies as optional.- That PEM parser reads RSA and EC keys only: an Ed25519 PEM fails with
JOSEException: Unsupported algorithm of PEM-encoded key: EdDSA. Read Ed25519 keys with the JDK (KeyFactory.getInstance("Ed25519")) and build anOctetKeyPairfrom the 32 raw bytes. - A common
kidchoice is the thumbprint itself:new ECKey.Builder(…).keyIDFromThumbprint().build()sets it in one step. computeThumbprint()on a private JWK gives the same value as on its public part — useful, but publishjwk.toPublicJWK(), never the private JWK.