package com.icing.dialer

import java.security.KeyStore
import java.security.PublicKey
import android.util.Base64

object PublicKeyHelper {

    private const val ANDROID_KEYSTORE = "AndroidKeyStore"

    /**
     * Retrieves the public key associated with the given alias.
     *
     * @param alias The alias of the key pair.
     * @return The public key as a Base64-encoded string.
     * @throws Exception if retrieval fails.
     */
    fun getPublicKey(alias: String): String {
        try {
            val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }

            val certificate = keyStore.getCertificate(alias) ?: throw Exception("Certificate not found for alias \"$alias\".")
            val publicKey: PublicKey = certificate.publicKey

            return Base64.encodeToString(publicKey.encoded, Base64.DEFAULT)
        } catch (e: Exception) {
            throw Exception("Failed to retrieve public key: ${e.message}", e)
        }
    }
}
