我必须使用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);但是我的公钥是字符串形式的,而我没有私钥。请告诉我如何验证签名。
发布于 2019-04-05 13:03:52
当使用非对称密钥加密时,我们需要私钥来创建签名,而公钥来验证。来回答你的问题
1.不存在私有
这很好,你不需要私钥来验证签名。关于您正在使用的lib,它的变量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;
}
}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;
}发布于 2018-10-22 01:20:10
这似乎是https://github.com/auth0/java-jwt的一个缺陷/限制,因为您似乎需要公钥和私钥来验证签名。在使用RSA256算法验证联合小波变换时,不需要拥有私钥。
这个用于处理JWT:https://github.com/jwtk/jjwt#reading-a-jws的替代java库没有同样的限制,因此我建议使用它。
Jwts.parser()
.setSigningKey(publicKey) // <---- publicKey, not privateKey
.parseClaimsJws(jwsString);发布于 2018-05-06 20:49:35
如果您是令牌生成器,则必须使用私钥来生成令牌。
除非您拥有私钥,否则无法验证令牌。
如果您在客户端使用令牌,则不需要对其进行验证。
如果您只想在编写功能之前验证令牌,可以转到:
如果你经历了这个,它会很有帮助:
如果有人在服务器上请求资源,您可以执行以下操作:
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);
//OK, we can trust this JWT
} catch (SignatureException e) {
//don't trust the JWT!
}我希望这能帮到你。
https://stackoverflow.com/questions/49693409
复制相似问题