package cn.gintone.encryptionUtils;


import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

// 生成公私钥
public class PemFileGenerator {

    // 生成RSA密钥对
    public static KeyPair generateRSAKeyPair(int keySize) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    }

    // 将公钥转换为PEM格式字符串
    public static String publicKeyToPem(PublicKey publicKey) {
        byte[] encoded = publicKey.getEncoded();
        String base64 = Base64.getEncoder().encodeToString(encoded);
        return formatPem(base64, "PUBLIC KEY");
    }

    // 将私钥转换为PEM格式字符串
    public static String privateKeyToPem(PrivateKey privateKey) {
        byte[] encoded = privateKey.getEncoded();
        String base64 = Base64.getEncoder().encodeToString(encoded);
        return formatPem(base64, "PRIVATE KEY");
    }

    // 格式化PEM内容
    private static String formatPem(String base64, String keyType) {
        StringBuilder pem = new StringBuilder();
        pem.append("-----BEGIN ").append(keyType).append("-----\n");

        // 每64个字符换行
        int lineLength = 64;
        for (int i = 0; i < base64.length(); i += lineLength) {
            int end = Math.min(i + lineLength, base64.length());
            pem.append(base64, i, end).append("\n");
        }

        pem.append("-----END ").append(keyType).append("-----\n");
        return pem.toString();
    }


    // 完整生成示例
    public static Map<String, String> generateAndSaveKeyPair(int keySize) throws Exception {
        // 生成密钥对
        KeyPair keyPair = generateRSAKeyPair(keySize);

        // 转换为PEM格式
        String publicPem = publicKeyToPem(keyPair.getPublic());
        String privatePem = privateKeyToPem(keyPair.getPrivate());

        Map<String, String> keyMap = new HashMap<String, String>();
        keyMap.put("publicPem", publicPem);
        keyMap.put("privatePem", privatePem);
        return keyMap;
    }

    // 测试用例
    public static void main(String[] args) throws Exception {
        // 生成2048位的RSA密钥对
        generateAndSaveKeyPair(
                2048
        );

        System.out.println("密钥对已生成：");
        System.out.println("公钥 -> public_key.pem");
        System.out.println("私钥 -> private_key.pem");
    }
}