欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Java驗(yàn)證jwt token代碼實(shí)例

 更新時間:2019年12月20日 09:24:19   作者:白馬酒涼  
這篇文章主要介紹了基于Java驗(yàn)證jwt token代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

這篇文章主要介紹了基于Java驗(yàn)證jwt token代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

How to load public certificate from pem file..?地址

1.HS256對稱加密

package jwt;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.Vector;
import java.util.Map;
 
import sun.misc.BASE64Decoder;
 
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
 
 
public class JWTValidator {
  private static String JWT_Type = "JWT";
   
  protected boolean validated;
  protected Object[] claims;
   
  public JWTValidator() {
    setValidated(false);
    setClaims(null);
  }
  public String Generate(String secret, String issuer, String audience, String subject){
    try {
      Algorithm algorithm = Algorithm.HMAC256(secret); // HS256
      String token = JWT.create()
        .withIssuer(issuer)
        .withAudience(audience)
        .withSubject(subject)
        .sign(algorithm);
      System.out.println(token);
      return token;
    } catch (Exception exception){
      //UTF-8 encoding not supported
      return "";
    }
  }
   
 
  public void Validate(String token, String secret, String issuer, String audience, String subject) {
    DecodedJWT jwt = null;
    setValidated(false);
     
    if (token == null || secret == null || issuer == null || audience == null || subject == null)
      return;
     
    try {
      jwt = JWT.require(Algorithm.HMAC256(secret.getBytes())).build().verify(token);
    } catch (JWTVerificationException e) {
      return;
    }
     
    if (jwt == null || jwt.getType() == null || !jwt.getType().contentEquals(JWT_Type))
      return;
     
    if (!jwt.getIssuer().contentEquals(issuer) ||
      !jwt.getAudience().contains(audience) ||
      !jwt.getSubject().contentEquals(subject))
      return;
     
    Date now = new Date();
     
    if ((jwt.getNotBefore() != null && jwt.getNotBefore().after(now)) ||
      (jwt.getExpiresAt() != null && jwt.getExpiresAt().before(now)))
      return;
     
    setValidated(true);
 
    Map<String, Claim> claimsMap = jwt.getClaims();
    Vector<Claim> claimsVector = new Vector<Claim>();
     
    if (claimsMap != null) {
      for (Map.Entry<String, Claim> entry : claimsMap.entrySet()) {
        String key = entry.getKey();
        if (key != null && !key.matches("aud|sub|iss|exp|iat")) {         
          //claimsVector.add(new Claim(key, entry.getValue().asString()));
        }
      }   
    }
 
    setClaims(claimsVector.isEmpty() ? null : claimsVector.toArray());
  }
 
  public boolean isValidated() { return validated; }
  public void setValidated(boolean val) { validated = val; }
 
  public Object[] getClaims() { return claims; }
  public void setClaims(Object[] val) { claims = (val == null ? new Object[0] : val); }
}

2.RS256不對稱加密,需要用public cert來驗(yàn)證

package jwt;
 
import junit.framework.TestCase;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.lang.JoseException;
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
 
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.UUID;
 
public class JWTValidatorForRSA extends TestCase{
 
  public void testCreateToken() throws IOException {
    System.out.println(createToken());
  }
 
