首页 > 编程语言 >java token自定义实现

java token自定义实现

时间:2023-04-24 13:23:55浏览次数:46  
标签:java String 自定义 Token token static return data public

import com.example.newsmanager.model.Token;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenUtil {

    public static final String TOKEN_NAME = "token";

    private TokenUtil() {}

    public static void addToken(HttpServletResponse response, String data) {
        Token token = new Token(data);
        Cookie cookie = new Cookie(TOKEN_NAME,token.toString());
        cookie.setMaxAge((int) (token.getDuration() / 1000 - 10));
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static boolean verify(HttpServletRequest request) {
        Token token = getTokenFromCookie(request);
        return token != null && token.verify();
    }

    public static boolean verify(HttpServletRequest request, boolean head) {
        if (!verify(request)) {
            return false;
        }else if(head) {
            Token token = getTokenFromHeader(request);
            return token != null && token.verify();
        }else {
            return true;
        }
    }

    private static Token getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (TOKEN_NAME.equals(cookie.getName())) {
                    return Token.valueOf(cookie.getValue());
                }
            }
        }
        return null;
    }

    private static Token getTokenFromHeader(HttpServletRequest request) {
        String tokenStr = request.getHeader(TOKEN_NAME);
        return Token.valueOf(tokenStr);
    }

    public static void deleteToken(HttpServletResponse response) {
        Cookie cookie = new Cookie(TOKEN_NAME,"");
        cookie.setMaxAge(0);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
import com.example.newsmanager.props.TokenProps;
import com.example.newsmanager.util.RSAUtil;
import lombok.Data;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Data
public class Token {
    private String data;
    private long timestamp = System.currentTimeMillis();
    private long duration = 43200000L;//one day
    private String sign;

    public Token(String data, long timestamp, long duration, String sign) {
        this.data = data;
        this.timestamp = timestamp;
        this.duration = duration;
        this.sign = sign;
    }

    public Token(String data, long timestamp, long duration) {
        this.data = data;
        this.timestamp = timestamp;
        this.duration = duration;
        initSign();
    }

    public Token(String data) {
        this.data = data;
        initSign();
    }

    public Token(String data, long duration) {
        this.data = data;
        this.duration = duration;
        initSign();
    }

    private void initSign() {
        try {
            this.sign = RSAUtil.sign(data+","+timestamp+","+duration, TokenProps.getPriKey());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return Base64.getEncoder().encodeToString((data+"\n"+timestamp+"\n"+duration+"\n"+sign).getBytes(StandardCharsets.UTF_8));
    }

    public boolean verify() {
        boolean flag = false;
        try {
            flag = RSAUtil.verify(data+","+timestamp+","+duration, TokenProps.getPubKey(),sign);
            if (flag) {
                long curTime = System.currentTimeMillis();
                flag = timestamp + duration > curTime;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static Token valueOf(String token) {
        if (token != null && token .length() > 0) {
            try {
                byte[] bytes = Base64.getDecoder().decode(token);
                String data = new String(bytes);
                String[] arr = data.split("\n");
                return new Token(arr[0],Long.parseLong(arr[1]),Long.parseLong(arr[2]),arr[3]);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    private static final int KEY_SIZE = 512;
    private static final String SIGN_TYPE = "MD5withRSA";

    private static final int MAX_DECRYPT_BLOCK = KEY_SIZE >> 3;
    private static final int MAX_ENCRYPT_BLOCK = MAX_DECRYPT_BLOCK - 11;

    public static void generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        Key publicKey = keyPair.getPublic();
        Key privateKey = keyPair.getPrivate();
        String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        System.out.println("pub:" + publicKeyStr);
        System.out.println("pri:" + privateKeyStr);
    }

    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.getDecoder().decode(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.getDecoder().decode(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    public static String encrypt(String data, String pubKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(pubKey));
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public static String decrypt(String data, String priKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(priKey));
        byte[] dataBytes = Base64.getDecoder().decode(data);
        int inputLen = dataBytes.length;
        try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            int offset = 0;
            byte[] cache;
            int i = 0;
            while (inputLen - offset > 0) {
                if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_DECRYPT_BLOCK;
            }
            return out.toString("UTF-8");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sign(String data, String priKey) throws Exception {
        Signature signature = Signature.getInstance(SIGN_TYPE);
        signature.initSign(getPrivateKey(priKey));
        signature.update(data.getBytes());
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    public static boolean verify(String srcData, String pubKey, String sign) throws Exception {
        Signature signature = Signature.getInstance(SIGN_TYPE);
        signature.initVerify(getPublicKey(pubKey));
        signature.update(srcData.getBytes());
        return signature.verify(Base64.getDecoder().decode(sign));
    }
}

标签:java,String,自定义,Token,token,static,return,data,public
From: https://www.cnblogs.com/xiaogblog/p/17349119.html

相关文章

  • JavaScript 实现伽马算法
    伽马函数是数学中的一个非常重要的函数,它在统计学、物理学等领域有广泛的应用,其中最重要的应用就在概率统计和计算机科学中。接下来,我们来介绍如何使用JavaScript实现伽马算法。递归实现functiongamma(x){if(x===1){return1;}else{return(x-1)......
  • python jwt token使用
    官网https://pyjwt.readthedocs.io/en/latest/index.html#官网https://pyjwt.readthedocs.io/en/latest/index.html#我们在jwt.encode函数中使用了三个参数:#1)第一个是payload,主要用来存放有效的信息,例如用户名,过期时间等想要传递的信息。payload字典内部官方指定有指定ke......
  • JAVA流程控制
    Java流程控制一、Scanner对象next():一定要读取到有效字符后才可以结束输入对输入有效字符之前遇到的空白,next()方法会自动将其去掉只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符next()不能得到带有空格的字符串nextLine():以Enter为结束符也就是说ne......
  • 前端进化笔记-JavaScript(一)
    简介:实现:三部分ecmascript语言核心DOM文档对象模型BOM浏览器对象模型DOM:用于html的应用程序接口(API),把整个页面映射成一个多层节点结构。例如:<html> <head> <title>samplepage</title> </head> <body> <p>helloworld</p> </body></html>DOM......
  • Java-Day-15( 异常 )
    Java-Day-15异常引出异常(Exception)如:零成分母时,会抛出ArithmeticException异常,然后程序就会崩溃退出,下面的代码也就不执行了但这种不出现致命错误就使得系统崩溃就不合理了所以设计者提供了异常处理机制来解决此问题解决方式—异常捕获如果程序员认为一段......
  • JavaScript 基础问答
      JavaScript数据类型有哪几种?  一共有五种:number、string、object、boolean、undefined.其中最后一个是定义变量后没有赋值介绍隐式类型转换字符串+数字=字符串;字符串-数字=数字;+数字字符串=数字null经过数字转换之后会变为0undefined经过数字转换之后会变为NaN......
  • 设计模式-原型模式-Java中使用示例-节日发送邮件活动
    场景设计模式-原型模式-浅克隆和深克隆在Java中的使用示例:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127576328上面初步记录了原型模式的使用示例,下面再记录一个银行节假日或者搞活动时发送邮件的例子。原型模式原型模式(PrototypePattern)的简单程度仅次......
  • 五分钟理解Java算法的时间复杂度
    关注我了解更多Java技术知识,带你一路“狂飙”到底!上岸大厂不是梦!前言时间复杂度主要是为了反映函数的执行时间随着输入规模增长而变化的规律,在一定程度上可以体现程序的执行效率和算法的优劣。作为程序员,掌握基本的算法时间复杂度的计算是很有必要的。时间复杂度介绍理论上,执......
  • Java-Day-14( 枚举 + 注解 + 自设头文件 )
    Java-Day-14枚举(enumeration,enum)若是创建春夏秋冬四季的信息,如果按传统方法创建,无法固定信息,可以随时调改,所以要用枚举,做到只读且不能改枚举一组常量的集合——属于一种特殊的类,里面只包含一组有限的特定的对象实现方式自定义类实现枚举构造器私有化......
  • Java 常见报错解决方案
    1.常见的java异常分类Throwable类有两个直接子类:Exception:出现的问题是可以被捕获的Check异常:派生自Exception的异常类,必须被捕获或再次声明抛出Runtime异常:派生自RuntimeException的异常类。使用throw语句可以随时抛出这种异常对象thrownewArithmeticException(…);......