package com.zjrs.ggfw.portal.utils;

import org.springframework.beans.factory.annotation.Value;

import java.util.Random;

/**
 * EncryptionUtil加密工具类
 */
public class EncryptionUtil {
    @Value("${ems.mrkey:a7cc6c5acf497f8cec13fd9004fcbadf}")
    private static String KEY;//默认key
    private static int RANDOM_LENGTH = 16;
    public final static String DATA_ERROR = "Data error!";

    /**
     * 加密
     * @param content
     * @param key
     * @return
     */
    public static String encodeContent(String content, String key) {
        // 获取16位随机数
        String randomStr = getRandom(RANDOM_LENGTH);
        String contentStr = randomStr + content;
        // MD5
        String md5Str = MD5Util.MD5(contentStr);
        // 加密
        return AESUtil.encrypt((contentStr + md5Str), key);
    }




        /**
        * 生成随机数
         * @param length 随机数长度
         * @return String 随机数
         */
    public static String getRandom(int length) {// length 小于或等于16
        String substring ;
        String random = new Random().nextLong() + "";
        if(!(random.length() <= 16)){
            substring = random.substring(0, length);
        }else{
            System.out.println("生成随机数不合格了");
            substring = getRandom(length);
        }
        return substring;
    }

    /**
     * 解密
     * @param content
     * @param key
     * @return
     */
    public static String decodeContent(String content, String key) {
        String result = DATA_ERROR;
        content = AESUtil.decrypt(content, key);
        // 解密
        String contentStr = content.substring(0, content.length() - 32);
        String md5Str = content.substring(content.length() - 32);
        String checkMd5Str = MD5Util.MD5(contentStr);
        if (md5Str.equals(checkMd5Str)) {
            result = contentStr.substring(16);
        }
        return result;
    }
}
