如何生成 RSAPublicKey 以馈送到 JJWT RSA 令牌验证中



我正在验证来自Azure的JWT令牌并使用JJWT。我从与我的 tid 相关的键文档中检索模数和指数,它们是字段分别为 n 和 e。验证失败,并显示错误:JWT 签名与本地计算的签名不匹配。不能断言 JWT 有效性,也不应信任。

这是代码。有人看到我犯的错误吗?代码运行良好,直到引发签名不匹配错误的验证。

private Claims extractClaimsForRsaSignedJwts(String token, String mod, String exp) {
    Claims claims = null;
    byte[] modBytes = Base64.decodeBase64(mod.getBytes());
    byte[] expBytes = Base64.decodeBase64(exp.getBytes());
    BigInteger modulus = new BigInteger(modBytes);
    BigInteger exponent = new BigInteger(expBytes);
    RSAPublicKeySpec pubKeySpecification = new RSAPublicKeySpec(modulus, exponent);
    KeyFactory keyFac = null;
    try {
        keyFac = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    RSAPublicKey rsaPub = null;
    try {
        rsaPub = (RSAPublicKey) keyFac.generatePublic(pubKeySpecification);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JwtParser jwtParser = Jwts.parser().setSigningKey(rsaPub);
    try {
        claims = jwtParser.parseClaimsJws(token).getBody();
    } catch (Exception e) {
        // JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
        System.out.println("The RSA JWT key validation failed: " + e.getMessage());
    }
    return claims;
}

谢谢!

一月

我发现了问题! BigInteger 应该用符号 1 构造为正数!现在,代码的工作方式类似于 AzureAD JWT 签名验证的超级按钮。

    BigInteger modulus  = new BigInteger(1, modBytes);
    BigInteger exponent = new BigInteger(1, expBytes);

这是最终代码:带更正的代码的屏幕截图

最新更新