Skip to content

Instantly share code, notes, and snippets.

@sohalloran
Created May 10, 2019 13:56
Show Gist options
  • Save sohalloran/79b0b0e92192e4e3d6e68dcadc172325 to your computer and use it in GitHub Desktop.
Save sohalloran/79b0b0e92192e4e3d6e68dcadc172325 to your computer and use it in GitHub Desktop.
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.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;
import java.util.HashMap;
import java.util.Map;
import java.io.FileInputStream;
import com.google.gson.*;
public class genJWK {
public static void main(String[] args) {
System.out.println("JWKS Generator");
try{
Gson gson = new Gson();
System.out.println( generateJWK(args[0],args[0]));
System.out.println();
System.out.println( gson.toJson(generateJWK(args[0],args[0])));
} catch(Exception e){
e.printStackTrace();
}
}
private static Map<String, Object> generateJWK(String env, String location){
Map<String, Object> values = new HashMap<>();
try{
FileInputStream fin = new FileInputStream(location);
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
System.out.println("Subject DN : " + certificate.getSubjectDN().getName());
System.out.println("Issuer : " + certificate.getIssuerDN().getName());
System.out.println("Not After: " + certificate.getNotAfter());
System.out.println("Not Before: " + certificate.getNotBefore());
System.out.println("version: " + certificate.getVersion());
System.out.println("serial number : " + certificate.getSerialNumber());
PublicKey pk = certificate.getPublicKey();
//System.out.println("PublicKey : \n" + pk);
RSAPublicKey rsa = (RSAPublicKey) pk;
values.put("kty", rsa.getAlgorithm()); // getAlgorithm() returns kty not algorithm
values.put("kid", env);
values.put("n", Base64.getUrlEncoder().encodeToString(rsa.getModulus().toByteArray()));
values.put("e", Base64.getUrlEncoder().encodeToString(rsa.getPublicExponent().toByteArray()));
values.put("alg", "RS256");
values.put("use", "sig");
} catch(Exception e){
e.printStackTrace();
}
return values;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment