Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / e2ee-p2p / src / main / java / com / vayunmathur / e2ee / Hkdf.kt
Hkdf.kt42 lines · 1.7 KiBRaw
| 1 | package com.vayunmathur.e2ee |
| 2 | |
| 3 | import javax.crypto.Mac |
| 4 | import javax.crypto.spec.SecretKeySpec |
| 5 | |
| 6 | /** |
| 7 | * HKDF (RFC 5869) over HMAC-SHA256: derive several fixed-purpose sub-keys from one secret so |
| 8 | * that compromising a key derived for one use says nothing about the others. |
| 9 | * |
| 10 | * Lives in the E2EE module (not `:library`) so SDKs and apps can use key |
| 11 | * derivation without depending on the whole base library (#884). |
| 12 | * |
| 13 | * Shared rather than per-app because several features need exactly this: |
| 14 | * `:backup` expands the BIP-0039 seed into the AES-256 master key, |
| 15 | * `:cast:protocol` expands the paired session secret into the control-channel |
| 16 | * and per-stream media keys, and `:sdk:controller` expands its session secret. |
| 17 | */ |
| 18 | object Hkdf { |
| 19 | private const val HMAC = "HmacSHA256" |
| 20 | private const val HASH_LEN = 32 |
| 21 | private const val MAX_BLOCKS = 255 |
| 22 | |
| 23 | fun derive(ikm: ByteArray, info: ByteArray, length: Int, salt: ByteArray = ByteArray(HASH_LEN)): ByteArray { |
| 24 | val prk = hmac(salt, ikm) |
| 25 | val blocks = (length + HASH_LEN - 1) / HASH_LEN |
| 26 | require(blocks <= MAX_BLOCKS) { "HKDF cannot derive more than 255 blocks" } |
| 27 | val output = ByteArray(blocks * HASH_LEN) |
| 28 | var previous = ByteArray(0) |
| 29 | for (i in 1..blocks) { |
| 30 | val mac = Mac.getInstance(HMAC).apply { init(SecretKeySpec(prk, HMAC)) } |
| 31 | mac.update(previous) |
| 32 | mac.update(info) |
| 33 | mac.update(i.toByte()) |
| 34 | previous = mac.doFinal() |
| 35 | previous.copyInto(output, (i - 1) * HASH_LEN) |
| 36 | } |
| 37 | return output.copyOf(length) |
| 38 | } |
| 39 | |
| 40 | private fun hmac(key: ByteArray, data: ByteArray): ByteArray = |
| 41 | Mac.getInstance(HMAC).apply { init(SecretKeySpec(key, HMAC)) }.doFinal(data) |
| 42 | } |