package cn.muchinfo.rma.netcore.crypto;

import java.security.MessageDigest;

public class SHA256Encrypt {

    /**
     * sha256加密
     *
     * @param encString
     * @param encType   SHA-256
     * @throws Exception encString 不能为空
     */
    public byte[] encrypt(String encString, String encType) throws Exception {
        try {
            if (encString == null) {
                throw new Exception();
            }
            byte[] tem = encString.getBytes();
            MessageDigest digest = MessageDigest.getInstance(encType);
            digest.reset();
            return digest.digest(tem);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * SHA-256加密
     *
     * @param encString
     * @throws Exception
     */
    public byte[] encrypt(String encString) throws Exception {
        return encrypt(encString, "SHA-256");
    }

    /**
     * @param b 加密后的值
     * @return
     */
    public String getEncryptString(byte[] b) {
        if (b == null) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            buffer.append(byteToString(b[i]));
        }
        return buffer.toString();
    }

    private String byteToString(byte b) {
        int s = 0;
        if (b < 0) {
            s = (int) b + 256;
        } else {
            s = b;
        }
        int a = s / 16;
        int e = s % 16;
        return intToString(a) + intToString(e);
    }

    private String intToString(int i) {
        switch (i) {
            case 0:
                return "0";
            case 1:
                return "1";
            case 2:
                return "2";
            case 3:
                return "3";
            case 4:
                return "4";
            case 5:
                return "5";
            case 6:
                return "6";
            case 7:
                return "7";
            case 8:
                return "8";
            case 9:
                return "9";
            case 10:
                return "A";
            case 11:
                return "B";
            case 12:
                return "C";
            case 13:
                return "D";
            case 14:
                return "E";
            case 15:
                return "F";
            default:
                return "0";
        }
    }
}
