feat: Remove debug logging from message sending and user blocking/unblocking functions

This commit is contained in:
k1ngsterr1
2026-01-14 03:44:29 +05:00
parent 671b68103f
commit e9dece8e86
7 changed files with 3 additions and 255 deletions

View File

@@ -77,20 +77,14 @@ object MessageCrypto {
* XChaCha20-Poly1305 encrypt implementation
*/
private fun xchacha20Poly1305Encrypt(plaintext: ByteArray, key: ByteArray, nonce: ByteArray): ByteArray {
android.util.Log.d("MessageCrypto", "🔐 XChaCha20-Poly1305 Encrypt:")
android.util.Log.d("MessageCrypto", " Key hex: ${key.toHex()}")
android.util.Log.d("MessageCrypto", " Nonce hex: ${nonce.toHex()}")
android.util.Log.d("MessageCrypto", " Plaintext hex: ${plaintext.toHex()}")
// Step 1: Derive subkey using HChaCha20
val subkey = hchacha20(key, nonce.copyOfRange(0, 16))
android.util.Log.d("MessageCrypto", " Subkey hex: ${subkey.toHex()}")
// Step 2: Create ChaCha20 nonce (4 zeros + last 8 bytes of original nonce)
val chacha20Nonce = ByteArray(12)
// First 4 bytes are 0
System.arraycopy(nonce, 16, chacha20Nonce, 4, 8)
android.util.Log.d("MessageCrypto", " ChaCha20 nonce hex: ${chacha20Nonce.toHex()}")
// Step 3: Initialize ChaCha20 engine ONCE
val engine = ChaCha7539Engine()
@@ -99,14 +93,11 @@ object MessageCrypto {
// Step 4: Generate Poly1305 key from first 64 bytes of keystream (counter=0)
val poly1305KeyBlock = ByteArray(64)
engine.processBytes(ByteArray(64), 0, 64, poly1305KeyBlock, 0)
android.util.Log.d("MessageCrypto", " Poly1305 key hex: ${poly1305KeyBlock.copyOfRange(0, 32).toHex()}")
// Step 5: Encrypt plaintext (engine continues from counter=1 automatically)
val ciphertext = ByteArray(plaintext.size)
engine.processBytes(plaintext, 0, plaintext.size, ciphertext, 0)
android.util.Log.d("MessageCrypto", " Ciphertext hex: ${ciphertext.toHex()}")
android.util.Log.d("MessageCrypto", " Ciphertext hex: ${ciphertext.toHex()}")
// Step 6: Generate Poly1305 tag
val mac = Poly1305()
@@ -309,15 +300,11 @@ object MessageCrypto {
* КРИТИЧНО: ephemeralKey.getPrivate('hex') в JS может быть БЕЗ ведущих нулей!
*/
fun encryptKeyForRecipient(keyAndNonce: ByteArray, recipientPublicKeyHex: String): String {
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "🔐 ECDH ENCRYPT KEY FOR RECIPIENT")
android.util.Log.d("MessageCrypto", "".repeat(80))
val secureRandom = SecureRandom()
val ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1")
// Генерируем эфемерный приватный ключ (32 байта)
android.util.Log.d("MessageCrypto", "📍 Step 1: Generate ephemeral key pair")
val ephemeralPrivateKeyBytes = ByteArray(32)
secureRandom.nextBytes(ephemeralPrivateKeyBytes)
val ephemeralPrivateKey = BigInteger(1, ephemeralPrivateKeyBytes)
@@ -328,29 +315,20 @@ object MessageCrypto {
val ephemeralPrivateKeyHex = ephemeralPrivateKey.toString(16).let {
// Но если нечётная длина, добавим ведущий 0 для правильного парсинга
if (it.length % 2 != 0) {
android.util.Log.d("MessageCrypto", "⚠️ Padded ephemeral private key (was odd length)")
"0$it"
} else it
}
android.util.Log.d("MessageCrypto", " ✓ Ephemeral private key: $ephemeralPrivateKeyHex")
android.util.Log.d("MessageCrypto", " ✓ Ephemeral private length: ${ephemeralPrivateKeyHex.length} hex chars")
// Получаем эфемерный публичный ключ
val ephemeralPublicKey = ecSpec.g.multiply(ephemeralPrivateKey)
val ephemeralPublicKeyHex = ephemeralPublicKey.getEncoded(false).toHex()
android.util.Log.d("MessageCrypto", " ✓ Ephemeral public key: $ephemeralPublicKeyHex")
// Парсим публичный ключ получателя
android.util.Log.d("MessageCrypto", "\n📍 Step 2: Parse recipient public key")
android.util.Log.d("MessageCrypto", " ✓ Recipient public key: $recipientPublicKeyHex")
val recipientPublicKeyBytes = recipientPublicKeyHex.hexToBytes()
android.util.Log.d("MessageCrypto", " ✓ Recipient key bytes: ${recipientPublicKeyBytes.size}")
val recipientPublicKey = ecSpec.curve.decodePoint(recipientPublicKeyBytes)
// ECDH: ephemeralPrivate * recipientPublic = sharedSecret
android.util.Log.d("MessageCrypto", "\n📍 Step 3: Compute ECDH shared secret")
android.util.Log.d("MessageCrypto", " • Computing: ephemeral_private × recipient_public")
val sharedPoint = recipientPublicKey.multiply(ephemeralPrivateKey)
// ⚠️ КРИТИЧНО: Эмулируем JS поведение!
@@ -358,48 +336,31 @@ object MessageCrypto {
// crypto.enc.Hex.parse(hex) парсит как есть
// Если X coordinate = 0x00abc..., JS получит "abc..." (меньше 32 байт)
val xCoordBigInt = sharedPoint.normalize().xCoord.toBigInteger()
android.util.Log.d("MessageCrypto", " • X coordinate (BigInt): $xCoordBigInt")
var sharedSecretHex = xCoordBigInt.toString(16)
android.util.Log.d("MessageCrypto", " • toString(16) result: $sharedSecretHex (${sharedSecretHex.length} chars)")
// JS: если hex нечётной длины, crypto.enc.Hex.parse добавит ведущий 0
if (sharedSecretHex.length % 2 != 0) {
android.util.Log.d("MessageCrypto", " ⚠️ Padding to even length for hex parsing")
sharedSecretHex = "0$sharedSecretHex"
}
val sharedSecret = sharedSecretHex.hexToBytes()
android.util.Log.d("MessageCrypto", " ✓ SHARED SECRET hex: $sharedSecretHex")
android.util.Log.d("MessageCrypto", " ✓ Shared secret bytes: ${sharedSecret.size} bytes")
// Генерируем IV для AES (16 байт)
android.util.Log.d("MessageCrypto", "\n📍 Step 4: Generate AES IV")
val iv = ByteArray(16)
secureRandom.nextBytes(iv)
val ivHex = iv.toHex()
android.util.Log.d("MessageCrypto", " ✓ IV: $ivHex")
// ⚠️ КРИТИЧНО: Эмулируем поведение React Native + crypto-js!
// React Native: Buffer.toString('binary') → строка с символами (включая > 127)
// crypto-js: AES.encrypt(string, ...) → кодирует строку в UTF-8 перед шифрованием
// Итого: байты > 127 превращаются в многобайтовые UTF-8 последовательности
android.util.Log.d("MessageCrypto", "\n📍 Step 5: Latin1 → UTF-8 (crypto-js compatibility)")
android.util.Log.d("MessageCrypto", " • Input key+nonce bytes: ${keyAndNonce.size}")
android.util.Log.d("MessageCrypto", " • Input hex: ${keyAndNonce.toHex()}")
// Шаг 1: Байты → Latin1 строка (как Buffer.toString('binary'))
val latin1String = String(keyAndNonce, Charsets.ISO_8859_1)
android.util.Log.d("MessageCrypto", " • Latin1 string length: ${latin1String.length} chars")
// Шаг 2: Latin1 строка → UTF-8 байты (как crypto-js делает внутри)
val utf8Bytes = latin1String.toByteArray(Charsets.UTF_8)
android.util.Log.d("MessageCrypto", " ✓ UTF-8 bytes length: ${utf8Bytes.size}")
android.util.Log.d("MessageCrypto", " ✓ UTF-8 hex: ${utf8Bytes.toHex()}")
// AES шифрование
android.util.Log.d("MessageCrypto", "\n📍 Step 6: AES-CBC encryption")
android.util.Log.d("MessageCrypto", " • AES key (shared secret): ${sharedSecret.size} bytes")
android.util.Log.d("MessageCrypto", " • IV: ${iv.size} bytes")
android.util.Log.d("MessageCrypto", " • Plaintext: ${utf8Bytes.size} bytes")
val aesKey = SecretKeySpec(sharedSecret, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
@@ -407,19 +368,11 @@ object MessageCrypto {
val encryptedKey = cipher.doFinal(utf8Bytes)
val encryptedKeyHex = encryptedKey.toHex()
android.util.Log.d("MessageCrypto", " ✓ CIPHERTEXT: $encryptedKeyHex")
android.util.Log.d("MessageCrypto", " ✓ Ciphertext length: ${encryptedKey.size} bytes")
// Формат как в RN: btoa(ivHex:encryptedHex:ephemeralPrivateHex)
android.util.Log.d("MessageCrypto", "\n📍 Step 7: Format as iv:ciphertext:ephemeralPrivate")
val combined = "$ivHex:$encryptedKeyHex:$ephemeralPrivateKeyHex"
android.util.Log.d("MessageCrypto", " • Combined string: ${combined.take(160)}...")
android.util.Log.d("MessageCrypto", " • Combined length: ${combined.length} chars")
val result = Base64.encodeToString(combined.toByteArray(), Base64.NO_WRAP)
android.util.Log.d("MessageCrypto", "\n ✅ FINAL ENCRYPTED KEY (Base64): $result")
android.util.Log.d("MessageCrypto", " ✅ Base64 length: ${result.length} chars")
android.util.Log.d("MessageCrypto", "".repeat(80) + "\n")
return result
}
@@ -430,111 +383,68 @@ object MessageCrypto {
* КРИТИЧНО: ephemeralPrivateKeyHex может иметь нечётную длину!
*/
fun decryptKeyFromSender(encryptedKeyBase64: String, myPrivateKeyHex: String): ByteArray {
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "🔓 ECDH DECRYPT KEY FROM SENDER")
android.util.Log.d("MessageCrypto", "".repeat(80))
android.util.Log.d("MessageCrypto", "📥 Encrypted key (Base64): $encryptedKeyBase64")
android.util.Log.d("MessageCrypto", "📥 Base64 length: ${encryptedKeyBase64.length} chars")
android.util.Log.d("MessageCrypto", "🔑 My private key: $myPrivateKeyHex")
android.util.Log.d("MessageCrypto", "\n📍 Step 1: Decode Base64 and parse format")
val combined = String(Base64.decode(encryptedKeyBase64, Base64.NO_WRAP))
android.util.Log.d("MessageCrypto", " • Decoded string: ${combined.take(160)}...")
android.util.Log.d("MessageCrypto", " • Decoded length: ${combined.length} chars")
val parts = combined.split(":")
if (parts.size != 3) {
android.util.Log.e("MessageCrypto", "❌ Invalid format: expected 3 parts, got ${parts.size}")
throw IllegalArgumentException("Invalid encrypted key format: expected 3 parts, got ${parts.size}")
}
android.util.Log.d("MessageCrypto", " ✓ Parsed into 3 parts")
val ivHex = parts[0]
val encryptedKeyHex = parts[1]
var ephemeralPrivateKeyHex = parts[2]
android.util.Log.d("MessageCrypto", " • Part 1 (IV): $ivHex (${ivHex.length} chars)")
android.util.Log.d("MessageCrypto", " • Part 2 (ciphertext): ${encryptedKeyHex.take(80)}... (${encryptedKeyHex.length} chars)")
android.util.Log.d("MessageCrypto", " • Part 3 (ephemeral private): $ephemeralPrivateKeyHex")
// ⚠️ КРИТИЧНО: JS toString(16) может вернуть hex нечётной длины!
// Добавляем ведущий 0 если нужно для правильного парсинга
if (ephemeralPrivateKeyHex.length % 2 != 0) {
android.util.Log.d("MessageCrypto", " ⚠️ Padding ephemeral key from ${ephemeralPrivateKeyHex.length} to ${ephemeralPrivateKeyHex.length + 1}")
ephemeralPrivateKeyHex = "0$ephemeralPrivateKeyHex"
}
val iv = ivHex.hexToBytes()
val encryptedKey = encryptedKeyHex.hexToBytes()
android.util.Log.d("MessageCrypto", " ✓ IV bytes: ${iv.size}")
android.util.Log.d("MessageCrypto", " ✓ Ciphertext bytes: ${encryptedKey.size}")
val ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1")
// Парсим эфемерный приватный ключ
android.util.Log.d("MessageCrypto", "\n📍 Step 2: Parse ephemeral key pair")
val ephemeralPrivateKey = BigInteger(ephemeralPrivateKeyHex, 16)
val ephemeralPublicKey = ecSpec.g.multiply(ephemeralPrivateKey)
val ephemeralPublicKeyHex = ephemeralPublicKey.getEncoded(false).toHex()
android.util.Log.d("MessageCrypto", " ✓ Ephemeral private: $ephemeralPrivateKeyHex")
android.util.Log.d("MessageCrypto", " ✓ Ephemeral public: $ephemeralPublicKeyHex")
// Парсим мой приватный ключ
android.util.Log.d("MessageCrypto", "\n📍 Step 3: Parse my key pair")
val myPrivateKey = BigInteger(myPrivateKeyHex, 16)
val myPublicKey = ecSpec.g.multiply(myPrivateKey)
val myPublicKeyHex = myPublicKey.getEncoded(false).toHex()
android.util.Log.d("MessageCrypto", " ✓ My private: ${myPrivateKeyHex.take(32)}...")
android.util.Log.d("MessageCrypto", " ✓ My public: $myPublicKeyHex")
// ECDH: ephemeralPrivate * myPublic = sharedSecret
android.util.Log.d("MessageCrypto", "\n📍 Step 4: Compute ECDH shared secret")
android.util.Log.d("MessageCrypto", " • Computing: ephemeral_private × my_public")
val sharedPoint = myPublicKey.multiply(ephemeralPrivateKey)
// ⚠️ КРИТИЧНО: Эмулируем JS поведение!
// JS: BN.toString(16) НЕ добавляет ведущие нули
val xCoordBigInt = sharedPoint.normalize().xCoord.toBigInteger()
android.util.Log.d("MessageCrypto", " • X coordinate (BigInt): $xCoordBigInt")
var sharedSecretHex = xCoordBigInt.toString(16)
android.util.Log.d("MessageCrypto", " • toString(16) result: $sharedSecretHex (${sharedSecretHex.length} chars)")
if (sharedSecretHex.length % 2 != 0) {
android.util.Log.d("MessageCrypto", " ⚠️ Padding to even length")
sharedSecretHex = "0$sharedSecretHex"
}
val sharedSecret = sharedSecretHex.hexToBytes()
android.util.Log.d("MessageCrypto", " ✓ SHARED SECRET hex: $sharedSecretHex")
android.util.Log.d("MessageCrypto", " ✓ Shared secret bytes: ${sharedSecret.size} bytes")
// Расшифровываем используя sharedSecret как AES ключ
android.util.Log.d("MessageCrypto", "\n📍 Step 5: AES-CBC decryption")
android.util.Log.d("MessageCrypto", " • AES key (shared secret): ${sharedSecret.size} bytes")
android.util.Log.d("MessageCrypto", " • IV: ${iv.size} bytes")
android.util.Log.d("MessageCrypto", " • Ciphertext: ${encryptedKey.size} bytes")
val aesKey = SecretKeySpec(sharedSecret, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, aesKey, IvParameterSpec(iv))
val decryptedUtf8Bytes = cipher.doFinal(encryptedKey)
android.util.Log.d("MessageCrypto", " ✓ Decrypted UTF-8 bytes: ${decryptedUtf8Bytes.size}")
android.util.Log.d("MessageCrypto", " ✓ Decrypted hex: ${decryptedUtf8Bytes.toHex()}")
// ⚠️ КРИТИЧНО: Обратная конвертация UTF-8 → Latin1!
// Desktop: decrypted.toString(crypto.enc.Utf8) → Buffer.from(str, 'binary')
// Это декодирует UTF-8 в строку, потом берёт charCode каждого символа
android.util.Log.d("MessageCrypto", "\n📍 Step 6: UTF-8 → Latin1 (crypto-js compatibility)")
val utf8String = String(decryptedUtf8Bytes, Charsets.UTF_8)
android.util.Log.d("MessageCrypto", " • UTF-8 string length: ${utf8String.length} chars")
val originalBytes = utf8String.toByteArray(Charsets.ISO_8859_1)
android.util.Log.d("MessageCrypto", " ✓ RESULT bytes: ${originalBytes.size}")
android.util.Log.d("MessageCrypto", " ✓ Result hex: ${originalBytes.toHex()}")
android.util.Log.d("MessageCrypto", "\n ✅ DECRYPTION COMPLETE")
android.util.Log.d("MessageCrypto", " ✅ Returned ${originalBytes.size} bytes")
android.util.Log.d("MessageCrypto", "".repeat(80) + "\n")
return originalBytes
}
@@ -552,51 +462,16 @@ object MessageCrypto {
* Полное шифрование сообщения для отправки
*/
fun encryptForSending(plaintext: String, recipientPublicKey: String): EncryptedForSending {
android.util.Log.d("MessageCrypto", "=".repeat(100))
android.util.Log.d("MessageCrypto", "🚀🚀🚀 START ENCRYPTION FOR SENDING 🚀🚀🚀")
android.util.Log.d("MessageCrypto", "=".repeat(100))
android.util.Log.d("MessageCrypto", "📝 PLAINTEXT: '$plaintext'")
android.util.Log.d("MessageCrypto", "📝 Plaintext length: ${plaintext.length} chars")
android.util.Log.d("MessageCrypto", "📝 Plaintext bytes: ${plaintext.toByteArray().size} bytes")
android.util.Log.d("MessageCrypto", "📝 Plaintext hex (first 128): ${plaintext.toByteArray().take(64).toByteArray().toHex()}")
android.util.Log.d("MessageCrypto", "🔑 RECIPIENT PUBLIC KEY: $recipientPublicKey")
android.util.Log.d("MessageCrypto", "🔑 Public key length: ${recipientPublicKey.length} chars")
// 1. Шифруем текст
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "⚡ STEP 1: XCHACHA20-POLY1305 ENCRYPTION")
android.util.Log.d("MessageCrypto", "".repeat(80))
val encrypted = encryptMessage(plaintext)
android.util.Log.d("MessageCrypto", "✅ CIPHERTEXT (hex): ${encrypted.ciphertext}")
android.util.Log.d("MessageCrypto", "✅ Ciphertext length: ${encrypted.ciphertext.length} chars")
android.util.Log.d("MessageCrypto", "✅ KEY (hex): ${encrypted.key}")
android.util.Log.d("MessageCrypto", "✅ Key length: ${encrypted.key.length} chars (should be 64)")
android.util.Log.d("MessageCrypto", "✅ NONCE (hex): ${encrypted.nonce}")
android.util.Log.d("MessageCrypto", "✅ Nonce length: ${encrypted.nonce.length} chars (should be 48)")
// 2. Собираем key + nonce
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "⚡ STEP 2: COMBINE KEY + NONCE")
android.util.Log.d("MessageCrypto", "".repeat(80))
val keyAndNonce = encrypted.key.hexToBytes() + encrypted.nonce.hexToBytes()
android.util.Log.d("MessageCrypto", "✅ KEY+NONCE combined: ${keyAndNonce.size} bytes (should be 56)")
android.util.Log.d("MessageCrypto", "✅ Combined hex: ${keyAndNonce.toHex()}")
// 3. Шифруем ключ для получателя
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "⚡ STEP 3: ECDH + AES ENCRYPTION OF KEY")
android.util.Log.d("MessageCrypto", "".repeat(80))
val encryptedKey = encryptKeyForRecipient(keyAndNonce, recipientPublicKey)
android.util.Log.d("MessageCrypto", "✅ ENCRYPTED KEY (Base64): $encryptedKey")
android.util.Log.d("MessageCrypto", "✅ Encrypted key length: ${encryptedKey.length} chars")
android.util.Log.d("MessageCrypto", "\n" + "=".repeat(100))
android.util.Log.d("MessageCrypto", "✅✅✅ ENCRYPTION COMPLETE ✅✅✅")
android.util.Log.d("MessageCrypto", "=".repeat(100))
android.util.Log.d("MessageCrypto", "FINAL OUTPUTS:")
android.util.Log.d("MessageCrypto", " • Ciphertext: ${encrypted.ciphertext.take(60)}... (${encrypted.ciphertext.length} chars)")
android.util.Log.d("MessageCrypto", " • Encrypted key: ${encryptedKey.take(60)}... (${encryptedKey.length} chars)")
android.util.Log.d("MessageCrypto", "=".repeat(100) + "\n")
return EncryptedForSending(encrypted.ciphertext, encryptedKey, keyAndNonce)
}
@@ -610,48 +485,17 @@ object MessageCrypto {
encryptedKey: String,
myPrivateKey: String
): DecryptedIncoming {
android.util.Log.d("MessageCrypto", "=".repeat(100))
android.util.Log.d("MessageCrypto", "🔓🔓🔓 START DECRYPTION OF INCOMING MESSAGE 🔓🔓🔓")
android.util.Log.d("MessageCrypto", "=".repeat(100))
android.util.Log.d("MessageCrypto", "📩 CIPHERTEXT (hex): ${ciphertext.take(100)}...")
android.util.Log.d("MessageCrypto", "📩 Ciphertext length: ${ciphertext.length} chars")
android.util.Log.d("MessageCrypto", "🔐 ENCRYPTED KEY: ${encryptedKey.take(100)}...")
android.util.Log.d("MessageCrypto", "🔐 Encrypted key length: ${encryptedKey.length} chars")
android.util.Log.d("MessageCrypto", "🔑 MY PRIVATE KEY: ${myPrivateKey.take(32)}... (${myPrivateKey.length} chars)")
// 1. Расшифровываем ключ
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "⚡ STEP 1: ECDH + AES DECRYPTION OF KEY")
android.util.Log.d("MessageCrypto", "".repeat(80))
val keyAndNonce = decryptKeyFromSender(encryptedKey, myPrivateKey)
android.util.Log.d("MessageCrypto", "✅ DECRYPTED KEY+NONCE: ${keyAndNonce.size} bytes (should be 56)")
android.util.Log.d("MessageCrypto", "✅ Key+Nonce hex: ${keyAndNonce.toHex()}")
// 2. Разделяем key и nonce
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "⚡ STEP 2: SPLIT KEY AND NONCE")
android.util.Log.d("MessageCrypto", "".repeat(80))
val key = keyAndNonce.slice(0 until 32).toByteArray()
val nonce = keyAndNonce.slice(32 until keyAndNonce.size).toByteArray()
android.util.Log.d("MessageCrypto", "✅ KEY (32 bytes): ${key.toHex()}")
android.util.Log.d("MessageCrypto", "✅ NONCE (24 bytes): ${nonce.toHex()}")
android.util.Log.d("MessageCrypto", "✅ Key length: ${key.size} bytes")
android.util.Log.d("MessageCrypto", "✅ Nonce length: ${nonce.size} bytes")
// 3. Расшифровываем сообщение
android.util.Log.d("MessageCrypto", "\n" + "".repeat(80))
android.util.Log.d("MessageCrypto", "⚡ STEP 3: XCHACHA20-POLY1305 DECRYPTION")
android.util.Log.d("MessageCrypto", "".repeat(80))
val plaintext = decryptMessage(ciphertext, key.toHex(), nonce.toHex())
android.util.Log.d("MessageCrypto", "✅ PLAINTEXT: '$plaintext'")
android.util.Log.d("MessageCrypto", "✅ Plaintext length: ${plaintext.length} chars")
android.util.Log.d("MessageCrypto", "✅ Plaintext bytes: ${plaintext.toByteArray().size} bytes")
android.util.Log.d("MessageCrypto", "\n" + "=".repeat(100))
android.util.Log.d("MessageCrypto", "✅✅✅ DECRYPTION COMPLETE ✅✅✅")
android.util.Log.d("MessageCrypto", "=".repeat(100))
android.util.Log.d("MessageCrypto", "FINAL OUTPUT: '$plaintext'")
android.util.Log.d("MessageCrypto", "=".repeat(100) + "\n")
return DecryptedIncoming(plaintext, keyAndNonce)
}
@@ -690,7 +534,6 @@ object MessageCrypto {
// 4. Расшифровываем AES-256-CBC
decryptWithPBKDF2Key(encryptedData, pbkdf2Key)
} catch (e: Exception) {
android.util.Log.e("MessageCrypto", "❌ Failed to decrypt attachment blob", e)
null
}
}
@@ -718,7 +561,6 @@ object MessageCrypto {
return try {
val parts = encryptedData.split(":")
if (parts.size != 2) {
android.util.Log.e("MessageCrypto", "Invalid encrypted data format")
return null
}
@@ -745,7 +587,6 @@ object MessageCrypto {
String(outputStream.toByteArray(), Charsets.UTF_8)
} catch (e: Exception) {
android.util.Log.e("MessageCrypto", "❌ Failed to decrypt with PBKDF2 key", e)
null
}
}
@@ -765,15 +606,10 @@ object MessageCrypto {
*/
fun encryptReplyBlob(replyJson: String, plainKeyAndNonce: ByteArray): String {
return try {
android.util.Log.d("MessageCrypto", "🔐 Encrypting reply blob...")
android.util.Log.d("MessageCrypto", " - ReplyJson length: ${replyJson.length}")
android.util.Log.d("MessageCrypto", " - PlainKeyAndNonce length: ${plainKeyAndNonce.size}")
// Convert keyAndNonce to string - simulate JS Buffer.toString('utf-8') behavior
// which replaces invalid UTF-8 sequences with U+FFFD
val password = bytesToJsUtf8String(plainKeyAndNonce)
android.util.Log.d("MessageCrypto", " - Password length: ${password.length}")
android.util.Log.d("MessageCrypto", " - Password char codes: ${password.take(5).map { it.code }}")
// Compress with pako (deflate)
val deflater = java.util.zip.Deflater()
@@ -783,7 +619,6 @@ object MessageCrypto {
val compressedSize = deflater.deflate(compressedBuffer)
deflater.end()
val compressed = compressedBuffer.copyOf(compressedSize)
android.util.Log.d("MessageCrypto", " - Compressed size: ${compressed.size}")
// PBKDF2 key derivation (matching RN: crypto.PBKDF2(password, 'rosetta', {keySize: 256/32, iterations: 1000}))
val factory = javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
@@ -795,12 +630,10 @@ object MessageCrypto {
)
val secretKey = factory.generateSecret(spec)
val keyBytes = secretKey.encoded
android.util.Log.d("MessageCrypto", " - PBKDF2 key derived: ${keyBytes.toHex()}")
// Generate random IV (16 bytes)
val iv = ByteArray(16)
java.security.SecureRandom().nextBytes(iv)
android.util.Log.d("MessageCrypto", " - IV generated: ${iv.size} bytes")
// AES-CBC encryption
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
@@ -808,17 +641,14 @@ object MessageCrypto {
val ivSpec = IvParameterSpec(iv)
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)
val ciphertext = cipher.doFinal(compressed)
android.util.Log.d("MessageCrypto", " - Ciphertext size: ${ciphertext.size}")
// Format: "ivBase64:ciphertextBase64" (same as RN new format)
val ivBase64 = Base64.encodeToString(iv, Base64.NO_WRAP)
val ctBase64 = Base64.encodeToString(ciphertext, Base64.NO_WRAP)
val result = "$ivBase64:$ctBase64"
android.util.Log.d("MessageCrypto", " ✅ Reply blob encrypted: ${result.take(50)}...")
result
} catch (e: Exception) {
android.util.Log.e("MessageCrypto", "❌ Failed to encrypt reply blob", e)
// Fallback: return plaintext (for backwards compatibility)
replyJson
}
@@ -849,31 +679,23 @@ object MessageCrypto {
*/
fun decryptReplyBlob(encryptedBlob: String, plainKeyAndNonce: ByteArray): String {
return try {
android.util.Log.d("MessageCrypto", "🔓 Decrypting reply blob...")
android.util.Log.d("MessageCrypto", " - EncryptedBlob length: ${encryptedBlob.length}")
android.util.Log.d("MessageCrypto", " - PlainKeyAndNonce length: ${plainKeyAndNonce.size}")
// Check if it's encrypted format (contains ':')
if (!encryptedBlob.contains(':')) {
android.util.Log.d("MessageCrypto", " - Plain JSON detected, returning as-is")
return encryptedBlob
}
// Parse ivBase64:ciphertextBase64
val parts = encryptedBlob.split(':')
if (parts.size != 2) {
android.util.Log.e("MessageCrypto", " - Invalid format, expected iv:ciphertext")
return encryptedBlob
}
val iv = Base64.decode(parts[0], Base64.DEFAULT)
val ciphertext = Base64.decode(parts[1], Base64.DEFAULT)
android.util.Log.d("MessageCrypto", " - IV size: ${iv.size}, Ciphertext size: ${ciphertext.size}")
// Password from keyAndNonce - use same JS-like UTF-8 conversion
val password = bytesToJsUtf8String(plainKeyAndNonce)
android.util.Log.d("MessageCrypto", " - Password length: ${password.length}")
android.util.Log.d("MessageCrypto", " - Password char codes: ${password.take(5).map { it.code }}")
// PBKDF2 key derivation
val factory = javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
@@ -885,7 +707,6 @@ object MessageCrypto {
)
val secretKey = factory.generateSecret(spec)
val keyBytes = secretKey.encoded
android.util.Log.d("MessageCrypto", " - PBKDF2 key derived: ${keyBytes.toHex()}")
// AES-CBC decryption
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
@@ -902,10 +723,8 @@ object MessageCrypto {
inflater.end()
val plaintext = String(outputBuffer, 0, outputSize, Charsets.UTF_8)
android.util.Log.d("MessageCrypto", " ✅ Reply blob decrypted: ${plaintext.take(50)}...")
plaintext
} catch (e: Exception) {
android.util.Log.e("MessageCrypto", "❌ Failed to decrypt reply blob: ${e.message}", e)
// Return as-is, might be plain JSON
encryptedBlob
}