package thyyxxk.webserver.service.ca;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.codec.Base64;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

@Slf4j
@Service
public class CaUtils {
    private static String SIGN_ALGORITHMS = "SHA256WithRSA";

    public static String GetSHA256FormString(String inData) {
        byte[] digest = SecureUtil.sha256().digest(inData.getBytes(StandardCharsets.UTF_8));
        return Base64.encode(digest);
    }

    public static String getSign(String privateKey, String data) {
        byte[] signData = signature(privateKey, data);
        String sign = null;
        if (signData != null) {
            sign = Base64.encode(signData);
        }
        return sign;
    }

    public static byte[] signature(String privateKey, String data) {
        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
                    Base64.decode(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyFactory.generatePrivate(keySpec);

            Signature oSig = Signature.getInstance(SIGN_ALGORITHMS);
            oSig.initSign(priKey);
            oSig.update(data.getBytes(StandardCharsets.UTF_8));
            return oSig.sign();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
