VaultCrypto.kt

3.6 KB · raw

1package com.peachpasswords.vault23import org.bouncycastle.crypto.generators.Argon2BytesGenerator4import org.bouncycastle.crypto.params.Argon2Parameters5import java.security.SecureRandom6import javax.crypto.Cipher7import javax.crypto.spec.GCMParameterSpec8import javax.crypto.spec.SecretKeySpec910object VaultCrypto {11    const val ARGON2_MEMORY_KB = 6553612    const val ARGON2_ITERATIONS = 313    const val ARGON2_PARALLELISM = 414    const val ARGON2_HASH_LENGTH = 3215    const val SALT_SIZE = 1616    const val NONCE_SIZE = 1217    const val TAG_LENGTH_BITS = 12818    const val KEY_SIZE = 3219    const val PAD_BLOCK = 102420    const val DURESS_SLOT_SIZE = 262_1442122    val PADDING_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)2324    const val AAD_SLOT_A = "slot_a_v1"25    const val AAD_SLOT_B = "slot_b_v1"26    const val AAD_ROOT_KEY = "pw_root_v1"2728    /**29     * Distinct from [AAD_SLOT_A] so a recovery-escrow blob can never be swapped in30     * as a slot-A blob (GCM auth covers the AAD).31     */32    const val AAD_RECOVERY = "recovery_escrow_v1"3334    private val secureRandom = SecureRandom()35    private var _lastTimestamp = 0L3637    fun deriveKey(password: String, salt: ByteArray): ByteArray {38        val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)39            .withSalt(salt)40            .withParallelism(ARGON2_PARALLELISM)41            .withMemoryAsKB(ARGON2_MEMORY_KB)42            .withIterations(ARGON2_ITERATIONS)43            .build()44        val generator = Argon2BytesGenerator().apply { init(params) }45        val hash = ByteArray(ARGON2_HASH_LENGTH)46        generator.generateBytes(password.toCharArray(), hash)47        return hash48    }4950    fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray {51        val nonce = ByteArray(NONCE_SIZE).also(secureRandom::nextBytes)52        val cipher = Cipher.getInstance("AES/GCM/NoPadding")53        cipher.init(54            Cipher.ENCRYPT_MODE,55            SecretKeySpec(key, "AES"),56            GCMParameterSpec(TAG_LENGTH_BITS, nonce),57        )58        cipher.updateAAD(aad.toByteArray(Charsets.UTF_8))59        return nonce + cipher.doFinal(plaintext)60    }6162    fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray {63        require(data.size >= NONCE_SIZE) { "Data too short" }64        val nonce = data.copyOfRange(0, NONCE_SIZE)65        val ciphertext = data.copyOfRange(NONCE_SIZE, data.size)66        val cipher = Cipher.getInstance("AES/GCM/NoPadding")67        cipher.init(68            Cipher.DECRYPT_MODE,69            SecretKeySpec(key, "AES"),70            GCMParameterSpec(TAG_LENGTH_BITS, nonce),71        )72        cipher.updateAAD(aad.toByteArray(Charsets.UTF_8))73        return cipher.doFinal(ciphertext)74    }7576    fun generateSalt(): ByteArray = ByteArray(SALT_SIZE).also(secureRandom::nextBytes)77    fun generateRootKey(): ByteArray = ByteArray(KEY_SIZE).also(secureRandom::nextBytes)78    fun generateNoise(): ByteArray = ByteArray(DURESS_SLOT_SIZE).also(secureRandom::nextBytes)7980    fun padToBucket(data: ByteArray): ByteArray {81        val target = PADDING_BUCKETS.firstOrNull { it >= data.size } ?: data.size82        return data.copyOf(target)83    }8485    fun padToBlock(data: ByteArray): ByteArray {86        val remainder = data.size % PAD_BLOCK87        if (remainder == 0) return data88        return data.copyOf(data.size + (PAD_BLOCK - remainder))89    }9091    @Synchronized92    fun monotonicEntryTimestamp(currentModifiedAt: Long? = null): Long {93        val base = maxOf(System.currentTimeMillis(), (currentModifiedAt ?: 0L) + 1L, _lastTimestamp + 1L)94        _lastTimestamp = base95        return base96    }9798    fun zero(bytes: ByteArray) {99        bytes.fill(0)100    }101}