gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:02:08 25 4
gpt4 key购买 nike

我需要一些帮助来使用 ECDSA 公钥验证 jwt 签名。我正在从带有充气城堡的 .pem 文件中读取 key ,并使用 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 验证椭圆曲线签名。错误解码签名字节。

最佳答案

这在不提及任何算法的情况下也能正常工作。

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')

关于java - 使用 ECDSA 公钥验证 JWT 签名 - 解码签名字节时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55710561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com