package com.czg.third.wechat;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Base64;

/**
 * 微信支付加解密
 * @author yjjie
 * @date 2025/12/26 10:58
 */
@Slf4j
public class WechatEncrypt {

    public static String rsaEncryptOaep(String message, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] data = message.getBytes(StandardCharsets.UTF_8);
            byte[] cipherData = cipher.doFinal(data);
            return Base64.getEncoder().encodeToString(cipherData);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            log.error("当前Java环境不支持RSA v1.5/OAEP");
        } catch (InvalidKeyException e) {
            log.error("无效的证书");
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            log.error("加密原串的长度不能超过214字节");
        }
        return "";
    }

    public static String getFileBytesSha256(byte[] input) throws NoSuchAlgorithmException  {
        return bytesToHex(calculateSha256(input));
    }

    /**
     * 核心方法：计算字节数组的 SHA-256 哈希值
     * @param input 待计算的字节数组
     * @return SHA-256 哈希值（32 字节的字节数组）
     */
    private static byte[] calculateSha256(byte[] input) throws NoSuchAlgorithmException {
        // 获取 SHA-256 消息摘要实例（Java 21 完全兼容）
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        // 计算哈希值
        return digest.digest(input);
    }

    /**
     * 辅助方法：将字节数组转换为十六进制字符串（SHA-256 结果常用格式）
     * @param bytes 待转换的字节数组
     * @return 十六进制字符串（SHA-256 对应 64 位字符串）
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        // Java 21 可使用 var 简化声明
        for (var b : bytes) {
            // 将字节转换为两位十六进制数，不足补 0
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
