package com.yihu.jw.utils.sfutils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.security.provider.SHA;
import java.security.MessageDigest;



/**
 * @className SHAUtils
 * @description  加密算法
 **/
public class SHAUtils {

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


    private static SHA instance = new SHA();

    private SHAUtils() {
    }

    public static SHA getInstance() {
        return instance;
    }

    public static String SHA1(String str) {
        return SHA(str,"SHA1");
    }

    public static String SHA512(String str) {
        return SHA(str,"SHA-512");
    }

    /**
     * SHA-1 加密
     *
     * @param str
     * @return
     */
    public static String SHA(String str,String algorithm) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance(algorithm);
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            logger.info("SHA 加密失败:{}",e);
            return null;
        }
    }

}
