jwt RS256 通过公钥验证token

private static String public_Key = "-----BEGIN PUBLIC KEY-----"
			+ "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv"
			+ "vkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc"
			+ "aT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy"
			+ "tvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0"
			+ "e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb"
			+ "V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9" + "MwIDAQAB"
			+ "-----END PUBLIC KEY-----";


/**
	 * 获取PublicKey对象
	 * 
	 * @param publicKeyBase64
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	private static PublicKey getPublicKey(String publicKeyBase64)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		String pem = publicKeyBase64.replaceAll("\\-*BEGIN PUBLIC KEY\\-*", "").replaceAll("\\-*END PUBLIC KEY\\-*", "")
				.trim();
		java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pem));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");

		PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
		System.out.println(publicKey);
		return publicKey;
	}



/**
	 * 验证jwt
	 * 
	 * @param token
	 * @return
	 * @throws Exception
	 */
	private static void verifyToken(String token) throws Exception {

		try {
			PublicKey publicKey = getPublicKey(public_Key);

			Jwt parseClaimsJwt = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);

			System.out.println(parseClaimsJwt);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


/**
*
*测试
*/
public static void main(String[] args) {

		String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJhdWQiOiIxMDEiLCJpc3MiOiJUZW5jZW50Q2xvdWQiLCJzYWlkIjoiMTAxIn0.PLHz0tOG6DWtjmWTZY5j3KG7MPnZX9qMQtbDWncKZSwTuxKxBosv24lGSkBUVCbtoDBADPRUwvWVYvglXyKz8A3j37mLNC_opK0koWeA3c0afa7EqXTQR4X5-k8IFZWYj2SnwjVw2M9CEorLixv0WE6R6qhaK73UEhhvSvYeIXwAoyU3oMDF9OpjXBebDNkVC_p5Js7ImJzvnZpFR3bf--bh3vkCriM126yUiS7mw9iEfZxW2EP-Eln2gEQvJjJFkhzwIqPbZv2LWB_F3PcgA1gk3eo_fllM29g5H1Hth1Ijf8PXYsCqAiWqs0Ns-JW4FJICqwqKKc3h8tktaW-r2w";
		try {
			verifyToken(token);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

你可能感兴趣的:(java)