diff --git a/app/src/main/java/com/rosetta/messenger/crypto/MessageCrypto.kt b/app/src/main/java/com/rosetta/messenger/crypto/MessageCrypto.kt index eaf2135..77683bf 100644 --- a/app/src/main/java/com/rosetta/messenger/crypto/MessageCrypto.kt +++ b/app/src/main/java/com/rosetta/messenger/crypto/MessageCrypto.kt @@ -303,12 +303,22 @@ object MessageCrypto { secureRandom.nextBytes(iv) val ivHex = iv.toHex() - // Шифруем keyAndNonce напрямую с AES-CBC используя sharedSecret как ключ - // React Native теперь использует crypto.enc.Latin1 для binary data + // КРИТИЧНО: Эмулируем поведение crypto-js! + // React Native делает: key.toString('binary') → crypto.AES.encrypt(string, ...) + // crypto-js интерпретирует string как UTF-8! + // Поэтому: ByteArray → Latin1 String → UTF-8 bytes → encrypt + val latin1String = String(keyAndNonce, Charsets.ISO_8859_1) + val utf8Bytes = latin1String.toByteArray(Charsets.UTF_8) + + android.util.Log.d("MessageCrypto", "📝 Key encoding:") + android.util.Log.d("MessageCrypto", " - Original bytes: ${keyAndNonce.size}") + android.util.Log.d("MessageCrypto", " - Latin1 string chars: ${latin1String.length}") + android.util.Log.d("MessageCrypto", " - UTF-8 bytes: ${utf8Bytes.size}") + val aesKey = SecretKeySpec(sharedSecret, "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.ENCRYPT_MODE, aesKey, IvParameterSpec(iv)) - val encryptedKey = cipher.doFinal(keyAndNonce) + val encryptedKey = cipher.doFinal(utf8Bytes) val encryptedKeyHex = encryptedKey.toHex() // Формат как в RN: btoa(ivHex:encryptedHex:ephemeralPrivateHex) @@ -358,7 +368,21 @@ object MessageCrypto { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.DECRYPT_MODE, aesKey, IvParameterSpec(iv)) - return cipher.doFinal(encryptedKey) + val decryptedUtf8Bytes = cipher.doFinal(encryptedKey) + + // КРИТИЧНО: Обратная конвертация как в crypto-js! + // crypto-js делает: decrypt → WordArray → .toString(Utf8) → string + // Потом: Buffer.from(string, 'binary') → bytes + // Эквивалент: UTF-8 bytes → UTF-8 string → Latin1 bytes + val utf8String = String(decryptedUtf8Bytes, Charsets.UTF_8) + val originalBytes = utf8String.toByteArray(Charsets.ISO_8859_1) + + android.util.Log.d("MessageCrypto", "📝 Key decoding:") + android.util.Log.d("MessageCrypto", " - Decrypted UTF-8 bytes: ${decryptedUtf8Bytes.size}") + android.util.Log.d("MessageCrypto", " - UTF-8 string chars: ${utf8String.length}") + android.util.Log.d("MessageCrypto", " - Original bytes: ${originalBytes.size}") + + return originalBytes } /**