Jwt加解密-Java

32 篇文章 0 订阅

工具类

引入依赖包

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.10.3</version>
</dependency>

工具类

package com.gallant.test;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt
 *
 * @author : 会灰翔的灰机
 * @date : 2021/1/28
 */
public class JwtUtil {

  private static final String MY_SALT = "mySalt";

  /**
   * 加密数据
   * @return 密文
   */
  public static String jwtCreate() {
    // 私钥和加密算法
    Algorithm algorithm = Algorithm.HMAC256(MY_SALT);
    Map<String, Object> header = new HashMap<>(2);
    header.put("Type", "Jwt");
    header.put("alg", "HS256");
    return JWT.create()
        // 添加头部
        .withHeader(header)
        .withClaim("dataKey1","my data1")
        .withClaim("dataKey2", "my data2")
        // 设置过期时间
        .withExpiresAt(new Date(System.currentTimeMillis() + 5000))
        // 设置发布时间
        .withIssuedAt(new Date())
        // 设置签名 密钥
        .sign(algorithm);
  }

  public static String getData(String token, String key) {
    try {
      // 私钥和加密算法
      Algorithm algorithm = Algorithm.HMAC256(MY_SALT);
      JWTVerifier verifier = JWT.require(algorithm).build();
      // 验证签名
      DecodedJWT jwt = verifier.verify(token);
      return jwt.getClaim(key).asString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static void main(String[] args) throws InterruptedException {
    String token = JwtUtil.jwtCreate();
    System.out.println("token:" + token);
    System.out.println("dataKey1:" + getData(token, "dataKey1"));
    Thread.sleep(6000);
    System.out.println("dataKey1:" + getData(token, "dataKey1"));
  }
}

执行结果

token:eyJUeXBlIjoiSnd0IiwidHlwIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJkYXRhS2V5MSI6Im15IGRhdGExIiwiZGF0YUtleTIiOiJteSBkYXRhMiIsImV4cCI6MTYxMTgyMzU3NCwiaWF0IjoxNjExODIzNTY5fQ.JVt8F03WOTBXBH-d003dGXBkqEHlOHHvMLICDGxwETM
dataKey1:my data1
com.auth0.jwt.exceptions.TokenExpiredException: The Token has expired on Thu Jan 28 16:46:14 CST 2021.
	at com.auth0.jwt.JWTVerifier.assertDateIsFuture(JWTVerifier.java:379)
	at com.auth0.jwt.JWTVerifier.assertValidDateClaim(JWTVerifier.java:370)
	at com.auth0.jwt.JWTVerifier.verifyClaims(JWTVerifier.java:295)
	at com.auth0.jwt.JWTVerifier.verify(JWTVerifier.java:278)
	at com.auth0.jwt.JWTVerifier.verify(JWTVerifier.java:261)
	at com.gallant.test.JwtUtil.getData(JwtUtil.java:50)
	at com.gallant.test.JwtUtil.main(JwtUtil.java:63)
dataKey1:null

Http对接

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.common.collect.Maps;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class MyHttpClient {
  public static void main(String[] args) throws Throwable {
    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("Authorization", "Bearer " + jwtCreate());
    HttpClient hc = HttpClientBuilder.create()
        .useSystemProperties()
        .setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS)
        .evictExpiredConnections()
        .build();
    HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(hc);
    httpRequestFactory.setConnectionRequestTimeout(3000);
    httpRequestFactory.setConnectTimeout(3000);
    httpRequestFactory.setReadTimeout(3000);
    Map<String, String> body = Maps.newHashMap();
    body.put("appId", "myApp");
    HttpEntity<Object> httpEntity = new HttpEntity<>(body, headers);
    RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
    ResponseEntity<String> responseEntity = restTemplate.exchange( "myUri", HttpMethod.POST,
        httpEntity, String.class);
    System.out.printf("responseEntity %s%n", responseEntity);
  }

  /**
   * 加密数据
   * @return 密文
   */
  public static String jwtCreate() {
    // 私钥和加密算法
    Algorithm algorithm = Algorithm.HMAC256("mySecret");
    Map<String, Object> header = new HashMap<>(2);
    header.put("Type", "JWT");
    header.put("alg", "HS256");
    return JWT.create()
        // 添加头部
        .withHeader(header)
        .withClaim("iss","jack")
        // 设置过期时间
        .withExpiresAt(new Date(System.currentTimeMillis() + 60000))
        // 设置发布时间
        .withIssuedAt(new Date())
        // 设置签名 密钥
        .sign(algorithm);
  }
}

插曲

401 Unauthorized

  1. Authorization header未加前缀"Bearer ",前缀依赖于你的认证机制,例如基于Basic Authentication的前缀是:"Basic "

Exception in thread “main” org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:81)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:776)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:734)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:668)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:577)

三种java开源实现加密端对比

  1. jsonwebtoken/bitbucket不会强制追加Header:typ。auth0会强制追加该参数
  2. jsonwebtoken/auth0不需要手工设置alg,客户端会自动识别。bitbucket需要手工设置
  3. jsonwebtoken/auth0计算payload顺序无相关性,与header顺序存在相关性。bitbucket计算与headers/payload顺序存在相关性。顺序不一致会导致计算结果不一致

jwtCreate基于jsonwebtoken

		<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.5</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
            <version>0.11.5</version>
            <scope>runtime</scope>
        </dependency>

jwtCreate2基于auth0

		<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.3</version>
        </dependency>

jwtCreate3基于bitbucket

		<dependency>
            <groupId>org.bitbucket.b_c</groupId>
            <artifactId>jose4j</artifactId>
            <version>0.7.12</version>
        </dependency>

