Skip to content

Instantly share code, notes, and snippets.

@emoran
Last active March 19, 2024 02:12
Show Gist options
  • Save emoran/6fb2e36f148f6900abe2a51e3d146228 to your computer and use it in GitHub Desktop.
Save emoran/6fb2e36f148f6900abe2a51e3d146228 to your computer and use it in GitHub Desktop.
Generares a Signed JWT token based on RSA private key pulled from local file
package com.emoran;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class JWTGenerator {
private String privateKey;
public static void main(String[] args) throws Exception {
JWTGenerator generator = new JWTGenerator();
PrivateKey privateKey = generator.getPrivateKey();
Instant now = Instant.now();
long timeSecs = (System.currentTimeMillis() / 1000);
//General Claim
JsonObject jsonClaim = new JsonObject();
jsonClaim.addProperty("iss", "UUID");
jsonClaim.addProperty("aud", "URL_HERE");
jsonClaim.addProperty("scope", "admin_read admin_write");
jsonClaim.addProperty("exp", timeSecs + + 60); //Expires every 60 secs
jsonClaim.addProperty("iat", timeSecs);
Gson gson = new Gson();
String serviceAccountAuthPayload = gson.toJson(jsonClaim);
System.out.println("JSON Claim"+serviceAccountAuthPayload);
String header = java.util.Base64.getUrlEncoder().encodeToString("{\"alg\":\"RS256\"}".getBytes());
//System.out.println("header: "+header);
String base64Claim = java.util.Base64.getUrlEncoder().encodeToString(serviceAccountAuthPayload.getBytes());
System.out.println("base64Claim: "+base64Claim);
String token = generator.signJWT(header,base64Claim,privateKey);
System.out.println("Token is: "+token);
}
/**
Signs the payload witht the RSA private key
*/
public String signJWT (String header, String payload, PrivateKey privateKey) throws Exception{
String token = header + "." + payload;
Signature sig = Signature.getInstance("SHA256WithRSA");
sig.initSign(privateKey);
sig.update(token.getBytes());
byte[] signature = sig.sign();
System.out.println("SIGN: " +Base64.getUrlEncoder().encodeToString(signature));
return token + "." + Base64.getUrlEncoder().encodeToString(signature);
}
/**
Pulls the private Key from resources folder. if "IOException : algid parse error, not a sequence" happens then you need to migrate your pem
file using this command openssl pkcs8 -topk8 -inform PEM -outform PEM -in original.pem -out migrated.pem -nocrypt
*/
public PrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, URISyntaxException {
String privateKeyContent = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("privateKey.pem").toURI())));
privateKeyContent = privateKeyContent.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment