package thyyxxk.webserver.service.ca;

import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64EncoderStream;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.MessageDigest;
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) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] messageDigest = md.digest(inData.getBytes());
            result = new String(BASE64EncoderStream.encode(messageDigest));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static String getSign(String privateKey, String data) {
        byte[] signData = signature(privateKey, data);
        String sign = null;
        if (signData != null) {
            sign = new String(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;
        }
    }


}
