package org.jeecg.modules.pay.unionPay;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256Util {

    private static final String SHA_256 = "SHA-256";

    public static void main(String[] args) {
        String password = "123456";
        String encryptedPassword = SHA256Util.encrypt(password);
        System.out.println("加密后的密文Encrypted Password: " + encryptedPassword);
        boolean isMatch = SHA256Util.verify(password, encryptedPassword);
        System.out.println("密文校验结果Is Match: " + isMatch);
    }

    /**
     * 对输入数据进行SHA-256加密
     *
     * @param input 输入数据
     * @return 加密后的散列值
     */
    public static String encrypt(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance(SHA_256);
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            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 (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验输入数据与散列值是否匹配
     *
     * @param input      输入数据
     * @param hashString 散列值
     * @return 是否匹配
     */
    public static boolean verify(String input, String hashString) {
        String encryptedInput = encrypt(input);
        return encryptedInput.equals(hashString);
    }
}