Jwt手写加密解密

pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.baojiaren</groupId>
    <artifactId>jwt</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.18.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.codec -->
        <dependency>
            <groupId>org.apache.directory.studio</groupId>
            <artifactId>org.apache.commons.codec</artifactId>
            <version>1.8</version>
        </dependency>
    </dependencies>
</project>
package com.baojiaren.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Base64;


/**
 * @author ✎ℳ๓₯㎕.倾心❀、
 * @create 2021-07-30-23:00
 * 手写一个jwt的案例
 */
public class JWTUtils {
//eyJBbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImJqciIsInVzZXJJZCI6IjE4ODg4IiwiYWdlIjoiMTgifQ==.ab9264eceda7b977a9ad906f145326b8
    public static void main(String[] args) {
        //加密
      String  jwt = JWTUtils.verifySignatureHS256("bjr","18","18888","baojiaren");
        boolean b = false;
        try {
            b = JWTUtils.decryptJwt(jwt,"baojiaren");
            System.out.println(b);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String s = JWTUtils.replaceCharacter("15869458358", 1, 13, "*").toString();
        System.out.println(s);
    }

    /**
     *字符串替换
     * @param str
     * @param start
     * @param end
     * @param content
     * @return
     */
    public static Object replaceCharacter(String str,Integer start,Integer end,String content){
        if (start==0){
            return new RuntimeException("start is Cannot equal zero");
        }
        if (end>str.length()){
            return new RuntimeException("end is Cannot be greater than:"+str+" string length");
        }
        System.out.println(str);
        StringBuffer sb=new StringBuffer(str);
        for (int i = 0; i < sb.length(); i++) {
            if (i>=start && i<=end){
                sb.replace(i-1,i,content);
            }
        }
        return  sb.toString();
    }

    /**
     * 验证签名
     * @return
     */
    public static   String verifySignatureHS256(String userName,String age,String userId, String key){
        JSONObject header=new JSONObject(); //头部信息
        header.put("Alg","HS256"); //定义加密方式
        JSONObject payLoad = new JSONObject();
        payLoad.put("userName",userName);
        payLoad.put("age",age);
        payLoad.put("userId",userId);
        payLoad.put("rd",System.currentTimeMillis());
        // base64 对实现数据编码
        String jwtHeader= Base64.getEncoder().encodeToString(header.toJSONString().getBytes());
        String jwtPayLoad=Base64.getEncoder().encodeToString(payLoad.toJSONString().getBytes());
        // 签名 后面加盐
        String sign= DigestUtils.md5Hex(payLoad.toJSONString()+key);
        String jwt=jwtHeader+"."+jwtPayLoad+"."+sign;
        System.out.println(jwt);
        return jwt;
    }


    /**
     * 解密匹配
     * @param jwt
     * @param key
     * @return
     * @throws UnsupportedEncodingException
     */
    public static boolean decryptJwt(String jwt,String key) throws UnsupportedEncodingException {
        String payLoadStr= new String(Base64.getDecoder().decode(jwt.split("\\.")[1].getBytes()),"UTF-8");
        String sign=jwt.split("\\.")[2];
        System.out.println(DigestUtils.md5Hex(payLoadStr+key).equals(sign));

        return DigestUtils.md5Hex(payLoadStr+key).equals(sign);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

௸྄ིོུ倾心ღ᭄ᝰꫛꫀꪝ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值