AesEncryptUtils.java 7.93 KB
package cn.com.glsx.smart.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Component
public class AesEncryptUtils {
    //可配置到Constant中,并读取配置文件注入,16位,自己定义
    @Value("${aesencrypt.key}")
    private String KEY;

    //参数分别代表 算法名称/加密模式/数据填充方式
    @Value("${aesencrypt.algorithmstr}")
    private String ALGORITHMSTR;

    //参数分别代表 算法名称/加密模式/数据填充方式
    @Value("${aesencrypt.secret.key}")
    private String secretKey;

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }

    public String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }

    public String encryptSecret(String content) throws Exception {
        return encrypt(content, secretKey);
    }

    public String decryptSecret(String encryptStr) throws Exception {
        return decrypt(encryptStr, secretKey);
    }


    public static void main(String[] args) throws Exception {
        //Map map = new HashMap<String, String>();
        //map.put("key", "value");
        //map.put("中文", "汉字");
        //String content = JSONObject.toJSONString(map);
        //System.out.println("加密前:" + content);
        //
        String encrypt = encrypt1("370342948446986240110", "0BDsQu0naQF9BYGr");
        System.out.println("加密后1:" + encrypt);
        //
        String decrypt = decrypt1("tZvuOJsVI6B8x5Yx3CBOH2MZn/3YhKbUtiVlkP9c+iU=", "0BDsQu0naQF9BYGr");
        System.out.println("解密后1:" + decrypt);

        String encrypt2 = encrypt1("37061517396835532890027292", "tHS9rKB161Oh9Idj");
        System.out.println("加密后:" + encrypt);
        ////
        String decrypt2 = decrypt1("pZz3WfhsWOJSxpky6q8r84EHTSL/rmlkHhcNeWR9bys=", "tHS9rKB161Oh9Idj");
        System.out.println("解密后2:" + decrypt);



        //

        //获取16位随机密钥
        String secret = getGUID();
        System.out.println("生成key:" + secret);



        String beginTime=new String("10:22");
        String endTime=new String("10:22");

        //1  直接用Date自带方法before()和after()比较

        SimpleDateFormat df = new SimpleDateFormat("HH:mm");

        Date sd1=df.parse(beginTime);
        Date sd2=df.parse(endTime);

        System.out.println(sd1.before(sd2));
        System.out.println(sd1.after(sd2));



       // 2  用String的compareTo()方法:

        Integer i=beginTime.compareTo(endTime);

        System.out.println(i);

        //返回正值是代表左侧日期大于参数日期,反之亦然,日期格式必须一致



       // 3  转成date格式换成秒数比较秒数大小,getTime()方法

        Date sd3=df.parse(beginTime);
        Date sd4=df.parse(endTime);

        long long1 =sd1.getTime();

        long long2= sd2.getTime();

        System.out.println(long1);
        System.out.println(long2);


        SnowflakeWorker worker = new SnowflakeWorker(1,1);
        String id = worker.nextId()+"";
        String result = id.substring(id.length()-16,id.length());
        System.out.println("nextid:"+id+"===res:"+result);
    }

    public static String decrypt1(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    /**
     * 生成16位不重复的随机数,含数字+大小写
     * @return
     */
    public static String getGUID() {
        StringBuilder uid = new StringBuilder();
        //产生16位的强随机数
        Random rd = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            //产生0-2的3位随机数
            int type = rd.nextInt(3);
            switch (type){
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(10));
         /*int random = ThreadLocalRandom.current().ints(0, 10)
         .distinct().limit(1).findFirst().getAsInt();*/
                    break;
                case 1:
                    //ASCII在65-90之间为大写,获取大写随机
                    uid.append((char)(rd.nextInt(25)+65));
                    break;
                case 2:
                    //ASCII在97-122之间为小写,获取小写随机
                    uid.append((char)(rd.nextInt(25)+97));
                    break;
                default:
                    break;
            }
        }
        return uid.toString();
    }

    public static String encrypt1(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);

    }

    /**
     * 计算中英文字符串的字节长度 <br/>
     * 一个中文占3个字节
     *
     * @param str
     * @return int 字符串的字节长度
     */
    public static int getLength(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        try {
            return str.getBytes("UTF-8").length;
        } catch (UnsupportedEncodingException e) {
            //logger.error("计算中英文字符串的字节长度失败,", e);
        }
        return 0;
    }

    //將10進制轉換為16進制
    public static String encodeHEX(Integer numb){

        String hex= Integer.toHexString(numb);
        return hex;

    }


    //將16進制字符串轉換為10進制數字
    public static int decodeHEX(String hexs){
        BigInteger bigint=new BigInteger(hexs, 16);
        int numb=bigint.intValue();
        return numb;
    }
}