实现代码

/**
   * 加密数据
   * @return 密文
   */
  public static String jwtCreate(Long timeMillis) {
    return Jwts.builder()
        .setHeaderParam("Type", Header.JWT_TYPE)
        .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
        .setIssuer("myIssuer")
        .setExpiration(new Date(timeMillis + 60000))
        .setIssuedAt(new Date(timeMillis))
        .signWith(Keys.hmacShaKeyFor("0123456789abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.UTF_8)))
        .compact();
  }

  /**
   * 加密数据
   * @return 密文
   */
  public static String jwtCreate2(Long timeMillis) {
    // 私钥和加密算法
    Algorithm algorithm = Algorithm.HMAC256("0123456789abcdefghijklmnopqrstuvwxyz");
    Map<String, Object> header = new HashMap<>(2);
    header.put("Type", "JWT");
    return JWT.create()
        // 添加头部
        .withHeader(header)
        // 设置过期时间
        .withExpiresAt(new Date(timeMillis + 60000))
        // 设置发布时间
        .withIssuedAt(new Date(timeMillis))
        .withIssuer("myIssuer")
        // 设置签名 密钥
        .sign(algorithm);
  }

  public static String jwtCreate3(Long timeMillis) throws JoseException {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("myIssuer");
    claims.setExpirationTime(NumericDate.fromMilliseconds(timeMillis + 60000));
    claims.setIssuedAt(NumericDate.fromMilliseconds(timeMillis));
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(new HmacKey("0123456789abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.UTF_8)));
    jws.setHeader("Type", "JWT");
    jws.setHeader("typ", "JWT");
    jws.setHeader("alg", "HS256");
    return jws.getCompactSerialization();
  }

验证参数顺序相关性

  /**
   * 加密数据
   * @return 密文
   */
  public static String jwtCreate(Long timeMillis) {
    Map<String, String> payload = Maps.newHashMap();
    payload.put("a", "a");
    payload.put("b", "b");
    payload.put("c", "c");
    return Jwts.builder()
        .setHeaderParam("Type", Header.JWT_TYPE)
        .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
        .setClaims(payload)
        .setIssuer("myIssuer")
        .setExpiration(new Date(timeMillis + 60000))
        .setIssuedAt(new Date(timeMillis))
        .signWith(Keys.hmacShaKeyFor("0123456789abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.UTF_8)))
        .compact();
  }

  /**
   * 加密数据
   * @return 密文
   */
  public static String jwtCreate2(Long timeMillis) {
    // 私钥和加密算法
    Algorithm algorithm = Algorithm.HMAC256("0123456789abcdefghijklmnopqrstuvwxyz");
    Map<String, Object> header = new HashMap<>(2);
    header.put("Type", "JWT");
    return JWT.create()
        // 添加头部
        .withHeader(header)
        .withClaim("a", "a")
        .withClaim("c", "c")
        .withClaim("b", "b")
        // 设置过期时间
        .withExpiresAt(new Date(timeMillis + 60000))
        // 设置发布时间
        .withIssuedAt(new Date(timeMillis))
        .withIssuer("myIssuer")
        // 设置签名 密钥
        .sign(algorithm);
  }

  public static String jwtCreate3(Long timeMillis) throws JoseException {
    JwtClaims claims = new JwtClaims();
    claims.setClaim("c", "c");
    claims.setClaim("b", "b");
    claims.setClaim("a", "a");
    claims.setIssuer("myIssuer");
    claims.setExpirationTime(NumericDate.fromMilliseconds(timeMillis + 60000));
    claims.setIssuedAt(NumericDate.fromMilliseconds(timeMillis));
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(new HmacKey("0123456789abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.UTF_8)));
    jws.setHeader("Type", "JWT");
    jws.setHeader("typ", "JWT");
    jws.setHeader("alg", "HS256");
    return jws.getCompactSerialization();
  }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中使用JWT(JSON Web Token)进行密和解密是一种常见的身份验证和授权机制。JWT由三部分组成:头部(Header)、载荷(Payload)和签名(Signature)。 1. 头部(Header):包含了算法和令牌类型等信息,通常使用Base64编码表示。 2. 载荷(Payload):包含了要传输的数据,比如用户ID、角色等信息,同样使用Base64编码表示。 3. 签名(Signature):使用私钥对头部和载荷进行签名,以确保数据的完整性和真实性。 下面是使用Java进行JWT密和解密的步骤: 1. 导入相关依赖:在项目的pom.xml文件中添以下依赖: ```xml <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> ``` 2. 创建JWT生成器:使用`Jwts.builder()`创建一个JWT生成器对象。 ```java JwtBuilder builder = Jwts.builder(); ``` 3. 设置头部和载荷信息:使用`setHeader()`和`setClaims()`方法设置头部和载荷信息。 ```java builder.setHeader(headerMap); builder.setClaims(claimsMap); ``` 4. 设置签名:使用`signWith()`方法设置签名算法和私钥。 ```java builder.signWith(SignatureAlgorithm.HS256, secretKey); ``` 5. 生成JWT:使用`compact()`方法生成最终的JWT字符串。 ```java String jwt = builder.compact(); ``` 6. 解密JWT:使用`Jwts.parser()`创建一个JWT解析器对象,并使用`setSigningKey()`方法设置公钥或密钥。 ```java Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody(); ``` 以上是使用Java进行JWT密和解密的基本步骤。需要注意的是,生成JWT时需要使用私钥进行签名,解密JWT时需要使用公钥或密钥进行验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值