项目工具类

Base64工具类
public class Base64ConvertUtil {

    /**     * 加密JDK1.8     */    public static String encode(String str) throws UnsupportedEncodingException {        byte[] encodeBytes = Base64.getEncoder().encode(str.getBytes("utf-8"));        return new String(encodeBytes);    }

    /**     * 解密JDK1.8     */    public static String decode(String str) throws UnsupportedEncodingException {        byte[] decodeBytes = Base64.getDecoder().decode(str.getBytes("utf-8"));        return new String(decodeBytes);    }

}
/** * 进制转换工具 */public class HexConvertUtil {

    private static final Integer INTEGER_1 = 1;

    private static final Integer INTEGER_2 = 2;

    /**     * 将二进制转换成16进制     */    public static String parseByte2HexStr(byte[] bytes) {        StringBuffer sb = new StringBuffer();        for (byte buff : bytes) {            String hex = Integer.toHexString(buff & 0xFF);            if (hex.length() == INTEGER_1) {                hex = ‘0‘ + hex;            }            sb.append(hex.toUpperCase());        }        return sb.toString();    }

    /**     * 将16进制转换为二进制     */    public static byte[] parseHexStr2Byte(String hexStr) {        if (hexStr.length() < INTEGER_1) {            return null;        }        byte[] result = new byte[hexStr.length() / INTEGER_2];        for (int i = 0, len = hexStr.length() / INTEGER_2; i < len; i++) {            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);            result[i] = (byte) (high * 16 + low);        }        return result;    }}
/** * Json和Object的互相转换,转List必须Json最外层加[],转Object,Json最外层不要加[] */public class JsonConvertUtil {    /**     * JSON 转 Object     */    public static <T> T jsonToObject(String pojo, Class<T> clazz) {        return JSONObject.parseObject(pojo, clazz);    }

    /**     * Object 转 JSON     */    public static <T> String objectToJson(T t){        return JSONObject.toJSONString(t);    }}
