使用 JWT ( java-jwt ) 验证签名

use*_*509 3 java jwt

我必须使用 java-jwt 库验证签名,我有令牌和公钥,公钥从 ssh-rsa AA 开始.........而且我必须使用 RSA256 算法,当我检查了github我发现以下

Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
JWTVerifier verifier = JWT.require(algorithm)
    .withIssuer("auth0")
    .build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
Run Code Online (Sandbox Code Playgroud)

但是我的公钥是字符串形式的,而我没有私钥.. 请建议我如何验证签名。

小智 9

使用非对称密钥加密时,我们需要私钥来创建签名和公钥来验证。来回答你的问题

1. 私人不存在

没关系,您不需要私钥来验证签名。关于您正在使用的库,其变量 args 。这意味着您可以根据签名/验证通过一个。下面是只使用公钥的 java 方法。

    public boolean verifyToken(String token,RSAPublicKey publicKey){
    try {
        Algorithm algorithm = Algorithm.RSA256(publicKey, null);
        JWTVerifier verifier = JWT.require(algorithm)
                //more validations if needed
                .build();
        verifier.verify(token);
        return true;
    } catch (Exception e){
        System.out.println("Exception in verifying "+e.toString());
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

2.公钥是字符串格式,不是java PublicKey格式。

您需要一种机制来您的公钥字符串文件转换为 Java PublicKey 格式。下面是我可以建议的一种方法。

    public static RSAPublicKey getPublicKeyFromString(String key) throws 
    IOException, GeneralSecurityException {

    String publicKeyPEM = key;

    /**replace headers and footers of cert, if RSA PUBLIC KEY in your case, change accordingly*/
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");

    byte[] encoded = Base64.decodeBase64(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));

    return pubKey;
    }
Run Code Online (Sandbox Code Playgroud)


小智 -2

如果您是令牌生成器,您必须拥有用于生成令牌的私钥。

除非您拥有私钥,否则您无法验证令牌。

如果您在客户端使用令牌,则无需验证它。

如果您只想在编写功能之前验证令牌,您可以转到:

https://jwt.io/

如果你经历过这个将会很有帮助:

https://github.com/jwtk/jjwt

如果有人在服务器上请求资源,您可以执行以下操作:

try {

    Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);

    //OK, we can trust this JWT

} catch (SignatureException e) {

    //don't trust the JWT!
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助...

  • 基于公钥/私钥的签名算法的全部意义不是任何人都应该能够在没有私钥的情况下验证签名吗?!不明白为什么没有私钥就无法验证令牌。这可以在node.js lib https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback中完成,并且似乎是特定java lib实现https://github的缺陷/限制。 OP中引用的com/auth0/java-jwt。 (2认同)