package com.wisedu.coeus.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;

public class SecurityUtils {
    private static Logger LOGGER = LoggerFactory.getLogger(SecurityUtils.class);

    /**
     * 把字节数组转成16进位制数
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        //把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toUpperCase();
    }

    /**
     * 将字节数组进行MD5哈希
     *
     * @param input
     * @return
     */
    public static String hashMD5(byte[] input) {
        String md5str = null;
        try {
            //创建一个提供信息摘要算法的对象，初始化为md5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //计算后获得字节数组
            byte[] buff = md.digest(input);
            //把数组每一字节换成16进制连成md5字符串
            md5str = bytesToHex(buff);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return md5str;
    }

    /**
     * 将字符串按照默认的编码（Unicode）方式进行MD5哈希
     *
     * @param str
     * @return
     */
    public static String hashMD5(String str) {
        try {
            byte[] input = str.getBytes("UTF-8");
            return hashMD5(input);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    public static String encode(String text) {
        try {
            byte[] bytes = text.getBytes("utf-8");

            return encode(bytes, true);

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }


    public static String encode(byte[] bytes, boolean nowrap) {
        String base64 = null;
        base64 = new BASE64Encoder().encode(bytes);
        if (nowrap) {
            base64 = base64.replaceAll("[\\r\\n]", "");
        }
        return base64;
    }

    public static String decodeToText(String text) {
        String base64 = null;
        try {
            byte[] bytes = new BASE64Decoder().decodeBuffer(text);
            base64 = new String(bytes, "utf-8");
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return base64;
    }

}
