JWT signing with public and private key

1k Views Asked by At

I have written this portion of code to create a JWT.

public String createJWT() throws JoseException {

        RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);

        // Give the JWK a Key ID (kid), which is just the polite thing to do
        rsaJsonWebKey.setKeyId(keyId);

        // Create the Claims, which will be the content of the JWT
        JwtClaims claims = new JwtClaims();
        claims.setIssuer(issuer);
        claims.setExpirationTimeMinutesInTheFuture(60);
        claims.setJwtId(keyId);
        claims.setIssuedAtToNow();
        claims.setNotBeforeMinutesInThePast(2);
        claims.setSubject(subject);

        // We create a JsonWebSignature object.
        JsonWebSignature jws = new JsonWebSignature();

        // The payload of the JWS is JSON content of the JWT Claims
        jws.setPayload(claims.toJson());

        //The header of the JWS
        jws.setHeader("typ", "JWT");

        // The JWT is signed using the private key
        jws.setKey(rsaJsonWebKey.getPrivateKey());

        jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());

        // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

        // Sign the JWS and produce the compact serialization or the complete JWT/JWS
        // representation, which is a string consisting of three dot ('.') separated
        // base64url-encoded parts in the form Header.Payload.Signature
        String jwt = jws.getCompactSerialization();

        System.out.println("JWT: " + jwt);

        return jwt;
    }

But I don't understand which private key is it retrieving? How can I customize this code to send my own public and private key stored in local JKS?

1

There are 1 best solutions below

0
bsanchezb On

Try to use the following to load your own keystore:

    try (InputStream is = new FileInputStream(new File("path to keystore"))) {
        KeyStore keyStore = KeyStore.getInstance(ksType);
        keyStore.load(is, password);
        final Enumeration<String> aliases = keyStore.aliases();
        final String alias = aliases.nextElement(); // assuming only one entry
        final Entry entry = keyStore.getEntry(alias, password);
        if (entry instanceof PrivateKeyEntry) {
                PrivateKeyEntry pke = (PrivateKeyEntry) entry;
                PrivateKey privateKey = pke .getPrivateKey();

                // and here you may return the PrivateKey

        }

    } catch (Exception e) {
        ...
    }

Disclaimer : I did not test the code, but it should work.