token字符串可直接用Base64 decode解密

来源:11-9 JWT是什么?【是什么、组成、上手】

banrino

2021-09-14

大目老师,有个问题,我用密钥生成token之后,用hutool的Base64的decode可以直接解密token字符打印里面的信息,为什么会这样呢,都没有使用密钥呢
代码图片描述
图片描述

package com.colt.usercenter.util;

import cn.hutool.core.codec.Base64;
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@SuppressWarnings(“WeakerAccess”)
@Component
public class JwtOperator {
/**
* 秘钥
* - 默认aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt
*/
@Value("KaTeX parse error: Expected 'EOF', got '有' at position 115: … /** * 有̲效期,单位秒 * -…{expire-time-in-second:1209600}")
private Long expirationTimeInSecond;

/**
 * 从token中获取claim
 *
 * @param token token
 * @return claim
 */
public Claims getClaimsFromToken(String token) {
    try {
        return Jwts.parser()
            .setSigningKey(this.secret.getBytes())
            .parseClaimsJws(token)
            .getBody();
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
        log.error("token解析错误", e);
        throw new IllegalArgumentException("Token invalided.");
    }
}

/**
 * 获取token的过期时间
 *
 * @param token token
 * @return 过期时间
 */
public Date getExpirationDateFromToken(String token) {
    return getClaimsFromToken(token)
        .getExpiration();
}

/**
 * 判断token是否过期
 *
 * @param token token
 * @return 已过期返回true,未过期返回false
 */
private Boolean isTokenExpired(String token) {
    Date expiration = getExpirationDateFromToken(token);
    return expiration.before(new Date());
}

/**
 * 计算token的过期时间
 *
 * @return 过期时间
 */
public Date getExpirationTime() {
    return new Date(System.currentTimeMillis() + this.expirationTimeInSecond * 1000);
}

/**
 * 为指定用户生成token
 *
 * @param claims 用户信息
 * @return token
 */

public String generateToken(Map<String, Object> claims) {
    Date createdTime = new Date();
    Date expirationTime = this.getExpirationTime();


    byte[] keyBytes = secret.getBytes();
    SecretKey key = Keys.hmacShaKeyFor(keyBytes);

    return Jwts.builder()
        .setClaims(claims)
        .setIssuedAt(createdTime)
        .setExpiration(expirationTime)
        // 你也可以改用你喜欢的算法
        // 支持的算法详见:https://github.com/jwtk/jjwt#features
        .signWith(key, SignatureAlgorithm.HS256)
        .compact();
}

/**
 * 判断token是否非法
 *
 * @param token token
 * @return 未过期返回true,否则返回false
 */
public Boolean validateToken(String token) {
    return !isTokenExpired(token);
}

public static void main(String[] args) {
    // 1. 初始化
   JwtOperator jwtOperator = new JwtOperator();
    jwtOperator.expirationTimeInSecond = 1209600L;
    jwtOperator.secret = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt";

    // 2.设置用户信息
     HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
    objectObjectHashMap.put("id", "1");
    objectObjectHashMap.put("name", "撒旦");

    // 测试1: 生成token
    String token = jwtOperator.generateToken(objectObjectHashMap);
    // 会生成类似该字符串的内容: eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ
    System.out.println(token);
    byte[] decode = Base64.decode(token);
    String s = new String(decode);
    System.err.println("decode String:"+s);
}

}

就是课程代码里的jwt工具类

写回答

2回答

大目

2021-09-15

你的代码有问题。

//img.mukewang.com/szimg/6141c04c09a0965e16040446.jpg

token本身并不是base64字符串。

所以,

    byte[] decode = Base64.decode(token);

这一行会有问题啊。

你只能Base64.decode(token的第一段或者token的第二段,用.分隔),例如:

byte[] decode = Base64.decode(token.split("\\.")[1]);


1
0

大目

2021-09-14

可以帮忙贴下完整的代码不?需要文字版的,我来看看哦

0
1
banrino
贴了代码了哈
2021-09-15
共1条回复

Spring Cloud Alibaba微服务从入门到进阶

面向未来微服务:熟练掌握Spring Cloud Alibaba

3085 学习 · 1324 问题

查看课程