/** * Properties工具 */public class PropertiesUtil {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static final Properties PROP = new Properties();

    public static void readProperties(String fileName) {        InputStream in = null;        try {            in = PropertiesUtil.class.getResourceAsStream("/" + fileName);            BufferedReader bf = new BufferedReader(new InputStreamReader(in));            PROP.load(bf);        } catch (IOException e) {            logger.error("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());            throw new CustomException("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());        } finally {            try {                if (in != null) {                    in.close();                }            } catch (IOException e) {                logger.error("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());                throw new CustomException("PropertiesUtil工具类读取配置文件出现IOException异常:" + e.getMessage());            }        }    }

    public static String getProperty(String key){        return PROP.getProperty(key);    }}
/** * Serializable工具(JDK)(也可以使用Protobuf自行百度) */public class SerializableUtil {

    /**     * logger     */    private static final Logger logger = LoggerFactory.getLogger(SerializableUtil.class);

    /**     * 序列化     */    public static byte[] serializable(Object object) {        ByteArrayOutputStream baos = null;        ObjectOutputStream oos = null;        try {            baos = new ByteArrayOutputStream();            oos = new ObjectOutputStream(baos);            oos.writeObject(object);            return baos.toByteArray();        } catch (IOException e) {            logger.error("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());            throw new CustomException("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());        } finally {            try {                if (oos != null) {                    oos.close();                }                if (baos != null) {                    baos.close();                }            } catch (IOException e) {                logger.error("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());                throw new CustomException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());            }        }    }

    /**     * 反序列化     */    public static Object unserializable(byte[] bytes) {        ByteArrayInputStream bais = null;        ObjectInputStream ois = null;        try {            bais = new ByteArrayInputStream(bytes);            ois = new ObjectInputStream(bais);            return ois.readObject();        } catch (ClassNotFoundException e) {            logger.error("SerializableUtil工具类反序列化出现ClassNotFoundException异常:" + e.getMessage());            throw new CustomException("SerializableUtil工具类反序列化出现ClassNotFoundException异常:" + e.getMessage());        } catch (IOException e) {            logger.error("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());            throw new CustomException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());        } finally {            try {                if (ois != null) {                    ois.close();                }                if (bais != null) {                    bais.close();                }            } catch (IOException e) {                logger.error("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());                throw new CustomException("SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());            }        }    }

}
/** * String工具 */public class StringUtil {    /**     * 定义下划线     */    private static final char UNDERLINE = ‘_‘;

    /**     * String为空判断(不允许空格)     */    public static boolean isBlank(String str) {        return str == null || "".equals(str.trim());    }

    /**     * String不为空判断(不允许空格)     */    public static boolean isNotBlank(String str) {        return !isBlank(str);    }

    /**     * Byte数组为空判断     */    public static boolean isNull(byte[] bytes) {        // 根据byte数组长度为0判断        return bytes == null || bytes.length == 0;    }

    /**     * Byte数组不为空判断     */    public static boolean isNotNull(byte[] bytes) {        return !isNull(bytes);    }

    /**     * 驼峰转下划线工具     * @param param     */    public static String camelToUnderline(String param) {        if (isNotBlank(param)) {            int len = param.length();            StringBuilder sb = new StringBuilder(len);            for (int i = 0; i < len; i++) {                char c = param.charAt(i);                if (Character.isUpperCase(c)) {                    sb.append(UNDERLINE);                    sb.append(Character.toLowerCase(c));                } else {                    sb.append(c);                }            }            return sb.toString();        } else {            return "";        }    }

    /**     * 下划线转驼峰工具     */    public static String underlineToCamel(String param) {        if (isNotBlank(param)) {            int len = param.length();            StringBuilder sb = new StringBuilder(len);            for (int i = 0; i < len; i++) {                char c = param.charAt(i);                if (c == 95) {                    ++i;                    if (i < len) {                        sb.append(Character.toUpperCase(param.charAt(i)));                    }                } else {                    sb.append(c);                }            }            return sb.toString();        } else {            return "";        }    }

    /**     * 在字符串两周添加‘‘     */    public static String addSingleQuotes(String param) {        return "\‘" + param + "\‘";    }}
/** * AES加密解密工具类 */@Componentpublic class AesCipherUtil {

    /**     * AES密码加密私钥(Base64加密)     */    private static String encryptAESKey;    // private static final byte[] KEY = { 1, 1, 33, 82, -32, -85, -128, -65 };

    @Value("${encryptAESKey}")    public void setEncryptAESKey(String encryptAESKey) {        AesCipherUtil.encryptAESKey = encryptAESKey;    }

    /**     * logger     */    private static final Logger logger = LoggerFactory.getLogger(AesCipherUtil.class);

    /**     * 加密     */    public static String enCrypto(String str) {        try {            Security.addProvider(new com.sun.crypto.provider.SunJCE());            // 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)            // KeyGenerator 提供对称密钥生成器的功能,支持各种算法            KeyGenerator keygen = KeyGenerator.getInstance("AES");            // 将私钥encryptAESKey先Base64解密后转换为byte[]数组按128位初始化            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");            secureRandom.setSeed(Base64ConvertUtil.decode(encryptAESKey).getBytes());            keygen.init(128, secureRandom);            // SecretKey 负责保存对称密钥 生成密钥            SecretKey desKey = keygen.generateKey();            // 生成Cipher对象,指定其支持的AES算法,Cipher负责完成加密或解密工作            Cipher c = Cipher.getInstance("AES");            // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式            c.init(Cipher.ENCRYPT_MODE, desKey);            byte[] src = str.getBytes();            // 该字节数组负责保存加密的结果            byte[] cipherByte = c.doFinal(src);            // 先将二进制转换成16进制,再返回Base64加密后的String            return Base64ConvertUtil.encode(HexConvertUtil.parseByte2HexStr(cipherByte));        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {            logger.error("getInstance()方法异常:" + e.getMessage());            throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());        } catch (UnsupportedEncodingException e) {            logger.error("Base64加密异常:" + e.getMessage());            throw new CustomUnauthorizedException("Base64加密异常:" + e.getMessage());        } catch (InvalidKeyException e) {            logger.error("初始化Cipher对象异常:" + e.getMessage());            throw new CustomUnauthorizedException("初始化Cipher对象异常:" + e.getMessage());        } catch (IllegalBlockSizeException | BadPaddingException e) {            logger.error("加密异常,密钥有误:" + e.getMessage());            throw new CustomUnauthorizedException("加密异常,密钥有误:" + e.getMessage());        }    }

    /**     * 解密     */    public static String deCrypto(String str) {        try {            Security.addProvider(new com.sun.crypto.provider.SunJCE());            // 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)            // KeyGenerator 提供对称密钥生成器的功能,支持各种算法            KeyGenerator keygen = KeyGenerator.getInstance("AES");            // 将私钥encryptAESKey先Base64解密后转换为byte[]数组按128位初始化            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");            secureRandom.setSeed(Base64ConvertUtil.decode(encryptAESKey).getBytes());            keygen.init(128, secureRandom);            // SecretKey 负责保存对称密钥 生成密钥            SecretKey desKey = keygen.generateKey();            // 生成Cipher对象,指定其支持的AES算法,Cipher负责完成加密或解密工作            Cipher c = Cipher.getInstance("AES");            // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示解密模式            c.init(Cipher.DECRYPT_MODE, desKey);            // 该字节数组负责保存解密的结果,先对str进行Base64解密,将16进制转换为二进制            byte[] cipherByte = c.doFinal(HexConvertUtil.parseHexStr2Byte(Base64ConvertUtil.decode(str)));            return new String(cipherByte);        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {            logger.error("getInstance()方法异常:" + e.getMessage());            throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());        } catch (UnsupportedEncodingException e) {            logger.error("Base64解密异常:" + e.getMessage());            throw new CustomUnauthorizedException("Base64解密异常:" + e.getMessage());        } catch (InvalidKeyException e) {            logger.error("初始化Cipher对象异常:" + e.getMessage());            throw new CustomUnauthorizedException("初始化Cipher对象异常:" + e.getMessage());        } catch (IllegalBlockSizeException | BadPaddingException e) {            logger.error("解密异常,密钥有误:" + e.getMessage());            throw new CustomUnauthorizedException("解密异常,密钥有误:" + e.getMessage());        }    }}
/** * JAVA-JWT工具类 */@Componentpublic class JwtUtil {

    /**     * logger     */    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**     * 过期时间改为从配置文件获取     */    private static String accessTokenExpireTime;

    /**     * JWT认证加密私钥(Base64加密)     */    private static String encryptJWTKey;

    @Value("${accessTokenExpireTime}")    public void setAccessTokenExpireTime(String accessTokenExpireTime) {        JwtUtil.accessTokenExpireTime = accessTokenExpireTime;    }

    @Value("${encryptJWTKey}")    public void setEncryptJWTKey(String encryptJWTKey) {        JwtUtil.encryptJWTKey = encryptJWTKey;    }

    /**     * 校验token是否正确     */    public static boolean verify(String token) {        try {            // 帐号加JWT私钥解密            String secret = getClaim(token, Constant.ACCOUNT) + Base64ConvertUtil.decode(encryptJWTKey);            Algorithm algorithm = Algorithm.HMAC256(secret);            JWTVerifier verifier = JWT.require(algorithm)                    .build();            DecodedJWT jwt = verifier.verify(token);            return true;        } catch (UnsupportedEncodingException e) {            logger.error("JWTToken认证解密出现UnsupportedEncodingException异常:" + e.getMessage());            throw new CustomException("JWTToken认证解密出现UnsupportedEncodingException异常:" + e.getMessage());        }    }

    /**     * 获得Token中的信息无需secret解密也能获得     */    public static String getClaim(String token, String claim) {        try {            DecodedJWT jwt = JWT.decode(token);            // 只能输出String类型,如果是其他类型返回null            return jwt.getClaim(claim).asString();        } catch (JWTDecodeException e) {            logger.error("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());            throw new CustomException("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());        }    }

    /**     * 生成签名     */    public static String sign(String account, String currentTimeMillis) {        try {            // 帐号加JWT私钥加密            String secret = account + Base64ConvertUtil.decode(encryptJWTKey);            // 此处过期时间是以毫秒为单位,所以乘以1000            Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);            Algorithm algorithm = Algorithm.HMAC256(secret);            // 附带account帐号信息            return JWT.create()                    .withClaim("account", account)                    .withClaim("currentTimeMillis", currentTimeMillis)                    .withExpiresAt(date)                    .sign(algorithm);        } catch (UnsupportedEncodingException e) {            logger.error("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());            throw new CustomException("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());        }    }}
/** * 获取当前登录用户工具类 */@Componentpublic class UserUtil {

    private final UsersMapper userMapper;

    @Autowired    public UserUtil(UsersMapper userMapper) {        this.userMapper = userMapper;    }

    /**     * 获取当前登录用户     * @param     */    public UsersDto getUser() {        String token = SecurityUtils.getSubject().getPrincipal().toString();        // 解密获得Account        String account = JwtUtil.getClaim(token, Constant.ACCOUNT);        UsersDto usersDto = new UsersDto();        usersDto.setAccount(account);        usersDto = userMapper.selectOne(usersDto);        // 用户是否存在        if (usersDto == null) {            throw new CustomException("该帐号不存在(The account does not exist.)");        }        return usersDto;    }

    /**     * 获取当前登录用户Id     * @param     */    public Integer getUserId() {        return getUser().getId();    }

    /**     * 获取当前登录用户Token     * @param     */    public String getToken() {        return SecurityUtils.getSubject().getPrincipal().toString();    }

    /**     * 获取当前登录用户Account     */    public String getAccount() {        String token = SecurityUtils.getSubject().getPrincipal().toString();        // 解密获得Account        return JwtUtil.getClaim(token, Constant.ACCOUNT);    }}

原文地址:https://www.cnblogs.com/Treesir/p/11600245.html

时间: 2024-07-30 03:03:33

项目工具类的相关文章

实用篇:说说我在JavaScript项目中使用的工具类

在JavaScript的开发中,我们都会写一些工具类来帮我们简化一些业务操作的逻辑,一下就貼几个我在项目开发过程中常用的工具类.表达能力有限,各位看官还是看源码吧. 一.日期处理工具类. /** * 日期处理工具类 * @Authors: jackyWHJ * @date 2013-10-18 * */ var DateUtils = { /** * 得到日期在一年当中的周数 */ getISOYearWeek: function(date) { var commericalyear = thi

项目中js的工具类

js工具类的功能有: 1.去掉字符串前后空格 2.清空select 3.验证手机号 4.字符串转换int型数字 5.获取checkbox的选中的值 6.去掉左边的空白 7.去掉邮编的空白 源码如下: /** * 去掉字符串前后空格 * * @param str * @returns */ function trim(str){ return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, ''); } /** * 清空select * * @param selec

J2EE开发框架搭建(5) - Java项目开发常用工具类

工具类下项目中的目录位置: 1. 中文转化成拼音.首字母  ,ChineseCharToPinYin,使用这个类的时候必须要加入pinyin.jar,pinyin.jar已经放到hqhop-framework-web项目的lib目录中: 使用方式: ChineseCharToPinYin只提供了两个方法: public static String getPinYin(String src) {.....}      将汉字转换为全拼 public static String getPinYinH

一个使用命令行编译Android项目的工具类

一个使用命令行编译Android项目的工具类 简介 编译apk项目需要使用的几个工具,基本都在sdk中,它们分别是(Windows系统): 1.aapt.exe 资源打包工具 2.android.jar Android编译工具 3.dx.bat dex文件生成工具 4.sdklib.jar 生成apk 5.jarsigner 签名工具 准备 在打包前,需要的环境如下: 1.JDK1.6+ 2.Android SDK 3.上述5个工具的路径 打包过程 1.生成R.java文件 比如: aapt p

iOS开发项目篇—21抽取工具类

iOS开发项目篇—21抽取工具类 一.抽取宏 把和应用相关的信息抽取出来 App Key:1972915028 App Secret:b255603c4dfd82b4785bf9a808ce2662 回调地址:http://www.cnblogs.com/wendingding/ (1)appkey和回调页面在很多地方都要用到 (2)如果是不同应用的话,只需要把这几个参数换掉就可以了.把它们抽取成一个宏,写到pch文件中. 项目的PCH文件 1 #import <Availability.h>

《项目架构那点儿事》——工具类,你喜欢你就拿去

[前言]众所周知,各式各样的Util类为我们提供了便利,也同时减少了我们对底层硬编码的时间,包括对字符串的操作,文件操作,反射的操作,泛型的操作,以及熟知 的分页类,Json解析类.日期工具类等,这里把我开发的项目中用到过的工具类分享出来,都是经过多个项目的开发积累而锤炼出来的,提供给大家交流和学 习. [目录]            1.文件操作类 FileUtil            2.反射工具类 ReflectionUtil            3.泛型工具类 GenericsUti

项目经验分享——Java常用工具类集合 转

http://blog.csdn.net/xyw591238/article/details/51678525 写在前面 本文涉及的工具类部分是自己编写,另一部分是在项目里收集的.工具类涉及数据库连接.格式转换.文件操作.发送邮件等等.提高开发效率,欢迎收藏与转载. 数据库连接工具类 数据库连接工具类——仅仅获得连接对象 ConnDB.java [java] package com.util; import java.sql.Connection; import java.sql.DriverM

Android开源项目大全 - 工具类

主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少View.服务.资源简化初始化,事件绑定等重复繁琐工作 AndroidAnnotations(Code Diet)android快速开发框架 项目地址:https://github.com/excilys/androidannotations 文档介绍:https://github.com/excilys

项目ITP(四) javaweb http json 交互 in action (服务端 spring 手机端 提供各种工具类)勿喷!

前言 系列文章:[传送门] 洗了个澡,准备写篇博客.然后看书了.时间 3 7 分.我慢慢规律生活,向目标靠近.  很喜欢珍惜时间像叮当猫一样 正文 慢慢地,二维码实现签到将要落幕了.下篇文章出二维码实现签到 这次 我们实现 javaweb http json 交互 in action 题目很长,但我想让你们看下,给我点意见. 开始吧 实战 本次以经典的登录作为案例.登录做的好也是经典. 服务端 和 app端,服务端简略,app端详细介绍... 服务端 资料: <spring> @Respons