jiangping
2024-11-29 a2e8793e2c53c7e80b67c1fe407b78fde59b2296
server/system_service/src/main/java/com/doumee/core/utils/DESUtil.java
@@ -1,5 +1,12 @@
package com.doumee.core.utils;
import com.alibaba.fastjson.JSONObject;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
@@ -7,8 +14,12 @@
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Key;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class DESUtil {
@@ -169,4 +180,54 @@
        }
        return null;
    }
    /**
     * 海康加密
     * @param userName
     * @param hour
     * @return
     */
    public static  String generateTokenToHk(String userName,Integer hour, RedisTemplate<String,Object> redisTemplate) {
         long currentTimeMillis = System.currentTimeMillis() + 1000*60*60*hour;
         String encrypt = DESUtil.encrypt("12345678",currentTimeMillis + "_" + userName );
        try{
//            encrypt =  Base64.getEncoder().encodeToString(encrypt.getBytes());
//            encrypt = URLEncoder.encode(encrypt,"UTF-8");
        }catch (Exception e){
            throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"生成加密码失败!");
        }
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(Constants.REDIS_HK_TOKEN_KEY+token, encrypt,1000*60*60*hour, TimeUnit.MILLISECONDS);
        return token;
    }
    /**
     * 海康解码
     * @param token
     * @return
     */
    public static String verifyHkToken(String token){
        String decrypt = DESUtil.decrypt("12345678",token);
        if(StringUtils.isBlank(decrypt)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"token解析失败");
        }
        try{
            Integer index_ = decrypt.indexOf("_");
            long currentTimeMillis = Long.valueOf(decrypt.substring(Constants.ZERO,index_));
            if(currentTimeMillis<=System.currentTimeMillis()){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"token已过期");
            }
            String userName = decrypt.substring(index_+Constants.ONE);
            return userName ;
        }catch (Exception e){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"token解析失败");
        }
    }
}