LicenseRepository.kt

5.3 KB · raw

1package com.peachpasswords.license23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import dagger.hilt.android.qualifiers.ApplicationContext7import java.math.BigInteger8import javax.inject.Inject9import javax.inject.Singleton10import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters11import org.bouncycastle.crypto.signers.Ed25519Signer1213@Singleton14class LicenseRepository @Inject constructor(@ApplicationContext context: Context) {15    companion object {16        private const val PUBLIC_KEY_HEX =17            "c7dc52d2c484696cf8566dbe6cfe69025d114cb47f6cf53c25088ecfd539bdfa"1819        private const val PREFS_FILE = "peach_license_prefs"20        private const val KEY_LICENSE = "peach_license"21        private const val KEY_PRO_CELEBRATED = "peach_pro_celebrated"2223        private const val BASE58_ALPHABET =24            "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"2526        // A 76-byte payload encodes to at most 104 base58 characters.27        private const val MAX_BASE58_LENGTH = 1042829        const val PAYLOAD_SIZE = 1230        const val SIGNATURE_SIZE = 6431        const val TOTAL_SIZE = 763233        const val PRODUCT_TAG = 0x01.toByte()34        const val PLAN_TAG = 0x01.toByte()35        const val VERSION_TAG = 0x01.toByte()36    }3738    private val masterKey = MasterKey.Builder(context)39        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)40        .build()4142    private val prefs = EncryptedSharedPreferences.create(43        context,44        PREFS_FILE,45        masterKey,46        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,47        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,48    )4950    fun storeLicense(key: String): Boolean {51        if (!validateLicense(key)) return false52        prefs.edit()53            .putString(KEY_LICENSE, key)54            .remove(KEY_PRO_CELEBRATED)55            .apply()56        return true57    }5859    fun getLicenseKey(): String? = prefs.getString(KEY_LICENSE, null)6061    fun getLicenseIssuedAtMillis(): Long? = getLicenseKey()?.let(::licenseIssuedAtMillis)6263    fun clearLicense() = prefs.edit().remove(KEY_LICENSE).apply()6465    fun isProCelebrated(): Boolean = prefs.getBoolean(KEY_PRO_CELEBRATED, false)6667    fun markProCelebrated() = prefs.edit().putBoolean(KEY_PRO_CELEBRATED, true).apply()6869    fun isProActive(): Boolean = getLicenseKey()?.let(::validateLicense) == true7071    fun hasFeature(feature: ProFeature): Boolean = isProActive()7273    fun validateLicense(licenseKey: String): Boolean {74        return try {75            val decoded = decodeLicenseKey(licenseKey) ?: return false76            if (decoded.size != TOTAL_SIZE) return false77            val payload = decoded.copyOfRange(0, PAYLOAD_SIZE)78            val signature = decoded.copyOfRange(PAYLOAD_SIZE, TOTAL_SIZE)79            if (payload[0] != PRODUCT_TAG) return false80            if (payload[1] != PLAN_TAG) return false81            if (payload[2] != VERSION_TAG) return false82            verifySignature(payload, signature)83        } catch (_: Exception) {84            false85        }86    }8788    fun licenseIssuedAtMillis(licenseKey: String): Long? {89        val decoded = decodeLicenseKey(licenseKey) ?: return null90        if (decoded.size != TOTAL_SIZE) return null91        val payload = decoded.copyOfRange(0, PAYLOAD_SIZE)92        if (payload[0] != PRODUCT_TAG || payload[1] != PLAN_TAG || payload[2] != VERSION_TAG) return null93        val days = (payload[3].toInt() and 0xff) or94            ((payload[4].toInt() and 0xff) shl 8) or95            ((payload[5].toInt() and 0xff) shl 16) or96            ((payload[6].toInt() and 0xff) shl 24)97        return days.toLong() * 86_400_000L98    }99100    private fun decodeLicenseKey(key: String): ByteArray? {101        if (!key.startsWith("PPK-")) return null102        val encoded = key.removePrefix("PPK-").replace("-", "")103        return base58Decode(encoded)104    }105106    private fun base58Decode(input: String): ByteArray? {107        if (input.length > MAX_BASE58_LENGTH) return null108        return try {109            var n = BigInteger.ZERO110            for (char in input) {111                val index = BASE58_ALPHABET.indexOf(char)112                if (index < 0) return null113                n = n.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(index.toLong()))114            }115            val bytes = n.toByteArray()116            if (bytes.isNotEmpty() && bytes[0] == 0.toByte()) bytes.copyOfRange(1, bytes.size) else bytes117        } catch (_: Exception) {118            null119        }120    }121122    private fun verifySignature(payload: ByteArray, signature: ByteArray): Boolean {123        return try {124            val publicKeyBytes = hexToBytes(PUBLIC_KEY_HEX)125            val verifier = Ed25519Signer()126            verifier.init(false, Ed25519PublicKeyParameters(publicKeyBytes, 0))127            verifier.update(payload, 0, payload.size)128            verifier.verifySignature(signature)129        } catch (_: Exception) {130            false131        }132    }133134    private fun hexToBytes(hex: String): ByteArray {135        val len = hex.length136        val data = ByteArray(len / 2)137        for (i in 0 until len step 2) {138            data[i / 2] = ((Character.digit(hex[i], 16) shl 4) +139                Character.digit(hex[i + 1], 16)).toByte()140        }141        return data142    }143}