Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / e2ee-p2p / src / main / java / com / vayunmathur / e2ee / InviteFingerprint.kt

InviteFingerprint.kt43 lines · 1.8 KiBRaw
1package com.vayunmathur.e2ee
2
3import java.security.MessageDigest
4
5/**
6 * Short fingerprint of a public bundle, small enough to ride along in an invite link.
7 *
8 * A [Pqc] bundle is ~3.1 kB (ML-KEM-768 + ML-DSA-65 SPKIs), so the key itself cannot
9 * travel in a URL. An invite instead carries this truncated digest; the recipient still
10 * fetches the full bundle from the relay and checks that it hashes to what the link said.
11 * That removes the relay's ability to substitute a key of its own, since matching a given
12 * digest means a second-preimage search over [LENGTH] bytes rather than a birthday
13 * collision — 2^128 work, versus the 2^64 a same-length collision bound would give.
14 *
15 * The user id is hashed in so a fingerprint lifted from one invite cannot be presented as
16 * some other user's, and the domain string keeps these digests from colliding with any
17 * other use of SHA-256 over the same bundles.
18 */
19object InviteFingerprint {
20 /** Truncated digest length. 16 bytes encodes to 22 unpadded base64url characters. */
21 const val LENGTH = 16
22
23 private const val DOMAIN = "ff-invite-v1"
24
25 /** `SHA-256(DOMAIN || u64be(userId) || publicBundle)`, truncated to [LENGTH]. */
26 fun compute(userId: Long, publicBundle: ByteArray): ByteArray {
27 val md = MessageDigest.getInstance("SHA-256")
28 md.update(DOMAIN.encodeToByteArray())
29 md.update(u64be(userId))
30 md.update(publicBundle)
31 return md.digest().copyOf(LENGTH)
32 }
33
34 private fun u64be(value: Long): ByteArray {
35 val out = ByteArray(U64_BYTES)
36 for (i in 0 until U64_BYTES) out[i] = (value ushr (U64_TOP_SHIFT - i * BYTE_BITS)).toByte()
37 return out
38 }
39
40 private const val U64_BYTES = 8
41 private const val U64_TOP_SHIFT = 56
42 private const val BYTE_BITS = 8
43}