package com.junmp.jyzb.auth;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * <pre>
 *
 * 描述：
 * 版本：1.0.0
 * 日期：2024/4/20 14:22
 * 作者：ningzp@junmp.com.cn
 * <br>修改记录
 * <br>修改日期        修改人          修改内容
 *
 * </pre>
 */
public class WsSignService {

    /**
     * WS公钥信息
     */
    public static String getPub() {
        return "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQtXpMxZnykwIoVnRrW290dBX2qBI0T7cvXkmYgpsD1gSNpnm7ZsIXN+ywLToa2f0MUU5bL0Widzb6HNPLTI9Nj2FpJsBPO2POgQrOkwM9V3ookh7HkVTRapw8Nls2sx2hyv7p45BHKSsDcgQMmuONFRUtLwM+EaSNC1o2jdkIhQIDAQAB";
    }

    /**
     * 私钥信息
     */
    public static String getPri() {
        return "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJC1ekzFmfKTAihWdGtbb3R0FfaoEjRPty9eSZiCmwPWBI2mebtmwhc37LAtOhrZ/QxRTlsvRaJ3Nvoc08tMj02PYWkmwE87Y86BCs6TAz1XeiiSHseRVNFqnDw2WzazHaHK/unjkEcpKwNyBAya440VFS0vAz4RpI0LWjaN2QiFAgMBAAECgYAFjRCd9U6MgZsplPduTtmdq/5TserQ2uX6CTHlic0Mfp86F9K/n5d+cITB1VpPQWF1oYDR+qQ/MTeIrKZrPAqbLdhfG1wRvqa6+qa8SFAcJFSA66q55SwZAZDvXYBwHz9RFlfdI9nvwuzuO5Zl5C1zk1eWmMIi0n+UORMrqoZfWQJBAPX1N3X3VbMry/7Xj2Ejk9UQzs9EINvtXRK52HsIwhpD2K+go7hbS+AouIfhemeQUb63yYG7oagJ+XXXX0cWjYsCQQCWnf5lT69ToFIz0gGVODUszw2TO9dkwXQsgsdG2VD9G7y34rSUy+7GMGfID0bJsVj9p4cUDZxZEQhrAg17GKQvAkASL9WwBV/y5bQp3eqeNjFCOgHw1YrQeFa/gbp+LoGby5SEOA6jHS0ZICm08nlImyVQQurFiwhDEqm9ivVinkpNAkBP4FI94FiW/PsbSFBWlox8ywHkB2Rfpsi5olGUnUN6N++Jhc1G7DAhIyKm0pMz+726J9JXLDCye3n/ZgNIOPU5AkEAsO8j5yDN3dBK04kTAGHbbAT0HWt2iN8vi2D+uoSGvGUCKm3xsK5EtyvJ31/FuL4ImaimIMIFi3aZXUbT3HDicA==";
    }

    /**
     * 生成key
     */
    public static RsaKeyPair generateKey(int keySize) {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(keySize);
            //生成密匙对
            KeyPair keyPair = kpg.generateKeyPair();
            String pub = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
            String pri = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
            return new RsaKeyPair(pub, pri);
        } catch (Exception e) {
            throw new RuntimeException("RSA key generate error", e);
        }
    }

    /**
     * 获取公钥（X509格式）
     */
    public static RSAPublicKey getPublicKey() {
        try {
            byte[] keyVal = Base64.getDecoder().decode(getPub());
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyVal);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取私钥（PKCS8格式）
     */
    public static RSAPrivateKey getPrivateKey() {
        try {
            byte[] keyVal = Base64.getDecoder().decode(getPri());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyVal);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建签名
     */
    public static String createSignVal(String data) {
        try {
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(getPrivateKey());
            signature.update(data.getBytes());
            byte[] sign = signature.sign();
            return Base64.getEncoder().encodeToString(sign);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static boolean verifySign(String signVal, String data) {
        try {
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(getPublicKey());
            signature.update(data.getBytes());
            return signature.verify(Base64.getDecoder().decode(signVal));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    public static String getMd5Hash(String input) {
        try {
            // 获取MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要信息
            md.update(input.getBytes());
            // 完成哈希计算，得到结果
            byte[] digest = md.digest();
            // 将结果转换为十六进制的字符串形式
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("程序异常", e);
        }
    }
}
