登录科普(四)JWT的使用
2018-01-30 本文已影响326人
靈08_1024
JWT的SHA256和RSA256:
本篇采用java-jwt的jar包来实现JWT。主要讲解SHA256和RSA256两种方式,其他的不做讨论。java-jwt是JAVA中最安全的、使用人数最多的jar包。
maven:
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
HS256:
package com.kindo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Date;
/**
* Created by lingbao08 on 2018/1/27.
*/
public class TestJWTHS256 {
private static JWTVerifier verifier = null;
static {
Algorithm algorithm;
try {
algorithm = Algorithm.HMAC256("secret");
verifier = JWT.require(algorithm)
.withIssuer("auth1")
.build();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Test
public void testCreate() {
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
.withIssuer("auth1")
//设置自定义字段
.withClaim("privilege","权限1")
.sign(algorithm);
System.out.println(token);
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (JWTCreationException e){
e.printStackTrace();
}
}
@Test
public void validateAndDecode(){
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMSIsInByaXZpbGlnZSI6Iuadg-mZkDEifQ.jkwTXIdG39VhzDEqEn090MAciuYYNVCGohwd_qJsH-k";
try {
DecodedJWT jwt = verifier.verify(token);
//从jwt中可以直接获取规定的字段,比如issuser,issUsedAt等字段
String issuer = jwt.getIssuer();
//自定义字段的获取
Claim privilege = jwt.getClaim("privilege");
//在不设置日期时,日期为null
Date expiresAt = jwt.getExpiresAt();
System.out.println(expiresAt);
System.out.println(issuer);
System.out.println(privilige.asString());
} catch (JWTVerificationException e){
e.printStackTrace();
}
}
}
RSA256:
首先需要一个RSA工具:
public class RSAUtil {
//非对称密钥算法
public static final String KEY_ALGORITHM="RSA";
/**
* 密钥长度,DH算法的默认密钥长度是1024
* 密钥长度必须是64的倍数,在512到65536位之间
* */
private static final int KEY_SIZE=1024;
//公钥
public static final String PUBLIC_KEY="RSAPublicKey";
//私钥
public static final String PRIVATE_KEY="RSAPrivateKey";
/**
* 初始化密钥对
* @return Map 甲方密钥的Map
* */
public static Map<String,Object> initKey() throws Exception{
//实例化密钥生成器
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance(KEY_ALGORITHM);
//初始化密钥生成器
keyPairGenerator.initialize(KEY_SIZE);
//生成密钥对
KeyPair keyPair=keyPairGenerator.generateKeyPair();
//甲方公钥
RSAPublicKey publicKey=(RSAPublicKey) keyPair.getPublic();
//甲方私钥
RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
//将密钥存储在map中
Map<String,Object> keyMap=new HashMap<>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
}
测试RSA256:
@RestController
public class RSAController {
public static final String ISSUER = "签发人";
private static Algorithm algorithm;
private static RSAPublicKey publicKey;
private static RSAPrivateKey privateKey;
/**
* 计算密钥
**/
@RequestMapping("/calculate")
public void calculate(){
Map<String, Object> stringObjectMap = null;
try {
stringObjectMap = RSACoder.initKey();
} catch (Exception e) {
e.printStackTrace();
}
publicKey = (RSAPublicKey) stringObjectMap.get(RSACoder
.PUBLIC_KEY);
privateKey = (RSAPrivateKey) stringObjectMap.get(RSACoder.PRIVATE_KEY);
algorithm = Algorithm.RSA256(publicKey, privateKey);
}
/**
* 生成JWT
**/
@RequestMapping("create")
public void testCreate() throws Exception {
try {
String token = JWT.create()
.withIssuer(ISSUER)
.sign(algorithm);
System.out.println(token);
} catch (JWTCreationException exception) {
exception.printStackTrace();
}
}
/**
* 校验JWT
**/
@RequestMapping("validate")
public void validateAndDecode(@RequestParam("token") String token) {
try {
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
DecodedJWT jwt = verifier.verify(token);
String issuer = jwt.getIssuer();
System.out.println(issuer);
} catch (JWTVerificationException e) {
e.printStackTrace();
}
}
}
ps:RS256的额外参数参见HS256.
springboot+spring security +io.jwt:参见链接:https://segmentfault.com/a/1190000009231329。