package com.sunyard.chsm.utils.gm;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;

import java.io.StringWriter;
import java.security.Provider;
import java.security.Security;
import java.util.Base64;

@Slf4j
public class GMBaseUtil {

    protected static final Provider BC = new BouncyCastleProvider();

    static {
        Security.addProvider(BC);
    }


    protected static byte[] readPem(String type, String pem) {
        try {
            String replaced = pem.replace("-----BEGIN " + type + "-----", "")
                    .replace("\n", "")
                    .replace(System.lineSeparator(), "")
                    .replace("-----END " + type + "-----", "")
                    .replace(" ", "+");
            return Base64.getDecoder().decode(replaced);
        } catch (Exception ex) {
            log.error("read pem error", ex);
            throw new IllegalArgumentException("PEM内容格式错误,读物异常");
        }
    }

    protected static String writePem(String type, byte[] content) {
        try (StringWriter str = new StringWriter(); PemWriter pemWriter = new PemWriter(str);) {
            PemObject pem = new PemObject(type, content);
            pemWriter.writeObject(pem);
            return str.toString();
        } catch (Exception ex) {
            log.error("write pem error", ex);
            throw new IllegalArgumentException("PEM内容格式错误,写入异常");
        }
    }
}
