java 使用jks公钥字符串 验签jwt Token
jks中存储了一个密钥对,包括私钥和公钥.
在spring security 和 oauth2 的整合中,使用文件名为 oauth2.jks 的文件作为密钥对.
在登录时使用秘钥对的私钥加密jwt Token,那么在验证jwt时,就需要提供秘钥对的公钥,同时项目中已经存在该秘钥对的公钥,是以文件的方式存放.那么我们如何用这个公钥字符串文件来验证jwt?
private boolean verifyVisitsNumber(String value) {
ClassPathResource resource = new ClassPathResource("public.txt");
String publicKey = null;
try {
publicKey = IOUtils.toString(resource.getInputStream(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
PublicKey publicKey1=null;
try {
publicKey1 = pemToPublicKey(publicKey);
} catch (Exception e) {
e.printStackTrace();
}
Claims body = Jwts.parser()
.setSigningKey(publicKey1)
.parseClaimsJws(value)
.getBody();
Map<String,String> userInfo = (Map<String,String>)body.get("userInfo");
String uid = userInfo.get("uid");
if(StringUtils.equals(uid,"9")){
//超级管理员不计次数
return true;
}
//明天凌晨
DateTime dateTime = DateUtil.beginOfDay(DateUtil.tomorrow());
Date date = new Date();
//距离多少分钟到凌晨->到凌晨自动重置访问次数
long betweenMinutes = DateUtil.between(date, dateTime, DateUnit.MINUTE);
String o = (String)redisTemplate.opsForValue().get(visitsNumberPrefix + ":" + uid);
if(StringUtils.isBlank(o)){
redisTemplate.opsForValue().set(visitsNumberPrefix + ":" + uid,"1",betweenMinutes, TimeUnit.MINUTES);
o="1";
}else{
redisTemplate.opsForValue().set(visitsNumberPrefix + ":" + uid,String.valueOf(Integer.valueOf(o)+1),betweenMinutes, TimeUnit.MINUTES);
o=String.valueOf(Integer.valueOf(o)+1);
}
if(Integer.valueOf(o) > visitsNumber){
//该用户当前请求次数耗尽
return false;
}
return true;
}
/**
* 将PEM格式的RSA公钥字符串转换为PublicKey对象
*
* @param pubKeyPEM PEM格式的RSA公钥字符串
* @return PublicKey对象
* @throws Exception 如果转换过程中发生错误
*/
public static PublicKey pemToPublicKey(String pubKeyPEM) throws Exception {
String publicKeyPEMHeader = "-----BEGIN PUBLIC KEY-----";
String publicKeyPEMFooter = "-----END PUBLIC KEY-----";
// 移除PEM格式的头部和尾部
String pubKey = pubKeyPEM.replace(publicKeyPEMHeader, "").replace(publicKeyPEMFooter, "").replaceAll("\\s+", "");
// Base64解码
byte[] encoded = Base64.getDecoder().decode(pubKey);
// 创建X509EncodedKeySpec
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
// 获取RSA密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// 生成PublicKey
return keyFactory.generatePublic(keySpec);
}
原文地址:https://blog.csdn.net/qq_31683775/article/details/140568048
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!