1package com.peachpasswords.vault23import org.bouncycastle.crypto.generators.Argon2BytesGenerator4import org.bouncycastle.crypto.params.Argon2Parameters5import java.security.SecureRandom6import java.text.Normalizer7import javax.crypto.Cipher8import javax.crypto.spec.GCMParameterSpec9import javax.crypto.spec.SecretKeySpec1011object VaultCrypto {12 const val ARGON2_MEMORY_KB = 6553613 const val ARGON2_ITERATIONS = 314 const val ARGON2_PARALLELISM = 415 const val ARGON2_HASH_LENGTH = 3216 const val SALT_SIZE = 1617 const val NONCE_SIZE = 1218 const val TAG_LENGTH_BITS = 12819 const val KEY_SIZE = 3220 const val PAD_BLOCK = 102421 const val DURESS_SLOT_SIZE = 262_1442223 val PADDING_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)24 private const val LARGE_PADDING_STEP = 65_5362526 const val AAD_SLOT_A = "slot_a_v1"27 const val AAD_SLOT_B = "slot_b_v1"28 const val AAD_ROOT_KEY = "pw_root_v1"2930 3132333435 const val AAD_RECOVERY = "recovery_escrow_v1"3637 383940414243 val AAD_RECOVERY_ROOTKEY = byteArrayOf(1)4445 private val secureRandom = SecureRandom()46 private var _lastTimestamp = 0L4748 495051525354555657 fun deriveKey(password: String, salt: ByteArray): ByteArray =58 deriveKeyFromBytes(59 Normalizer.normalize(password, Normalizer.Form.NFC).toByteArray(Charsets.UTF_8),60 salt,61 )6263 6465666768 fun deriveKeyRaw(password: String, salt: ByteArray): ByteArray =69 deriveKeyFromBytes(password.toByteArray(Charsets.UTF_8), salt)7071 private fun deriveKeyFromBytes(passwordBytes: ByteArray, salt: ByteArray): ByteArray {72 val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)73 .withSalt(salt)74 .withParallelism(ARGON2_PARALLELISM)75 .withMemoryAsKB(ARGON2_MEMORY_KB)76 .withIterations(ARGON2_ITERATIONS)77 .build()78 val generator = Argon2BytesGenerator().apply { init(params) }79 val hash = ByteArray(ARGON2_HASH_LENGTH)80 try {81 generator.generateBytes(passwordBytes, hash)82 } finally {83 84 passwordBytes.fill(0)85 }86 return hash87 }8889 fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray =90 encrypt(plaintext, key, aad.toByteArray(Charsets.UTF_8))9192 fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray =93 decrypt(data, key, aad.toByteArray(Charsets.UTF_8))9495 96979899100 fun encrypt(plaintext: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {101 val nonce = ByteArray(NONCE_SIZE).also(secureRandom::nextBytes)102 val cipher = Cipher.getInstance("AES/GCM/NoPadding")103 cipher.init(104 Cipher.ENCRYPT_MODE,105 SecretKeySpec(key, "AES"),106 GCMParameterSpec(TAG_LENGTH_BITS, nonce),107 )108 cipher.updateAAD(aad)109 return nonce + cipher.doFinal(plaintext)110 }111112 fun decrypt(data: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {113 require(data.size >= NONCE_SIZE) { "Data too short" }114 val nonce = data.copyOfRange(0, NONCE_SIZE)115 val ciphertext = data.copyOfRange(NONCE_SIZE, data.size)116 val cipher = Cipher.getInstance("AES/GCM/NoPadding")117 cipher.init(118 Cipher.DECRYPT_MODE,119 SecretKeySpec(key, "AES"),120 GCMParameterSpec(TAG_LENGTH_BITS, nonce),121 )122 cipher.updateAAD(aad)123 return cipher.doFinal(ciphertext)124 }125126 fun generateSalt(): ByteArray = ByteArray(SALT_SIZE).also(secureRandom::nextBytes)127 fun generateRootKey(): ByteArray = ByteArray(KEY_SIZE).also(secureRandom::nextBytes)128 fun generateNoise(): ByteArray = ByteArray(DURESS_SLOT_SIZE).also(secureRandom::nextBytes)129130 fun padToBucket(data: ByteArray): ByteArray {131 val target = PADDING_BUCKETS.firstOrNull { it >= data.size }?.toLong()132 ?: run {133 val size = data.size.toLong()134 val remainder = size % LARGE_PADDING_STEP135 size + if (remainder == 0L) 0L else LARGE_PADDING_STEP - remainder136 }137 require(target <= Int.MAX_VALUE) { "padded plaintext is too large" }138 return data.copyOf(target.toInt())139 }140141 fun padToBlock(data: ByteArray): ByteArray {142 val remainder = data.size % PAD_BLOCK143 if (remainder == 0) return data144 return data.copyOf(data.size + (PAD_BLOCK - remainder))145 }146147 @Synchronized148 fun monotonicEntryTimestamp(currentModifiedAt: Long? = null): Long {149 val base = maxOf(System.currentTimeMillis(), (currentModifiedAt ?: 0L) + 1L, _lastTimestamp + 1L)150 _lastTimestamp = base151 return base152 }153154 155156157158159160161162163 fun resetMonotonicClockForTest() {164 _lastTimestamp = 0L165 }166167 fun zero(bytes: ByteArray) {168 bytes.fill(0)169 }170}