package me.qwq.doghouse.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

import org.bouncycastle.crypto.digests.SHA3Digest;
import org.bouncycastle.util.encoders.Hex;
import lombok.extern.slf4j.Slf4j;

/**
 * 加密相关
 * @author Doghole
 *
 */
@Slf4j
public class Cryptos {
    
    public static String md5(byte[] bytes) {
        String resultString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return Hex.toHexString(md.digest(bytes));
        } catch (Exception e) {
            log.error("MD5 Hash failed", e);
        }
        return resultString;
    }

    public static String md5(String origin) {
        if (origin == null) return origin;
        return md5(origin.getBytes());
    }
    
    public static byte[] sha3(byte[] bytes, int digit) {
        SHA3Digest digest = new SHA3Digest(digit);
        digest.update(bytes, 0, bytes.length);
        byte[] rsData = new byte[digest.getDigestSize()];
        digest.doFinal(rsData, 0);
        return rsData;
    }
    
    public static String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            log.error("SHA-256 Hash failed", e);
            return null;
        }
    }
    
    public static String sha256Hex(InputStream in) throws IOException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        try (DigestInputStream dis = new DigestInputStream(in, digest)) {
            byte[] buffer = new byte[8192];
            while (dis.read(buffer) != -1) {
                // just read
            }
        }
        byte[] hash = digest.digest();
        return HexFormat.of().formatHex(hash);
    }
    
    public static String sha3(String data, int digit) {
        return Hex.toHexString(sha3(data.getBytes(), digit));
    }
    
    public static String toHexString(byte[] data) {
        return Hex.toHexString(data);
    }
    
    public static void main(String[] args) {
    }
}