  public void testVerifyToken() throws Exception {
    String token = createToken();
    System.out.println(token);
     
    String pkeyPath = "D:\\temp\\idsrv4.crt";
    JwtClaims jwtClaims = verifyToken(token,pkeyPath);
    System.out.println(jwtClaims.getClaimValue("name"));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jwtClaims.getIssuedAt().getValueInMillis()));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jwtClaims.getExpirationTime().getValueInMillis()));
  }
 
  /**
   * 生成jwt,SHA256加密
   * @return
   * @throws IOException
   */
  public String createToken() throws IOException {
    String privateKeyPath = "D:\\temp\\idsrv4.key";
    PrivateKey privateKey = getPrivateKey(getStringFromFile(privateKeyPath));
    final JwtClaims claims = new JwtClaims();
    claims.setClaim("name", "jack");
    claims.setSubject("a@a.com");
    claims.setAudience("test");//用于驗(yàn)證簽名是否合法,驗(yàn)證方必須包含這些內(nèi)容才驗(yàn)證通過
    claims.setExpirationTimeMinutesInTheFuture(-1); // 60*24*30);
    claims.setIssuedAtToNow();
 
    // Generate the payload
    final JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setPayload(claims.toJson());
    jws.setKeyIdHeaderValue(UUID.randomUUID().toString());
 
    // Sign using the private key
    jws.setKey(privateKey);
    try {
      return jws.getCompactSerialization();
    } catch (JoseException e) {
      return null;
    }
  }
 
  /**
   * 驗(yàn)證jwt
   * @param token
   * @return
   * @throws Exception
   */
  public JwtClaims verifyToken(String token,String publicKeyPath) throws Exception {
 
    try {
      PublicKey publicKey = getPublicKey(publicKeyPath);
 
      JwtConsumer jwtConsumer = new JwtConsumerBuilder()
          .setRequireExpirationTime()
          .setVerificationKey(publicKey)
          .setExpectedAudience("test")//用于驗(yàn)證簽名是否合法,可以設(shè)置多個,且可設(shè)置必須存在項(xiàng),如果jwt中不包含這些內(nèi)容則不通過
          .build();
 
      return jwtConsumer.processToClaims(token);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  private String getStringFromFile(String filePath) throws IOException {
    //  生成方法:安裝openssl,執(zhí)行   openssl genrsa -out private.pem 2048
    return IOUtils.toString(new FileInputStream(filePath));
  }
 
  /**
   * 獲取PublicKey對象
   * @param publicKeyBase64
   * @return
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   * @throws CertificateException
   * @throws FileNotFoundException
   */
  private PublicKey getPublicKey(String publicKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, FileNotFoundException {
    /* Not work : data isn't an object ID (tag = 2)
    String pem = publicKeyBase64
        .replaceAll("\\-*BEGIN.*CERTIFICATE\\-*", "")
        .replaceAll("\\-*END.*CERTIFICATE\\-*", "");
    java.security.Security.addProvider(
        new org.bouncycastle.jce.provider.BouncyCastleProvider()
    );
    System.out.println(pem);
     
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pem));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
 
    PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
    */
     
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    FileInputStream is = new FileInputStream (publicKeyPath);
    X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
    PublicKey publicKey = cer.getPublicKey();
     
    System.out.println(publicKey);
     
    return publicKey;
  }
 
  /**
   * 獲取PrivateKey對象
   * @param privateKeyBase64
   * @return
   */
  private PrivateKey getPrivateKey(String privateKeyBase64) {
    String privKeyPEM = privateKeyBase64
        .replaceAll("\\-*BEGIN.*KEY\\-*", "")
        .replaceAll("\\-*END.*KEY\\-*", "");
 
    // Base64 decode the data
    byte[] encoded = Base64.decodeBase64(privKeyPEM);
 
    try {
      DerInputStream derReader = new DerInputStream(encoded);
      DerValue[] seq = derReader.getSequence(0);
 
      if (seq.length < 9) {
        throw new GeneralSecurityException("Could not read private key");
      }
 
      // skip version seq[0];
      BigInteger modulus = seq[1].getBigInteger();
      BigInteger publicExp = seq[2].getBigInteger();
      BigInteger privateExp = seq[3].getBigInteger();
      BigInteger primeP = seq[4].getBigInteger();
      BigInteger primeQ = seq[5].getBigInteger();
      BigInteger expP = seq[6].getBigInteger();
      BigInteger expQ = seq[7].getBigInteger();
      BigInteger crtCoeff = seq[8].getBigInteger();
 
      RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp,
          primeP, primeQ, expP, expQ, crtCoeff);
 
      KeyFactory factory = KeyFactory.getInstance("RSA");
      return factory.generatePrivate(keySpec);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java Swing JProgressBar進(jìn)度條的實(shí)現(xiàn)示例

    Java Swing JProgressBar進(jìn)度條的實(shí)現(xiàn)示例

    這篇文章主要介紹了Java Swing JProgressBar進(jìn)度條的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • Java Bigdecimal使用原理詳解

    Java Bigdecimal使用原理詳解

    這篇文章主要介紹了Java Bigdecimal使用原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-03-03
  • 關(guān)于postman傳參的幾種格式 list,map 等

    關(guān)于postman傳參的幾種格式 list,map 等

    這篇文章主要介紹了postman傳參的幾種格式 list,map等,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • SpringMVC 上傳文件 MultipartFile 轉(zhuǎn)為 File的方法

    SpringMVC 上傳文件 MultipartFile 轉(zhuǎn)為 File的方法

    這篇文章主要介紹了SpringMVC 上傳文件 MultipartFile 轉(zhuǎn)為 File的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • JAVA學(xué)習(xí)之一步步搭建spring框架

    JAVA學(xué)習(xí)之一步步搭建spring框架

    這篇文章主要介紹了JAVA學(xué)習(xí)之一步步搭建spring框架,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例

    Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例

    這篇文章主要介紹了Java編程實(shí)現(xiàn)深度優(yōu)先遍歷與連通分量代碼示例,
    2017-11-11
  • Java enum關(guān)鍵字不識別的快速解決辦法

    Java enum關(guān)鍵字不識別的快速解決辦法

    這篇文章主要介紹了Java enum關(guān)鍵字不識別的快速解決辦法,非常不錯,具有參考借鑒價值,感興趣的朋友一起看看吧
    2016-09-09
  • 學(xué)習(xí)不同 Java.net 語言中類似的函數(shù)結(jié)構(gòu)

    學(xué)習(xí)不同 Java.net 語言中類似的函數(shù)結(jié)構(gòu)

    這篇文章主要介紹了學(xué)習(xí)不同 Java.net 語言中類似的函數(shù)結(jié)構(gòu),函數(shù)式編程語言包含多個系列的常見函數(shù)。但開發(fā)人員有時很難在語言之間進(jìn)行切換,因?yàn)槭煜さ暮瘮?shù)具有不熟悉的名稱。函數(shù)式語言傾向于基于函數(shù)范例來命名這些常見函數(shù)。,需要的朋友可以參考下
    2019-06-06
  • 一文搞懂Runnable、Callable、Future、FutureTask及應(yīng)用

    一文搞懂Runnable、Callable、Future、FutureTask及應(yīng)用

    一般創(chuàng)建線程只有兩種方式,一種是繼承Thread,一種是實(shí)現(xiàn)Runnable接口,在Java1.5之后就有了Callable、Future,這二種可以提供線程執(zhí)行完的結(jié)果,本文主要介紹了Runnable、Callable、Future、FutureTask及應(yīng)用,感興趣的可以了解一下
    2023-08-08
  • JAVA遍歷map的幾種實(shí)現(xiàn)方法代碼

    JAVA遍歷map的幾種實(shí)現(xiàn)方法代碼

    這篇文章主要介紹了JAVA遍歷map的幾種實(shí)現(xiàn)方法,有需要的朋友可以參考一下
    2014-01-01

最新評論