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

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalSafetyNumber.kt

SignalSafetyNumber.kt55 lines · 2.1 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import com.vayunmathur.library.log.Log
4import org.signal.libsignal.protocol.IdentityKey
5import org.signal.libsignal.protocol.ServiceId
6import org.signal.libsignal.protocol.fingerprint.NumericFingerprintGenerator
7
8/**
9 * Safety numbers — the 60-digit fingerprint over both parties' identity keys that users compare out of
10 * band to detect a substituted key.
11 *
12 * Parameters match the official client so the numbers agree with what the other side sees:
13 * `NumericFingerprintGenerator(5200)`, version 2, and each side identified by its ACI's 16 raw UUID
14 * bytes. Any deviation produces a number that looks plausible but never matches.
15 */
16object SignalSafetyNumber {
17 private const val TAG = "SignalSafetyNumber"
18 private const val ITERATIONS = 5200
19 private const val VERSION = 2
20 private const val SAFETY_GROUP = 5
21
22 /**
23 * The displayable safety number for a pair of identities, or null if either ACI or key is unusable.
24 * The result is symmetric: both sides compute the same string.
25 *
26 * [warn] is injectable so this stays testable off-device.
27 */
28 fun compute(
29 localAci: String,
30 localIdentityKey: ByteArray,
31 remoteAci: String,
32 remoteIdentityKey: ByteArray,
33 warn: (String) -> Unit = { Log.status(TAG, it) },
34 ): String? = try {
35 val generator = NumericFingerprintGenerator(ITERATIONS)
36 val fingerprint = generator.createFor(
37 VERSION,
38 aciBytes(localAci),
39 IdentityKey(localIdentityKey),
40 aciBytes(remoteAci),
41 IdentityKey(remoteIdentityKey),
42 )
43 fingerprint.displayableFingerprint.displayText
44 } catch (expected: Throwable) {
45 warn("could not compute a safety number: ${expected.message}")
46 null
47 }
48
49 /** Group the 60 digits into 12 blocks of 5, the way both apps display them. */
50 fun format(displayText: String): String =
51 displayText.chunked(SAFETY_GROUP).joinToString(" ")
52
53 private fun aciBytes(aci: String): ByteArray =
54 ServiceId.Aci.parseFromString(aci).toServiceIdBinary()
55}