public static void testSigning() throws Exception { String h = "{\"typ\":\"JWT\",\"kid\":\"9k0HPG3moXENne\",\"alg\":\"RS256\"}"; String p = "{\"iss\":\"https://ashigaru.ncsa.uiuc.edu:9443\",\"sub\":\"jgaynor\",\"exp\":1484764744,\"aud\":\"myproxy:oa4mp,2012:/client_id/14649e2f468450dac0c1834811dbd4c7\",\"iat\":1484763844,\"nonce\":\"0ZIi-EuxeC_X8AgB3VifOoqKiXWsz_NlXSzIu7h8rzU\",\"auth_time\":\"1484763843\"}\n"; JSONObject header = JSONObject.fromObject(h); System.out.println("header=" + header); JSONObject payload = JSONObject.fromObject(p); System.out.println("payload=" + payload); System.out.println("base 64=" + concat(header, payload)); //String keyID = "9k0HPG3moXENne"; String keyID = "244B235F6B28E34108D101EAC7362C4E"; JSONWebKeys keys = JSONWebKeyUtil.fromJSON(new File("/home/ncsa/dev/csd/config/polo-keys.jwk")); String idTokken = createJWT(payload, keys.get(keyID)); System.out.println(idTokken); JSONObject claims = verifyAndReadJWT(idTokken, keys); System.out.println("claims = " + claims); JSONWebKey webKey = keys.get(keyID); System.out.println(KeyUtil.toX509PEM(webKey.publicKey)); }
public static JSONObject verifyAndReadJWT(String jwt, URI wellKnown) { if(wellKnown == null){ throw new GeneralException("Error: Missing well known uri. Cannot resolve the keys"); } if(jwt == null || jwt.isEmpty()){ throw new GeneralException("Error: Missing or empty token."); } return verifyAndReadJWT(jwt, JWTUtil.getJsonWebKeys(wellKnown.toString())); }
public static void signAndVerify(JSONWebKeys keys, String keyID) throws Exception { String h = "{" + " \"typ\": \"JWT\"," + " \"kid\": \"9k0HPG3moXENne\"," + " \"alg\": \"RS256\"" + "}"; String p = "{\n" + " \"iss\": \"https://ashigaru.ncsa.uiuc.edu:9443\"," + " \"sub\": \"jgaynor\"," + " \"exp\": 1484764744," + " \"aud\": \"myproxy:oa4mp,2012:/client_id/14649e2f468450dac0c1834811dbd4c7\"," + " \"iat\": 1484763844," + " \"nonce\": \"0ZIi-EuxeC_X8AgB3VifOoqKiXWsz_NlXSzIu7h8rzU\"," + " \"auth_time\": \"1484763843\"" + "}"; JSONObject header = JSONObject.fromObject(h); JSONObject payload = JSONObject.fromObject(p); JSONWebKey key = keys.get(keyID); String signature = sign(header, payload, key); System.out.println(concat(header, payload) + "." + signature); System.out.println(KeyUtil.toX509PEM(key.publicKey)); System.out.println("verified?" + verify(header, payload, signature, key)); }
/** Strictly for testing. * This will take two arguments, a file name containing the keys, the word decode|encode and a string. * If the word decode is used, then the string is decoded against the * @param args */ public static void main(String[] args) { try { // firstTest(); // firstTestB(); // otherTest(); testSigning(); JSONWebKeys keys = getJsonWebKeys("https://test.cilogon.org/oauth2/.well-known"); System.out.println("Detected " + keys.size() + " keys on test.cilogon.org"); // testSigningDirectly(); //testJWT_IO(); // printKeys(); // generateAndSign(); } catch (Throwable t) { t.printStackTrace(); } }
public static void firstTestB() throws Exception { String keyID = "9k0HPG3moXENne"; JSONWebKeys keys = JSONWebKeyUtil.fromJSON(new File("/home/ncsa/dev/csd/config/keys.jwk")); JSONObject payload = new JSONObject(); payload.put("name", "jeff"); payload.put("id", "sukjfhusdfsdjkfh"); payload.put("other_claim", "skjdf93489ghiovs 98sd89wehi ws"); payload.put("another_claim", "l;kfg8934789dfio9v 92w89 98wer"); JSONWebKey webKey = keys.get(keyID); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(webKey.privateKey.getEncoded()); RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec); System.out.println(KeyUtil.toX509PEM(webKey.publicKey)); System.out.println(KeyUtil.toPKCS1PEM(privateKey)); System.out.println(KeyUtil.toPKCS8PEM(privateKey)); String tokken = createJWT(payload, keys.get(keyID)); System.out.println("JWT=" + tokken); System.out.println("claims=" + verifyAndReadJWT(tokken, keys)); System.out.println("-----"); // note that if the this last call // works it is because the verification works too. }
throw new GeneralException("Error: missing or empty token"); String[] x = decat(jwt); JSONObject h = JSONObject.fromObject(new String(Base64.decodeBase64(x[HEADER_INDEX]))); JSONObject p = JSONObject.fromObject(new String(Base64.decodeBase64(x[PAYLOAD_INDEX]))); isOK = verify(h, p, x[SIGNATURE_INDEX], webKeys.get(h.getString(KEY_ID))); } catch (Throwable t) { throw new IllegalStateException("Error: could not verify signature", t);
public static void otherTest() throws Exception { JSONWebKeys keys = JSONWebKeyUtil.fromJSON(new File("/home/ncsa/dev/csd/config/keys.jwk")); JSONObject claims = verifyAndReadJWT(ID_TOKKEN, keys); System.out.println("claims=" + claims); }
public static JSONWebKeys getJsonWebKeys(URI wellKnown) { if(wellKnown == null){ throw new GeneralException("Error: Missing well known uri. Cannot resolve the keys"); } return getJsonWebKeys(wellKnown.toString()); }
public static boolean verify(JSONObject header, JSONObject payload, String sig, JSONWebKey webKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException { Object alg = header.get(ALGORITHM); if (alg == null || !(alg instanceof String)) { throw new IllegalStateException("Unknown algorithm"); } String algorithm = (String) alg; DebugUtil.dbg(JWTUtil.class, "Verifying ID token with algorithm =" + algorithm); Signature signature = null; if (algorithm.equals(NONE_JWT)) { return true; } signature = Signature.getInstance(getJavaSignatureName(algorithm)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(webKey.publicKey.getEncoded()); RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); signature.initVerify(pubKey); signature.update(concat(header, payload).getBytes()); boolean rc = signature.verify(Base64.decodeBase64(sig)); DebugUtil.dbg(JWTUtil.class, "Verification ok?" + rc); return rc; }
/** * Creates an unsigned token. * * @param payload * @return */ public static String createJWT(JSONObject payload) { JSONObject header = new JSONObject(); header.put(TYPE, "JWT"); header.put(ALGORITHM, NONE_JWT); return concat(header, payload) + "."; // as per spec. }
public static void testJWT_IO() throws Exception { String header = "{" + " \"typ\": \"JWT\"," + " \"kid\": \"9k0HPG3moXENne\"," + " \"alg\": \"RS256\"" + "}"; String payload = "{\n" + " \"iss\": \"https://ashigaru.ncsa.uiuc.edu:9443\"," + " \"sub\": \"jgaynor\"," + " \"exp\": 1484764744," + " \"aud\": \"myproxy:oa4mp,2012:/client_id/14649e2f468450dac0c1834811dbd4c7\"," + " \"iat\": 1484763844," + " \"nonce\": \"0ZIi-EuxeC_X8AgB3VifOoqKiXWsz_NlXSzIu7h8rzU\"," + " \"auth_time\": \"1484763843\"" + "}"; String keyID = "9k0HPG3moXENne"; JSONWebKeys keys = JSONWebKeyUtil.fromJSON(new File("/home/ncsa/dev/csd/config/keys.jwk")); JSONWebKey jsonWebKey = keys.get(keyID); JSONObject h = JSONObject.fromObject(header); JSONObject p = JSONObject.fromObject(payload); String signature = sign(h, p, jsonWebKey); System.out.println(signature); }
public static void generateAndSign() throws Exception { String keyID = "aQEiCy2fJcVgkOft"; KeyPair keyPair = KeyUtil.generateKeyPair(); JSONWebKeys keys = new JSONWebKeys(keyID); JSONWebKey key = new JSONWebKey(); key.privateKey = keyPair.getPrivate(); key.publicKey = keyPair.getPublic(); key.algorithm = RS256_JWT; key.id = keyID; key.use = "sig"; key.type = "RSA"; keys.put(key); System.out.println("Generating keys and signing."); signAndVerify(keys, keyID); JSONObject jsonKeys = JSONWebKeyUtil.toJSON(keys); JSONWebKeys keys2 = JSONWebKeyUtil.fromJSON(jsonKeys.toString(2)); JSONWebKey webKey = keys2.get(keyID); System.out.println("Serializing, deserializing then signing."); signAndVerify(keys2, keyID); }
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(webkey.privateKey.getEncoded()); RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec); Signature signature = Signature.getInstance(getJavaSignatureName(webkey.algorithm)); signature.initSign(privateKey); byte[] content = x.getBytes();
public static void firstTest() throws Exception { JSONObject header = new JSONObject(); header.put(TYPE, "JWT"); header.put(ALGORITHM, "RS256"); KeyPair keyPair = KeyUtil.generateKeyPair(); JSONWebKey webKey = new JSONWebKey(); webKey.algorithm = "RS256"; webKey.privateKey = keyPair.getPrivate(); webKey.publicKey = keyPair.getPublic(); webKey.id = "qwert"; webKey.type = "sig"; JSONObject payload = new JSONObject(); payload.put("name", "jeff"); payload.put("id", "sukjfhusdfsdjkfh"); payload.put("other_claim", "skjdf93489ghiovs 98sd89wehi ws"); payload.put("another_claim", "l;kfg8934789dfio9v 92w89 98wer"); String tokken = createJWT(payload, webKey); System.out.println("JWT=" + tokken); JSONWebKeys keys = new JSONWebKeys(null); keys.put(webKey.id, webKey); System.out.println("claims=" + verifyAndReadJWT(tokken, keys)); System.out.println("-----"); // note that if the this last call // works it is because the verification works too. }
public void validate_token(InputLine inputLine) throws Exception { if (showHelp(inputLine)) { printValidateTokenHelp(); return; } String token = null; if (1 == inputLine.size()) { say("Sorry, no argument"); return; } if (inputLine.hasArg("-file")) { token = getArgValue(inputLine, "-file"); } else { token = inputLine.getArg(1); } String[] x = decat(token); JSONObject h = JSONObject.fromObject(new String(Base64.decodeBase64(x[0]))); JSONObject p = JSONObject.fromObject(new String(Base64.decodeBase64(x[1]))); say("header=" + h); say("payload=" + p); if (JWTUtil.verify(h, p, x[2], keys.get(defaultKeyID))) { say("token valid!"); } else { say("could not validate token"); } } }
throw new GeneralException("Error: Missing id token."); claims = JWTUtil.verifyAndReadJWT(jsonObject.getString(ID_TOKEN), keys); if(claims.isNullObject()){
/** * Create a basic {@link ServiceClient} to get the keys from the well known page. If you require a special * setup (e.g. your own SSL certs), you will need to create your own ServiceClient and supply that in the * related call getJSONWebKeys(ServiceClient, String wellKnown). * @param wellKnown * @return */ public static JSONWebKeys getJsonWebKeys(String wellKnown) { if(wellKnown == null || wellKnown.isEmpty()){ throw new GeneralException("Error: missing well known URI. Cannot get keys"); } ServiceClient serviceClient = new ServiceClient(URI.create(wellKnown)); return getJsonWebKeys(serviceClient, wellKnown); }
public static String createJWT(JSONObject payload, JSONWebKey jsonWebKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, InvalidKeyException, IOException { JSONObject header = new JSONObject(); header.put(TYPE, "JWT"); header.put(KEY_ID, jsonWebKey.id); String signature = null; header.put(ALGORITHM, jsonWebKey.algorithm); if (jsonWebKey.algorithm.equals(NONE_JWT)) { signature = ""; // as per spec } else { DebugUtil.dbg(JWTUtil.class, "Signing ID token with algorithm=" + jsonWebKey.algorithm); signature = sign(header, payload, jsonWebKey); } String x = concat(header, payload); return x + "." + signature; }