package me.proxylink.plugin.tls;

import java.security.MessageDigest;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.HexFormat;
import java.util.Locale;

public final class CertificateFingerprints {
    private static final HexFormat HEX = HexFormat.of().withUpperCase();

    private CertificateFingerprints() {
    }

    public static String sha256(X509Certificate certificate) throws CertificateEncodingException {
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded());
            return colonDelimited(HEX.formatHex(digest));
        } catch (java.security.NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-256 is not available", e);
        }
    }

    public static String normalize(String fingerprint) {
        if (fingerprint == null) {
            return "";
        }
        return fingerprint
                .replace(":", "")
                .replace("-", "")
                .replace(" ", "")
                .trim()
                .toUpperCase(Locale.ROOT);
    }

    private static String colonDelimited(String hex) {
        StringBuilder builder = new StringBuilder(hex.length() + hex.length() / 2);
        for (int i = 0; i < hex.length(); i += 2) {
            if (i > 0) {
                builder.append(':');
            }
            builder.append(hex, i, i + 2);
        }
        return builder.toString();
    }
}
