Jwt加解密-Java

Jwt加解密-Java工具类引入依赖包<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.10.3</version></dependency>工具类packagecom.gallant.test;importcom.auth0.jwt.JWT;importcom.auth0.j

工具类

引入依赖包

<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();
  }

今天的文章Jwt加解密-Java分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/5468.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注