使用ECDSA公钥验证JWT签名-解码签名字节时出错

时间:2019-04-16 14:28:12

标签: java jwt bouncycastle ecdsa

我需要一些帮助来使用ECDSA公钥验证jwt签名。我正在从具有弹力城堡的.pem文件中读取密钥,并使用jjwt进行验证。验证签名时出现错误。

Security.addProvider(new BouncyCastleProvider());
String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJtc2kiOiI5NzE1NTA5ODc2NTUiLCJmZWEiOiJzaWdudXAtZGF0YSIsImlzcyI6IkNEUCIsImV4cCI6MTU1NDU2NjMzNiwiaWF0IjoxNTU0MzkzNTM2LCJzaWQiOiIwNDI0MDMwMDg5NzI4MTg3QG5haS5lcGMubW5jMTMwLm1jYzMxMC4zZ3BwbmV0d29yay5vcmcifQ.RwxoGmFd1_dQPeGN-0gnWIW79xXvGHoyJKBbCKajgO75UooceS6tskxwqViEuP1gZD66UE8Bd2L0FaeI2aS_IA";
PemReader pemReader = new PemReader(new FileReader("/publickey.pem"));
X509EncodedKeySpec spec = new X509EncodedKeySpec(pemReader.readPemObject().getContent());
KeyFactory kf = KeyFactory.getInstance("ECDSA","BC");
PublicKey publicKey = kf.generatePublic(spec);
Jws<Claims> claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jwt);

我收到以下签名异常:无法使用已配置的ECPublicKey验证椭圆曲线签名。解码签名字节时出错。

2 个答案:

答案 0 :(得分:4)

这同样适用,无需提及任何算法。

public boolean isTokenValid(String token) {
    try {
        String certificate = "GET_YOUR_PUBLIC_CERTIFICATE_HERE"; //Either from REST call or reading from a cert file.
        getPublicKeyAndParseToken(token, certificate);
        return true;
    } catch (IOException e) {
        log.error("", e);
    } catch (Exception e) {
        log.error("", e);
        log.error("JWT Not-Verified");
    }
    return false;
}

private void getPublicKeyAndParseToken(String token, String certificate) throws IOException, CertificateException {
    log.debug("Certificate:: " + certificate); //Only for debugging purpose
    InputStream is = new ByteArrayInputStream(certificate.getBytes(StandardCharsets.UTF_8));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(is);
    PublicKey publicKey = cert.getPublicKey();

    Jws parsedClaimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    log.debug("Header:: " + parsedClaimsJws.getHeader()); //Only for debugging purpose
    log.debug("Body:: " + parsedClaimsJws.getBody()); //Only for debugging purpose
}

不要忘记使用jjwt库的版本“ 0.9.x”。我在build.gradle中低于依赖项:

compile('io.jsonwebtoken:jjwt:0.9.1')

答案 1 :(得分:1)

发现问题,我正在使用旧的jjwt lib(0.6)。使用相同的代码更改为0.9,并且可以按预期工作。

谢谢