session-android/libsession/src/main/java/org/session/libsession/messaging/utilities/SodiumUtilities.kt

253 lines
11 KiB
Kotlin
Raw Normal View History

Add Session Id blinding (#862) * feat: Add Session Id blinding Including modified version of lazysodium-android to expose missing libsodium functions, we could build from a fork which we still need to setup. * Add v4 onion request handling * Update SOGS signature construction * Fix SOGS signature construction * Update onion request * Update signature data * Keep path prefixes for v4 endpoints * Update SOGS signature message * Rename to remove api version suffix * Update onion response parsing * Refactor file download paths * Implement request batching * Refactor batch response handling * Handle batch endpoint responses * Update batch endpoint responses * Update attachment download handling * Handle file downloads * Handle inbox messages * Fix issue with file downloads * Preserve image bytearray encoding * Refactor * Open group message requests * Check id blinding in user detail bottom sheet rather * Message validation refactor * Cache last inbox/outbox server ids * Update message encryption/decryption * Refactor * Refactor * Bypass user details bottom sheet in open groups for blinded session ids * Fix capabilities call auth * Refactor * Revert default server details * Update sodium dependency to forked repo * Fix attachment upload * Revert "Update sodium dependency to forked repo" This reverts commit c7db9529f900d09585ab94e440f6645faa88544e. * Add signed sodium lib * Update contact id truncation and mention logic * Open group inbox messaging fix * Refactor * Update blinded id check * Fix open group message sends * Fix crash on open group direct message send * Direct message refactor * Direct message encrypt/decrypt fixes * Use updated curve25519 version * Updated lazysodium dependency * Update encryption/decryption calls * Handle direct message parse errors * Minor refactor * Existing chat refactor * Update encryption & decryption parameters * Fix authenticated ciphertext size * Set direct message sync target * Update direct message thread lookup * Add blinded id mapping table * Add blinded id mapping table * Update threads after sends * Update open group message timestamp handling * Filter unblinded contacts * Format blinded id mentions * Add message deleted field * Hide open group inbox id * Update message request response handling * Update message request response sender handling * Fix mentions of blinded ids * Handle open group poll failure * fix: add log for failed open group onion request, add decoding body for blinding required error at destination * fix: change the error check * Persist group members * Reschedule polling after capabilities update * Retry on other exceptions * Minor refactor * Open group profile fix * Group member db schema update * Fix ban request key * Update ban response type * Ban endpoint updates * Ban endpoint updates * Delete messages Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-08-10 10:17:48 +02:00
package org.session.libsession.messaging.utilities
import com.goterl.lazysodium.LazySodiumAndroid
import com.goterl.lazysodium.SodiumAndroid
import com.goterl.lazysodium.interfaces.AEAD
import com.goterl.lazysodium.interfaces.GenericHash
import com.goterl.lazysodium.interfaces.Hash
import com.goterl.lazysodium.interfaces.Sign
Add Session Id blinding (#862) * feat: Add Session Id blinding Including modified version of lazysodium-android to expose missing libsodium functions, we could build from a fork which we still need to setup. * Add v4 onion request handling * Update SOGS signature construction * Fix SOGS signature construction * Update onion request * Update signature data * Keep path prefixes for v4 endpoints * Update SOGS signature message * Rename to remove api version suffix * Update onion response parsing * Refactor file download paths * Implement request batching * Refactor batch response handling * Handle batch endpoint responses * Update batch endpoint responses * Update attachment download handling * Handle file downloads * Handle inbox messages * Fix issue with file downloads * Preserve image bytearray encoding * Refactor * Open group message requests * Check id blinding in user detail bottom sheet rather * Message validation refactor * Cache last inbox/outbox server ids * Update message encryption/decryption * Refactor * Refactor * Bypass user details bottom sheet in open groups for blinded session ids * Fix capabilities call auth * Refactor * Revert default server details * Update sodium dependency to forked repo * Fix attachment upload * Revert "Update sodium dependency to forked repo" This reverts commit c7db9529f900d09585ab94e440f6645faa88544e. * Add signed sodium lib * Update contact id truncation and mention logic * Open group inbox messaging fix * Refactor * Update blinded id check * Fix open group message sends * Fix crash on open group direct message send * Direct message refactor * Direct message encrypt/decrypt fixes * Use updated curve25519 version * Updated lazysodium dependency * Update encryption/decryption calls * Handle direct message parse errors * Minor refactor * Existing chat refactor * Update encryption & decryption parameters * Fix authenticated ciphertext size * Set direct message sync target * Update direct message thread lookup * Add blinded id mapping table * Add blinded id mapping table * Update threads after sends * Update open group message timestamp handling * Filter unblinded contacts * Format blinded id mentions * Add message deleted field * Hide open group inbox id * Update message request response handling * Update message request response sender handling * Fix mentions of blinded ids * Handle open group poll failure * fix: add log for failed open group onion request, add decoding body for blinding required error at destination * fix: change the error check * Persist group members * Reschedule polling after capabilities update * Retry on other exceptions * Minor refactor * Open group profile fix * Group member db schema update * Fix ban request key * Update ban response type * Ban endpoint updates * Ban endpoint updates * Delete messages Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-08-10 10:17:48 +02:00
import com.goterl.lazysodium.utils.Key
import com.goterl.lazysodium.utils.KeyPair
import org.session.libsignal.utilities.Hex
import org.session.libsignal.utilities.IdPrefix
import org.session.libsignal.utilities.SessionId
Add Session Id blinding (#862) * feat: Add Session Id blinding Including modified version of lazysodium-android to expose missing libsodium functions, we could build from a fork which we still need to setup. * Add v4 onion request handling * Update SOGS signature construction * Fix SOGS signature construction * Update onion request * Update signature data * Keep path prefixes for v4 endpoints * Update SOGS signature message * Rename to remove api version suffix * Update onion response parsing * Refactor file download paths * Implement request batching * Refactor batch response handling * Handle batch endpoint responses * Update batch endpoint responses * Update attachment download handling * Handle file downloads * Handle inbox messages * Fix issue with file downloads * Preserve image bytearray encoding * Refactor * Open group message requests * Check id blinding in user detail bottom sheet rather * Message validation refactor * Cache last inbox/outbox server ids * Update message encryption/decryption * Refactor * Refactor * Bypass user details bottom sheet in open groups for blinded session ids * Fix capabilities call auth * Refactor * Revert default server details * Update sodium dependency to forked repo * Fix attachment upload * Revert "Update sodium dependency to forked repo" This reverts commit c7db9529f900d09585ab94e440f6645faa88544e. * Add signed sodium lib * Update contact id truncation and mention logic * Open group inbox messaging fix * Refactor * Update blinded id check * Fix open group message sends * Fix crash on open group direct message send * Direct message refactor * Direct message encrypt/decrypt fixes * Use updated curve25519 version * Updated lazysodium dependency * Update encryption/decryption calls * Handle direct message parse errors * Minor refactor * Existing chat refactor * Update encryption & decryption parameters * Fix authenticated ciphertext size * Set direct message sync target * Update direct message thread lookup * Add blinded id mapping table * Add blinded id mapping table * Update threads after sends * Update open group message timestamp handling * Filter unblinded contacts * Format blinded id mentions * Add message deleted field * Hide open group inbox id * Update message request response handling * Update message request response sender handling * Fix mentions of blinded ids * Handle open group poll failure * fix: add log for failed open group onion request, add decoding body for blinding required error at destination * fix: change the error check * Persist group members * Reschedule polling after capabilities update * Retry on other exceptions * Minor refactor * Open group profile fix * Group member db schema update * Fix ban request key * Update ban response type * Ban endpoint updates * Ban endpoint updates * Delete messages Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-08-10 10:17:48 +02:00
import org.whispersystems.curve25519.Curve25519
import kotlin.experimental.xor
object SodiumUtilities {
private val sodium by lazy { LazySodiumAndroid(SodiumAndroid()) }
private val curve by lazy { Curve25519.getInstance(Curve25519.BEST) }
private const val SCALAR_LENGTH: Int = 32 // crypto_core_ed25519_scalarbytes
private const val NO_CLAMP_LENGTH: Int = 32 // crypto_scalarmult_ed25519_bytes
private const val SCALAR_MULT_LENGTH: Int = 32 // crypto_scalarmult_bytes
private const val PUBLIC_KEY_LENGTH: Int = 32 // crypto_scalarmult_bytes
private const val SECRET_KEY_LENGTH: Int = 64 //crypto_sign_secretkeybytes
/* 64-byte blake2b hash then reduce to get the blinding factor */
fun generateBlindingFactor(serverPublicKey: String): ByteArray? {
// k = salt.crypto_core_ed25519_scalar_reduce(blake2b(server_pk, digest_size=64).digest())
val serverPubKeyData = Hex.fromStringCondensed(serverPublicKey)
if (serverPubKeyData.size != PUBLIC_KEY_LENGTH) return null
val serverPubKeyHash = ByteArray(GenericHash.BLAKE2B_BYTES_MAX)
if (!sodium.cryptoGenericHash(serverPubKeyHash, serverPubKeyHash.size, serverPubKeyData, serverPubKeyData.size.toLong())) {
return null
}
// Reduce the server public key into an ed25519 scalar (`k`)
val x25519PublicKey = ByteArray(SCALAR_LENGTH)
sodium.cryptoCoreEd25519ScalarReduce(x25519PublicKey, serverPubKeyHash)
return if (x25519PublicKey.any { it.toInt() != 0 }) {
x25519PublicKey
} else null
}
/*
Calculate k*a. To get 'a' (the Ed25519 private key scalar) we call the sodium function to
convert to an *x* secret key, which seems wrong--but isn't because converted keys use the
same secret scalar secret (and so this is just the most convenient way to get 'a' out of
a sodium Ed25519 secret key)
*/
fun generatePrivateKeyScalar(secretKey: ByteArray): ByteArray? {
// a = s.to_curve25519_private_key().encode()
val aBytes = ByteArray(SCALAR_MULT_LENGTH)
return if (sodium.convertSecretKeyEd25519ToCurve25519(aBytes, secretKey)) {
aBytes
} else null
}
/* Constructs a "blinded" key pair (`ka, kA`) based on an open group server `publicKey` and an ed25519 `keyPair` */
Add emoji reacts support (#889) * feat: Add emoji reacts support * Remove message multi-selection * Add emoji reaction model * Add emoji reaction panel * Blur reacts panel background * Show emoji keyboard * Add emoji sprites * Update reaction proto * Emoji database updates * Emoji database refactor * Emoji reaction persistence * Optimize reactions retrieval * Fix emoji group query * Display emojis * Fix emoji persistence * Cleanup * Persistence refactor * Add reactions bottom sheet * Cleanup * Ui tweaks * React with any emoji * Show emoji react notifications * Remove reaction * Show reactions modal on long press * Click to react (+1) with an emoji * Click to react with an emoji * Enable emoji expand/collapse * fix: some compile issues from merge conflicts * fix: compile issues merging quote and media message UI * fix: xml IDs and adding in legacy is selected for future inclusion * Fix view constraints * Fix merge issue * Add message selection option in conversation context menu * Add sogs emoji integration * Handle sogs emoji reactions * Enable sending/deleting sogs emojis * fix: improve the visible message layout * fix: add file IDs to request parameters for message send (#940) * Fix open group polling from seqno instead of last hash (#939) * fix: reset seqno to get recent messages from open groups * build: upgrade build numbers * fix: actually run the migration * Using StringBuilder to construct request url * Fix reaction filter * fix: is_mms added in second projection query * Update default emojis * fix: include legacy and new open groups in server ID tracking (#941) * feat: add hidden moderator and admin roles, separated as they may be used independently in future (#942) * Cleanup * Fix view constraints * Add reactions capability check * Fix reactions alignment * Ui fixes * Display reactions list * feat: add formatted count strings * fix: account for negatives and add tests * Migrate old official open group locations for polling and adding (#932) * feat: adding in first part of open group migrations and tests for migration logic / helpers * feat: test code and migration logic for open groups in the case of no conflicts * feat: add in extra test cases and refactor code for migrator * refactor: migrate open group join URLs and references to server in adding new open groups to catch legacy and re-write it * refactor: joining open groups using OpenGroupUrlParser.kt now * fix: add in compile issues for renamed OpenGroupApi.kt from OpenGroupV2 * fix: prevent duplicates of http/https for new open group DNS and prevent adding new groups based on public key * fix: room and server swapped parameters * fix: replace default server for config messages * fix: actually using public key to de-dupe didn't work for rooms * build: bump version code and name * Display reactions list on open groups for moderators * Ui tweaks * Ui tweaks for moderation * Refactor * fix: compile issue * fix: de-duping joined queries in the get X from cursor * Restore import * fix: colouring the reaction overlay scrubber * fix: highlight colour, show reaction count if 1 or above * Cleanup * fix: light mode accent * fix: light / dark mode themeing in reactions dialog fragment * Emoji notification blinded id check * fix: show reaction list correctly and pass isUserModerator to bind methods * fix: remove unnecessary places for the moderator * fix: X button for removing own react not showing up properly * feat: add clear all header view * fix: migrate the clear all to the correct location * fix: use display instead of base * Truncate emoji sender ids * feat: add notify thread function in thread db * Notify threads on reaction received * fix: design fixes for the reaction list * fix: emoji reactions bottom sheet dialog UI designs * feat: add unsupported emoji reaction * fix: crash and doing vector properly * Fix reaction database queries * Fix background open group adder job * Show new open group reactions * Fetch a maximum of 5 reactors * Handle open group reactions polling conflicts * Add count to user reaction * Show number of additional reactors * fix: unreads set same as the unread query * fix: design changes * fix: update dependency to improve flexboxlayout behaviour, design consistencies * Add select message icon and update long press menu items order and wording * Fix crash on reactors dialog * fix: colours and backgrounds to match designs * fix: add header in recipient item * fix: margins * fix: alignments and layout issues for emoji reactions view * feat: add overflow previews and logic for overflow * Dim action bar * Add emoji search * Search index fix * Set count for 1:1 and closed group reactions when inserting in local database * Use on screen toolbar to allow overlaying * Show/hide scroll to bottom button * feat: add extended properties so it doesn't collapse on re-bind * Cleanup * feat: prevent keeping extended on rebinding if we get a new message ID * fix: long press works on devices now, fix release lint issue and crash for emoji search DBs from emoji builds * Display message timestamp * Fix modal items alignment * fix: sort order and emoji count in compareTo * Scale down really large messages to fit * Prevent closed group crash * Fix reaction author Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-09-04 13:03:32 +02:00
@JvmStatic
Add Session Id blinding (#862) * feat: Add Session Id blinding Including modified version of lazysodium-android to expose missing libsodium functions, we could build from a fork which we still need to setup. * Add v4 onion request handling * Update SOGS signature construction * Fix SOGS signature construction * Update onion request * Update signature data * Keep path prefixes for v4 endpoints * Update SOGS signature message * Rename to remove api version suffix * Update onion response parsing * Refactor file download paths * Implement request batching * Refactor batch response handling * Handle batch endpoint responses * Update batch endpoint responses * Update attachment download handling * Handle file downloads * Handle inbox messages * Fix issue with file downloads * Preserve image bytearray encoding * Refactor * Open group message requests * Check id blinding in user detail bottom sheet rather * Message validation refactor * Cache last inbox/outbox server ids * Update message encryption/decryption * Refactor * Refactor * Bypass user details bottom sheet in open groups for blinded session ids * Fix capabilities call auth * Refactor * Revert default server details * Update sodium dependency to forked repo * Fix attachment upload * Revert "Update sodium dependency to forked repo" This reverts commit c7db9529f900d09585ab94e440f6645faa88544e. * Add signed sodium lib * Update contact id truncation and mention logic * Open group inbox messaging fix * Refactor * Update blinded id check * Fix open group message sends * Fix crash on open group direct message send * Direct message refactor * Direct message encrypt/decrypt fixes * Use updated curve25519 version * Updated lazysodium dependency * Update encryption/decryption calls * Handle direct message parse errors * Minor refactor * Existing chat refactor * Update encryption & decryption parameters * Fix authenticated ciphertext size * Set direct message sync target * Update direct message thread lookup * Add blinded id mapping table * Add blinded id mapping table * Update threads after sends * Update open group message timestamp handling * Filter unblinded contacts * Format blinded id mentions * Add message deleted field * Hide open group inbox id * Update message request response handling * Update message request response sender handling * Fix mentions of blinded ids * Handle open group poll failure * fix: add log for failed open group onion request, add decoding body for blinding required error at destination * fix: change the error check * Persist group members * Reschedule polling after capabilities update * Retry on other exceptions * Minor refactor * Open group profile fix * Group member db schema update * Fix ban request key * Update ban response type * Ban endpoint updates * Ban endpoint updates * Delete messages Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-08-10 10:17:48 +02:00
fun blindedKeyPair(serverPublicKey: String, edKeyPair: KeyPair): KeyPair? {
if (edKeyPair.publicKey.asBytes.size != PUBLIC_KEY_LENGTH || edKeyPair.secretKey.asBytes.size != SECRET_KEY_LENGTH) return null
val kBytes = generateBlindingFactor(serverPublicKey) ?: return null
val aBytes = generatePrivateKeyScalar(edKeyPair.secretKey.asBytes) ?: return null
// Generate the blinded key pair `ka`, `kA`
val kaBytes = ByteArray(SECRET_KEY_LENGTH)
sodium.cryptoCoreEd25519ScalarMul(kaBytes, kBytes, aBytes)
if (kaBytes.all { it.toInt() == 0 }) return null
val kABytes = ByteArray(PUBLIC_KEY_LENGTH)
return if (sodium.cryptoScalarMultEd25519BaseNoClamp(kABytes, kaBytes)) {
KeyPair(Key.fromBytes(kABytes), Key.fromBytes(kaBytes))
} else {
null
}
}
/*
Constructs an Ed25519 signature from a root Ed25519 key and a blinded scalar/pubkey pair, with one tweak to the
construction: we add kA into the hashed value that yields r so that we have domain separation for different blinded
pubkeys (this doesn't affect verification at all)
*/
fun sogsSignature(
message: ByteArray,
secretKey: ByteArray,
blindedSecretKey: ByteArray, /*ka*/
blindedPublicKey: ByteArray /*kA*/
): ByteArray? {
// H_rh = sha512(s.encode()).digest()[32:]
val digest = ByteArray(Hash.SHA512_BYTES)
val h_rh = if (sodium.cryptoHashSha512(digest, secretKey, secretKey.size.toLong())) {
digest.takeLast(32).toByteArray()
} else return null
// r = salt.crypto_core_ed25519_scalar_reduce(sha512_multipart(H_rh, kA, message_parts))
val rHash = sha512Multipart(listOf(h_rh, blindedPublicKey, message)) ?: return null
val r = ByteArray(SCALAR_LENGTH)
sodium.cryptoCoreEd25519ScalarReduce(r, rHash)
if (r.all { it.toInt() == 0 }) return null
// sig_R = salt.crypto_scalarmult_ed25519_base_noclamp(r)
val sig_R = ByteArray(NO_CLAMP_LENGTH)
if (!sodium.cryptoScalarMultEd25519BaseNoClamp(sig_R, r)) return null
// HRAM = salt.crypto_core_ed25519_scalar_reduce(sha512_multipart(sig_R, kA, message_parts))
val hRamHash = sha512Multipart(listOf(sig_R, blindedPublicKey, message)) ?: return null
val hRam = ByteArray(SCALAR_LENGTH)
sodium.cryptoCoreEd25519ScalarReduce(hRam, hRamHash)
if (hRam.all { it.toInt() == 0 }) return null
// sig_s = salt.crypto_core_ed25519_scalar_add(r, salt.crypto_core_ed25519_scalar_mul(HRAM, ka))
val sig_sMul = ByteArray(SCALAR_LENGTH)
val sig_s = ByteArray(SCALAR_LENGTH)
sodium.cryptoCoreEd25519ScalarMul(sig_sMul, hRam, blindedSecretKey)
if (sig_sMul.any { it.toInt() != 0 }) {
sodium.cryptoCoreEd25519ScalarAdd(sig_s, r, sig_sMul)
if (sig_s.all { it.toInt() == 0 }) return null
} else return null
return sig_R + sig_s
}
private fun sha512Multipart(parts: List<ByteArray>): ByteArray? {
val state = Hash.State512()
sodium.cryptoHashSha512Init(state)
parts.forEach {
sodium.cryptoHashSha512Update(state, it, it.size.toLong())
}
val finalHash = ByteArray(Hash.SHA512_BYTES)
return if (sodium.cryptoHashSha512Final(state, finalHash)) {
finalHash
} else null
}
/* Combines two keys (`kA`) */
fun combineKeys(lhsKey: ByteArray, rhsKey: ByteArray): ByteArray? {
val kA = ByteArray(NO_CLAMP_LENGTH)
return if (sodium.cryptoScalarMultEd25519NoClamp(kA, lhsKey, rhsKey)) {
kA
} else null
}
/*
Calculate a shared secret for a message from A to B:
BLAKE2b(a kB || kA || kB)
The receiver can calculate the same value via:
BLAKE2b(b kA || kA || kB)
*/
fun sharedBlindedEncryptionKey(
secretKey: ByteArray,
otherBlindedPublicKey: ByteArray,
kA: ByteArray, /*fromBlindedPublicKey*/
kB: ByteArray /*toBlindedPublicKey*/
): ByteArray? {
val aBytes = generatePrivateKeyScalar(secretKey) ?: return null
val combinedKeyBytes = combineKeys(aBytes, otherBlindedPublicKey) ?: return null
val outputHash = ByteArray(GenericHash.KEYBYTES)
val inputBytes = combinedKeyBytes + kA + kB
return if (sodium.cryptoGenericHash(outputHash, outputHash.size, inputBytes, inputBytes.size.toLong())) {
outputHash
} else null
}
/* This method should be used to check if a users standard sessionId matches a blinded one */
fun sessionId(
standardSessionId: String,
blindedSessionId: String,
serverPublicKey: String
): Boolean {
// Only support generating blinded keys for standard session ids
val sessionId = SessionId(standardSessionId)
if (sessionId.prefix != IdPrefix.STANDARD) return false
val blindedId = SessionId(blindedSessionId)
if (blindedId.prefix != IdPrefix.BLINDED) return false
val k = generateBlindingFactor(serverPublicKey) ?: return false
// From the session id (ignoring 05 prefix) we have two possible ed25519 pubkeys;
// the first is the positive (which is what Signal's XEd25519 conversion always uses)
val xEd25519Key = curve.convertToEd25519PublicKey(Key.fromHexString(sessionId.publicKey).asBytes)
// Blind the positive public key
val pk1 = combineKeys(k, xEd25519Key) ?: return false
// For the negative, what we're going to get out of the above is simply the negative of pk1, so flip the sign bit to get pk2
// pk2 = pk1[0:31] + bytes([pk1[31] ^ 0b1000_0000])
val pk2 = pk1.take(31).toByteArray() + listOf(pk1.last().xor(128.toByte())).toByteArray()
return SessionId(IdPrefix.BLINDED, pk1).publicKey == blindedId.publicKey ||
SessionId(IdPrefix.BLINDED, pk2).publicKey == blindedId.publicKey
}
fun encrypt(message: ByteArray, secretKey: ByteArray, nonce: ByteArray, additionalData: ByteArray? = null): ByteArray? {
val authenticatedCipherText = ByteArray(message.size + AEAD.CHACHA20POLY1305_ABYTES)
return if (sodium.cryptoAeadXChaCha20Poly1305IetfEncrypt(
authenticatedCipherText,
longArrayOf(0),
message,
message.size.toLong(),
additionalData,
(additionalData?.size ?: 0).toLong(),
null,
nonce,
secretKey
)
) {
authenticatedCipherText
} else null
}
fun decrypt(ciphertext: ByteArray, decryptionKey: ByteArray, nonce: ByteArray): ByteArray? {
val plaintextSize = ciphertext.size - AEAD.XCHACHA20POLY1305_IETF_ABYTES
Add Session Id blinding (#862) * feat: Add Session Id blinding Including modified version of lazysodium-android to expose missing libsodium functions, we could build from a fork which we still need to setup. * Add v4 onion request handling * Update SOGS signature construction * Fix SOGS signature construction * Update onion request * Update signature data * Keep path prefixes for v4 endpoints * Update SOGS signature message * Rename to remove api version suffix * Update onion response parsing * Refactor file download paths * Implement request batching * Refactor batch response handling * Handle batch endpoint responses * Update batch endpoint responses * Update attachment download handling * Handle file downloads * Handle inbox messages * Fix issue with file downloads * Preserve image bytearray encoding * Refactor * Open group message requests * Check id blinding in user detail bottom sheet rather * Message validation refactor * Cache last inbox/outbox server ids * Update message encryption/decryption * Refactor * Refactor * Bypass user details bottom sheet in open groups for blinded session ids * Fix capabilities call auth * Refactor * Revert default server details * Update sodium dependency to forked repo * Fix attachment upload * Revert "Update sodium dependency to forked repo" This reverts commit c7db9529f900d09585ab94e440f6645faa88544e. * Add signed sodium lib * Update contact id truncation and mention logic * Open group inbox messaging fix * Refactor * Update blinded id check * Fix open group message sends * Fix crash on open group direct message send * Direct message refactor * Direct message encrypt/decrypt fixes * Use updated curve25519 version * Updated lazysodium dependency * Update encryption/decryption calls * Handle direct message parse errors * Minor refactor * Existing chat refactor * Update encryption & decryption parameters * Fix authenticated ciphertext size * Set direct message sync target * Update direct message thread lookup * Add blinded id mapping table * Add blinded id mapping table * Update threads after sends * Update open group message timestamp handling * Filter unblinded contacts * Format blinded id mentions * Add message deleted field * Hide open group inbox id * Update message request response handling * Update message request response sender handling * Fix mentions of blinded ids * Handle open group poll failure * fix: add log for failed open group onion request, add decoding body for blinding required error at destination * fix: change the error check * Persist group members * Reschedule polling after capabilities update * Retry on other exceptions * Minor refactor * Open group profile fix * Group member db schema update * Fix ban request key * Update ban response type * Ban endpoint updates * Ban endpoint updates * Delete messages Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-08-10 10:17:48 +02:00
val plaintext = ByteArray(plaintextSize)
return if (sodium.cryptoAeadXChaCha20Poly1305IetfDecrypt(
plaintext,
longArrayOf(plaintextSize.toLong()),
null,
ciphertext,
ciphertext.size.toLong(),
null,
0L,
nonce,
decryptionKey
)
) {
plaintext
} else null
}
fun toX25519(ed25519PublicKey: ByteArray): ByteArray? {
val x25519PublicKey = ByteArray(PUBLIC_KEY_LENGTH)
return if (sodium.convertPublicKeyEd25519ToCurve25519(x25519PublicKey, ed25519PublicKey)) {
x25519PublicKey
} else null
}
/**
* Returns true only if the signature verified successfully
*/
fun verifySignature(signature: ByteArray, publicKey: ByteArray, messageToVerify: ByteArray): Boolean {
return sodium.cryptoSignVerifyDetached(signature, messageToVerify, messageToVerify.size, publicKey)
}
/**
* For signing
*/
fun sign(message: ByteArray, signingKey: ByteArray): ByteArray {
val signature = ByteArray(Sign.BYTES)
if (!sodium.cryptoSignDetached(signature, message, message.size.toLong(), signingKey)) {
throw SecurityException("Couldn't sign the message with the signing key")
}
return signature
}
Add Session Id blinding (#862) * feat: Add Session Id blinding Including modified version of lazysodium-android to expose missing libsodium functions, we could build from a fork which we still need to setup. * Add v4 onion request handling * Update SOGS signature construction * Fix SOGS signature construction * Update onion request * Update signature data * Keep path prefixes for v4 endpoints * Update SOGS signature message * Rename to remove api version suffix * Update onion response parsing * Refactor file download paths * Implement request batching * Refactor batch response handling * Handle batch endpoint responses * Update batch endpoint responses * Update attachment download handling * Handle file downloads * Handle inbox messages * Fix issue with file downloads * Preserve image bytearray encoding * Refactor * Open group message requests * Check id blinding in user detail bottom sheet rather * Message validation refactor * Cache last inbox/outbox server ids * Update message encryption/decryption * Refactor * Refactor * Bypass user details bottom sheet in open groups for blinded session ids * Fix capabilities call auth * Refactor * Revert default server details * Update sodium dependency to forked repo * Fix attachment upload * Revert "Update sodium dependency to forked repo" This reverts commit c7db9529f900d09585ab94e440f6645faa88544e. * Add signed sodium lib * Update contact id truncation and mention logic * Open group inbox messaging fix * Refactor * Update blinded id check * Fix open group message sends * Fix crash on open group direct message send * Direct message refactor * Direct message encrypt/decrypt fixes * Use updated curve25519 version * Updated lazysodium dependency * Update encryption/decryption calls * Handle direct message parse errors * Minor refactor * Existing chat refactor * Update encryption & decryption parameters * Fix authenticated ciphertext size * Set direct message sync target * Update direct message thread lookup * Add blinded id mapping table * Add blinded id mapping table * Update threads after sends * Update open group message timestamp handling * Filter unblinded contacts * Format blinded id mentions * Add message deleted field * Hide open group inbox id * Update message request response handling * Update message request response sender handling * Fix mentions of blinded ids * Handle open group poll failure * fix: add log for failed open group onion request, add decoding body for blinding required error at destination * fix: change the error check * Persist group members * Reschedule polling after capabilities update * Retry on other exceptions * Minor refactor * Open group profile fix * Group member db schema update * Fix ban request key * Update ban response type * Ban endpoint updates * Ban endpoint updates * Delete messages Co-authored-by: charles <charles@oxen.io> Co-authored-by: jubb <hjubb@users.noreply.github.com>
2022-08-10 10:17:48 +02:00
}