package com.cool.store.utils;

/**
 * @Author suzhuhong
 * @Date 2025/11/13 12:15
 * @Version 1.0
 */
public class KeyFormatUtil {

    /**
     * 将单行密钥转换为标准PEM多行格式
     */
    public static String convertToPEMFormat(String singleLineKey, String keyType) {
        if (singleLineKey == null || singleLineKey.trim().isEmpty()) {
            throw new IllegalArgumentException("密钥不能为空");
        }

        // 清理密钥，移除可能存在的头尾标记和空白
        String cleanedKey = cleanKey(singleLineKey);

        // 定义头尾标记
        String header = getKeyHeader(keyType);
        String footer = getKeyFooter(keyType);

        // 构建多行格式
        StringBuilder pemKey = new StringBuilder();
        pemKey.append(header).append("\n");

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

        pemKey.append(footer);
        return pemKey.toString();
    }

    /**
     * 清理密钥字符串
     */
    public static String cleanKey(String key) {
        return key.replaceAll("-----BEGIN.*-----", "")
                .replaceAll("-----END.*-----", "")
                .replaceAll("\\s", "")  // 移除所有空白字符
                .trim();
    }

    private static String getKeyHeader(String keyType) {
        switch (keyType.toUpperCase()) {
            case "PRIVATE":
            case "PRIVATE_KEY":
                return "-----BEGIN PRIVATE KEY-----";
            case "PUBLIC":
            case "PUBLIC_KEY":
                return "-----BEGIN PUBLIC KEY-----";
            case "RSA_PRIVATE":
                return "-----BEGIN RSA PRIVATE KEY-----";
            case "RSA_PUBLIC":
                return "-----BEGIN RSA PUBLIC KEY-----";
            default:
                throw new IllegalArgumentException("不支持的密钥类型: " + keyType);
        }
    }

    private static String getKeyFooter(String keyType) {
        switch (keyType.toUpperCase()) {
            case "PRIVATE":
            case "PRIVATE_KEY":
                return "-----END PRIVATE KEY-----";
            case "PUBLIC":
            case "PUBLIC_KEY":
                return "-----END PUBLIC KEY-----";
            case "RSA_PRIVATE":
                return "-----END RSA PRIVATE KEY-----";
            case "RSA_PUBLIC":
                return "-----END RSA PUBLIC KEY-----";
            default:
                throw new IllegalArgumentException("不支持的密钥类型: " + keyType);
        }
    }
}
