{"id":251,"date":"2026-10-23T17:03:00","date_gmt":"2026-10-23T17:03:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=251"},"modified":"2026-11-06T08:48:15","modified_gmt":"2026-11-06T08:48:15","slug":"android-app-security-best-practices-with-kotlin-keystore-encrypted-storage-network-security","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/android-app-security-best-practices-with-kotlin-keystore-encrypted-storage-network-security\/","title":{"rendered":"Android App Security Best Practices with Kotlin: Keystore, Encrypted Storage &#038; Network Security"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Security is a critical part of modern Android application development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Mobile applications frequently handle sensitive information, including authentication tokens, personal information, payment-related data, private documents, and user-generated content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If this information is stored or transmitted insecurely, attackers may be able to access or manipulate it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Android provides multiple security mechanisms to help developers protect application data and reduce common vulnerabilities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These include <strong>Android Keystore, application sandboxing, cryptographic APIs, HTTPS, Network Security Configuration, runtime permissions, and secure authentication patterns<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll explore Android app security best practices using Kotlin and modern Android development techniques.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also build a practical encrypted notes example using Android Keystore and AES-GCM encryption.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Why Android Application Security Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Mobile applications operate in environments that developers do not fully control.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Devices may be lost, compromised, rooted, or connected to untrusted networks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Attackers may attempt to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Extract sensitive application data.<\/li>\n\n\n\n<li>Intercept network communications.<\/li>\n\n\n\n<li>Reverse-engineer application packages.<\/li>\n\n\n\n<li>Steal authentication tokens.<\/li>\n\n\n\n<li>Exploit exported Android components.<\/li>\n\n\n\n<li>Manipulate locally stored information.<\/li>\n\n\n\n<li>Abuse insecure deep links.<\/li>\n\n\n\n<li>Access improperly protected files.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A secure Android application should protect sensitive data throughout its lifecycle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Three Important Security Goals<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Goal<\/th><th>Description<\/th><\/tr><tr><td>Confidentiality<\/td><td>Prevent unauthorized access to information<\/td><\/tr><tr><td>Integrity<\/td><td>Prevent unauthorized modification of information<\/td><\/tr><tr><td>Availability<\/td><td>Keep legitimate functionality accessible<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Security requires multiple layers of protection rather than relying on a single library or API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Understand Android&#8217;s Security Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android includes several platform-level security mechanisms.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Application Sandboxing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each Android application normally runs under its own Linux application identity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This helps isolate application data and processes from other applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Permission System<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android permissions control access to protected capabilities and information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include camera access, microphone access, and location access.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Application Signing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android uses application signing to establish update identity and package authenticity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Android Keystore<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android Keystore provides a mechanism for generating and using cryptographic keys while limiting access to their key material.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Network Security<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android supports TLS, Network Security Configuration, and certificate validation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Simplified Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Android Application\n        |\n        +-- Application Sandbox\n        |\n        +-- Runtime Permissions\n        |\n        +-- Android Keystore\n        |\n        +-- Encrypted Data Storage\n        |\n        +-- HTTPS \/ TLS\n        |\n        +-- Secure Authentication<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These protections work together.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, they do not automatically prevent vulnerabilities introduced by application code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">3. Follow the Principle of Least Privilege<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The principle of least privilege means granting access only to the resources required for a specific feature.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a photo editing application may need access to selected images.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not necessarily need unrestricted access to the entire media library.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Request only necessary permissions.<\/li>\n\n\n\n<li>Prefer system pickers where appropriate.<\/li>\n\n\n\n<li>Avoid unnecessary exported components.<\/li>\n\n\n\n<li>Restrict sensitive APIs.<\/li>\n\n\n\n<li>Remove unused permissions.<\/li>\n\n\n\n<li>Review third-party SDK permissions.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Android Photo Picker<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For applications that need users to select photos, Android Photo Picker can provide access to selected media without requiring broad media library permissions in many scenarios.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This reduces unnecessary data exposure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Principle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The fewer permissions and privileges an application requires, the smaller its potential attack surface.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">4. Understand Android Keystore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android Keystore is a system service that supports secure cryptographic key management.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Applications can generate and use cryptographic keys through the Android Keystore APIs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Depending on the device and key configuration, keys may be protected by hardware-backed security components.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Key material can remain non-exportable through supported APIs.<\/li>\n\n\n\n<li>Keys can be restricted to specific cryptographic purposes.<\/li>\n\n\n\n<li>Keys can have authentication requirements.<\/li>\n\n\n\n<li>Some devices provide hardware-backed key protection.<\/li>\n\n\n\n<li>Applications can use standard Java Cryptography Architecture APIs.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Simplified Flow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Android Application\n        |\n        v\nAndroid Keystore\n        |\n        v\nCryptographic Key\n        |\n        v\nEncrypt \/ Decrypt\n        |\n        v\nProtected Application Data<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Limitation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android Keystore does not make a compromised application process completely secure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If malicious code executes with the application&#8217;s privileges, it may be able to request permitted cryptographic operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keystore protects key material and enforces supported key-use restrictions; it is not a complete defense against runtime compromise.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">5. Generate an AES Key with Android Keystore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create an AES key suitable for encrypting application data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll use AES-GCM, an authenticated encryption mode.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Kotlin Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class SecureKeyManager {\n\n    companion object {\n        private const val KEY_ALIAS =\n            \"moiks_secure_notes_key\"\n\n        private const val ANDROID_KEYSTORE =\n            \"AndroidKeyStore\"\n    }\n\n    fun getOrCreateKey(): SecretKey {\n\n        val keyStore = KeyStore.getInstance(\n            ANDROID_KEYSTORE\n        ).apply {\n            load(null)\n        }\n\n        val existingKey = keyStore.getKey(\n            KEY_ALIAS,\n            null\n        ) as? SecretKey\n\n        if (existingKey != null) {\n            return existingKey\n        }\n\n        val keyGenerator =\n            KeyGenerator.getInstance(\n                KeyProperties.KEY_ALGORITHM_AES,\n                ANDROID_KEYSTORE\n            )\n\n        val specification =\n            KeyGenParameterSpec.Builder(\n                KEY_ALIAS,\n                KeyProperties.PURPOSE_ENCRYPT or\n                    KeyProperties.PURPOSE_DECRYPT\n            )\n                .setBlockModes(\n                    KeyProperties.BLOCK_MODE_GCM\n                )\n                .setEncryptionPaddings(\n                    KeyProperties.ENCRYPTION_PADDING_NONE\n                )\n                .setKeySize(256)\n                .build()\n\n        keyGenerator.init(specification)\n\n        return keyGenerator.generateKey()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">How It Works<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The code first checks whether a key already exists.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a suitable key is found, it returns that key.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Otherwise, it generates a new AES key in Android Keystore.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Considerations<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The example targets Android API 23 and above.<\/li>\n\n\n\n<li>AES-256 support should be verified for the intended devices and provider configuration.<\/li>\n\n\n\n<li>Some keys may be hardware-backed, while others may use software protection.<\/li>\n\n\n\n<li>This example does not require biometric authentication.<\/li>\n\n\n\n<li>Real applications must handle key invalidation and unrecoverable key scenarios.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">6. Why AES-GCM Is Recommended<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">AES is a widely used symmetric encryption algorithm.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">GCM is an authenticated encryption mode that provides both confidentiality and integrity protection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">AES-GCM Provides<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Encryption of plaintext.<\/li>\n\n\n\n<li>Authentication of encrypted data.<\/li>\n\n\n\n<li>Detection of unauthorized ciphertext modification.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Simplified Encryption Flow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Plaintext\n    |\n    v\nAES-GCM Encryption\n    |\n    +-- Secret Key\n    |\n    +-- Unique IV\n    |\n    v\nCiphertext + Authentication Tag<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Rule<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Never reuse the same initialization vector (IV) with the same AES-GCM key.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For encryption using Android Keystore, allow the cryptographic provider to generate an appropriate IV and store it alongside the ciphertext.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The IV is not a secret.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">7. Encrypt Data Using AES-GCM<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a class responsible for encryption.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class SecureEncryptionManager(\n    private val keyManager: SecureKeyManager\n) {\n\n    fun encrypt(plainText: String): String {\n\n        val secretKey =\n            keyManager.getOrCreateKey()\n\n        val cipher = Cipher.getInstance(\n            \"AES\/GCM\/NoPadding\"\n        )\n\n        cipher.init(\n            Cipher.ENCRYPT_MODE,\n            secretKey\n        )\n\n        val encryptedBytes =\n            cipher.doFinal(\n                plainText.toByteArray(\n                    Charsets.UTF_8\n                )\n            )\n\n        val iv = cipher.iv\n\n        val output = ByteBuffer.allocate(\n            1 + 4 + iv.size + encryptedBytes.size\n        ).apply {\n            put(1.toByte())\n            putInt(iv.size)\n            put(iv)\n            put(encryptedBytes)\n        }.array()\n\n        return Base64.encodeToString(\n            output,\n            Base64.NO_WRAP\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">What Gets Stored?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The encrypted result contains:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>A format version.<\/li>\n\n\n\n<li>The IV length.<\/li>\n\n\n\n<li>The IV.<\/li>\n\n\n\n<li>The ciphertext, including the GCM authentication tag.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Why Store a Version?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Versioning allows the application to evolve its encrypted data format later.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a future version may use different metadata or key-management rules.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">8. Decrypt Data Using AES-GCM<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now add a decryption function to the same class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fun decrypt(encryptedText: String): String {\n\n    val data = Base64.decode(\n        encryptedText,\n        Base64.NO_WRAP\n    )\n\n    val buffer = ByteBuffer.wrap(data)\n\n    require(buffer.remaining() &gt;= 5) {\n        \"Invalid encrypted data\"\n    }\n\n    val version = buffer.get().toInt()\n\n    require(version == 1) {\n        \"Unsupported encryption version\"\n    }\n\n    val ivLength = buffer.int\n\n    require(ivLength == 12) {\n        \"Invalid IV length\"\n    }\n\n    require(buffer.remaining() &gt;= ivLength + 16) {\n        \"Invalid encrypted payload\"\n    }\n\n    val iv = ByteArray(ivLength)\n    buffer.get(iv)\n\n    val ciphertext =\n        ByteArray(buffer.remaining())\n\n    buffer.get(ciphertext)\n\n    val cipher = Cipher.getInstance(\n        \"AES\/GCM\/NoPadding\"\n    )\n\n    cipher.init(\n        Cipher.DECRYPT_MODE,\n        keyManager.getOrCreateKey(),\n        GCMParameterSpec(\n            128,\n            iv\n        )\n    )\n\n    val plainBytes =\n        cipher.doFinal(ciphertext)\n\n    return String(\n        plainBytes,\n        Charsets.UTF_8\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This method belongs inside <code>SecureEncryptionManager<\/code> from the previous section.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Security Behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If ciphertext or its authentication tag has been modified, decryption fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Applications should catch the relevant cryptographic exceptions at the repository boundary and handle them without exposing sensitive internal details.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Considerations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The example is designed to explain the cryptographic workflow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A production implementation should also define:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Maximum accepted payload sizes.<\/li>\n\n\n\n<li>Data format migration rules.<\/li>\n\n\n\n<li>Key loss recovery.<\/li>\n\n\n\n<li>Backup and restore behavior.<\/li>\n\n\n\n<li>Key rotation.<\/li>\n\n\n\n<li>Secure error handling.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Never display cryptographic keys or decrypted secrets in application logs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">9. Secure Storage vs Plain SharedPreferences<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedPreferences is commonly used for lightweight application settings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, ordinary SharedPreferences does not automatically encrypt values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>preferences.edit()\n    .putString(\n        \"access_token\",\n        token\n    )\n    .apply()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This stores the token as an ordinary preference value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Application-private storage limits access from other ordinary sandboxed apps, but it should not be confused with encryption.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Better Approach<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For sensitive values requiring encryption at rest, use a carefully designed storage layer that encrypts data using keys managed through Android Keystore.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Note About EncryptedSharedPreferences<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">AndroidX Security Crypto APIs, including <code>EncryptedSharedPreferences<\/code>, have been deprecated in recent library releases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For new applications, review current Android guidance and consider direct Android Keystore integration or a maintained security solution that fits your threat model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid introducing deprecated dependencies into a new application without understanding their maintenance and migration implications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">10. Can DataStore Store Encrypted Data?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack DataStore is designed for asynchronous and transactional data storage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, standard Preferences DataStore does not automatically encrypt values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Jetpack Compose UI\n        |\n        v\nViewModel\n        |\n        v\nSecure Repository\n        |\n        +-- Android Keystore\n        |\n        +-- AES-GCM Encryption\n        |\n        v\nEncrypted Local Storage<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Encrypting individual DataStore values requires careful handling of serialization, key availability, migration, and error recovery.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For structured sensitive information, a database with a suitable encryption strategy may be more appropriate.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume that storing data in DataStore automatically makes it confidential.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">11. Understand Android Network Security<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Mobile applications regularly communicate with remote servers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Network communication may include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Authentication requests.<\/li>\n\n\n\n<li>User profile updates.<\/li>\n\n\n\n<li>File uploads.<\/li>\n\n\n\n<li>Payment-related operations.<\/li>\n\n\n\n<li>Application configuration.<\/li>\n\n\n\n<li>Cloud synchronization.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">These operations must be protected against interception and manipulation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Use HTTPS<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">HTTPS uses TLS to protect communication between the application and server.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It helps provide:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Confidentiality.<\/li>\n\n\n\n<li>Integrity.<\/li>\n\n\n\n<li>Server authentication.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use HTTPS for production API endpoints.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not disable TLS certificate validation to make development easier.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">12. Configure Network Security Configuration<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android supports declarative network security rules.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>res\/xml\/network_security_config.xml<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;network-security-config&gt;\n\n    &lt;base-config cleartextTrafficPermitted=\"false\"&gt;\n\n        &lt;trust-anchors&gt;\n            &lt;certificates src=\"system\" \/&gt;\n        &lt;\/trust-anchors&gt;\n\n    &lt;\/base-config&gt;\n\n&lt;\/network-security-config&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Reference the file in <code>AndroidManifest.xml<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;application\n    android:networkSecurityConfig=\"@xml\/network_security_config\"\n    android:usesCleartextTraffic=\"false\"\n    ... &gt;\n&lt;\/application&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">What This Configuration Does<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Disallows cleartext traffic for the configured base policy.<\/li>\n\n\n\n<li>Uses system certificate authorities for trust.<\/li>\n\n\n\n<li>Provides an explicit network security policy.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Network Security Configuration applies to supported Android networking stacks and APIs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Applications using custom native networking libraries must ensure that those libraries enforce equivalent protections.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">13. Avoid Trust-All Certificate Validation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A dangerous development shortcut is accepting every TLS certificate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Insecure Concept<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Server Certificate\n       |\n       v\nSkip Validation\n       |\n       v\nAccept Any Server<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This defeats server authentication and may expose traffic to man-in-the-middle attacks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Approach<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use proper certificate validation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For development environments with private certificate authorities, configure trust appropriately in a development-only configuration.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Never ship trust-all certificate logic in production.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">14. Understand Certificate Pinning<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Certificate pinning restricts which public keys or certificates are accepted for a particular server.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">OkHttp supports certificate pinning.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val certificatePinner =\n    CertificatePinner.Builder()\n        .add(\n            \"api.example.com\",\n            \"sha256\/REPLACE_WITH_REAL_PIN\"\n        )\n        .build()\n\nval client = OkHttpClient.Builder()\n    .certificatePinner(\n        certificatePinner\n    )\n    .build()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Warning<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The example uses a placeholder pin and must not be deployed unchanged.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Certificate pinning introduces operational risks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, certificate or key rotation can break application connectivity if backup pins and recovery strategies are not managed correctly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Android&#8217;s official guidance generally cautions against routine certificate pinning because of these risks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use pinning only when justified by the application&#8217;s threat model and operational capabilities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For many applications, standard TLS validation is the better choice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">15. Secure Authentication Tokens<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Authentication tokens are commonly used to authorize API requests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Access tokens.<\/li>\n\n\n\n<li>Refresh tokens.<\/li>\n\n\n\n<li>Session tokens.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">These values should be treated as sensitive.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Mistakes<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Logging tokens.<\/li>\n\n\n\n<li>Storing tokens in plaintext without considering the threat model.<\/li>\n\n\n\n<li>Embedding permanent secrets in application code.<\/li>\n\n\n\n<li>Including tokens in URLs.<\/li>\n\n\n\n<li>Sharing tokens with unrelated components.<\/li>\n\n\n\n<li>Failing to invalidate sessions.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use short-lived access tokens where appropriate.<\/li>\n\n\n\n<li>Protect refresh tokens carefully.<\/li>\n\n\n\n<li>Avoid token exposure in logs.<\/li>\n\n\n\n<li>Use HTTPS.<\/li>\n\n\n\n<li>Implement secure logout.<\/li>\n\n\n\n<li>Handle expired tokens correctly.<\/li>\n\n\n\n<li>Use server-side authorization checks.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important Principle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A mobile application is a public client.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume secrets embedded in an APK or AAB can remain confidential.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">16. Avoid Hardcoded API Secrets<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Consider this example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const val SECRET_API_KEY =\n    \"my_private_backend_secret\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Embedding a private backend credential in application code is insecure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Attackers can inspect application packages and potentially recover embedded values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Better Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Android Application\n        |\n        v\nAuthenticated Backend\n        |\n        v\nPrivate API Credentials\n        |\n        v\nThird-Party Service<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Keep genuinely private credentials on a trusted backend.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application should authenticate to the backend using an appropriate mechanism.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Some public API identifiers are designed to be embedded in mobile applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These are not necessarily secrets.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Restrict them using supported mechanisms such as package identity, signing certificate restrictions, quotas, and server-side authorization where applicable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">17. Secure Android Intents and Exported Components<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android applications communicate using Intents.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Activities, Services, and BroadcastReceivers can be exposed to other applications depending on their manifest configuration.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;activity\n    android:name=\".InternalSettingsActivity\"\n    android:exported=\"false\" \/&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This prevents ordinary external applications from directly launching the component through the exported-component mechanism.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Export only components that require external access.<\/li>\n\n\n\n<li>Validate incoming Intent data.<\/li>\n\n\n\n<li>Avoid trusting external extras.<\/li>\n\n\n\n<li>Protect sensitive exported components with permissions where appropriate.<\/li>\n\n\n\n<li>Review deep links and app links.<\/li>\n\n\n\n<li>Avoid exposing internal file paths.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important Consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Setting <code>android:exported=\"false\"<\/code> does not replace application-level authorization and input validation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">18. Secure Deep Links<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Deep links allow users to navigate directly into application content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, improperly validated deep links can create security vulnerabilities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>myapp:\/\/open?documentId=123<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">An attacker may attempt to modify parameters.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Validate input parameters.<\/li>\n\n\n\n<li>Verify authentication before displaying private content.<\/li>\n\n\n\n<li>Check authorization for requested resources.<\/li>\n\n\n\n<li>Avoid directly executing commands from deep-link values.<\/li>\n\n\n\n<li>Prefer verified Android App Links where appropriate.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Key Principle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A deep link is an entry point, not proof that the caller is trusted.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">19. Secure WebView Usage<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">WebView allows Android applications to display web content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, it requires careful configuration.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Load trusted HTTPS content.<\/li>\n\n\n\n<li>Disable JavaScript if not required.<\/li>\n\n\n\n<li>Avoid exposing unnecessary JavaScript interfaces.<\/li>\n\n\n\n<li>Restrict untrusted navigation.<\/li>\n\n\n\n<li>Avoid enabling unsafe file access.<\/li>\n\n\n\n<li>Keep WebView and application dependencies updated.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>webView.settings.javaScriptEnabled = false\n\nwebView.loadUrl(\n    \"https:\/\/example.com\"\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Warning<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">JavaScript interfaces can expose application functionality to web content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Only use them when necessary, with trusted content and carefully designed interfaces.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">20. Protect Sensitive Information in Logs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Application logs are useful during development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, logging sensitive information can expose private data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Avoid Logging<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Passwords.<\/li>\n\n\n\n<li>Authentication tokens.<\/li>\n\n\n\n<li>Private encryption keys.<\/li>\n\n\n\n<li>Personal documents.<\/li>\n\n\n\n<li>Payment credentials.<\/li>\n\n\n\n<li>Sensitive user information.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Insecure Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Log.d(\n    \"Authentication\",\n    \"Access token: $token\"\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Better Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Log.d(\n    \"Authentication\",\n    \"Authentication completed\"\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use structured logging with redaction where necessary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Review release logging behavior and third-party logging interceptors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">21. Use Biometric Authentication Appropriately<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android provides biometric authentication APIs for supported devices.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">BiometricPrompt can authenticate users using supported biometric methods and, depending on configuration, device credentials.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Use Cases<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Unlocking sensitive application features.<\/li>\n\n\n\n<li>Authorizing access to protected data.<\/li>\n\n\n\n<li>Confirming sensitive operations.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important Distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Biometric authentication alone does not automatically encrypt stored data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For stronger protection, an Android Keystore key can be configured to require user authentication before specific cryptographic operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This requires appropriate key configuration and careful handling of device capability and key invalidation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">22. Understand Android Backup Security<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android backup features can preserve application data across device changes or reinstalls, depending on configuration.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, Keystore keys are generally not restored with application data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Potential Problem<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Device A\n   |\n   +-- Encrypted Data\n   |\n   +-- Keystore Key\n\nBackup Restores Data\n        |\n        v\nDevice B\n   |\n   +-- Encrypted Data\n   |\n   +-- Original Key Missing<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The restored ciphertext may become undecryptable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Exclude device-bound encrypted files from backup where appropriate.<\/li>\n\n\n\n<li>Define explicit backup and restore behavior.<\/li>\n\n\n\n<li>Test device migration.<\/li>\n\n\n\n<li>Handle missing keys gracefully.<\/li>\n\n\n\n<li>Use a server-assisted recovery design if the product requires cross-device access.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important Principle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Encryption and backup must be designed together.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">23. Understand Rooted and Compromised Devices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Rooted devices may allow users or attackers to bypass some normal platform protections.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, detecting root access does not guarantee that a device is secure or insecure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Strategy<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use layered protections:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Secure backend authorization.<\/li>\n\n\n\n<li>Short-lived credentials.<\/li>\n\n\n\n<li>Keystore-backed keys.<\/li>\n\n\n\n<li>Input validation.<\/li>\n\n\n\n<li>Network security.<\/li>\n\n\n\n<li>Risk-based integrity checks where appropriate.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Play Integrity API<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Google Play Integrity API can provide integrity-related signals for supported applications and environments.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These signals can help a backend assess risk.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They should not be treated as an absolute guarantee of device or application trustworthiness.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">24. Protect Against Reverse Engineering<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android application packages can be inspected and analyzed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">R8 can shrink, optimize, and obfuscate application code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>buildTypes {\n    release {\n        isMinifyEnabled = true\n        isShrinkResources = true\n\n        proguardFiles(\n            getDefaultProguardFile(\n                \"proguard-android-optimize.txt\"\n            ),\n            \"proguard-rules.pro\"\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Code obfuscation raises the difficulty of reverse engineering.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not provide cryptographic protection and cannot make embedded private secrets safe.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Always keep critical authorization decisions on a trusted backend.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">25. Follow OWASP MASVS<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">OWASP Mobile Application Security Verification Standard (MASVS) provides a framework for evaluating mobile application security.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It covers areas such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Secure storage.<\/li>\n\n\n\n<li>Cryptography.<\/li>\n\n\n\n<li>Authentication and authorization.<\/li>\n\n\n\n<li>Network communication.<\/li>\n\n\n\n<li>Platform interaction.<\/li>\n\n\n\n<li>Code quality.<\/li>\n\n\n\n<li>Resilience.<\/li>\n\n\n\n<li>Privacy.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Why MASVS Matters<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It provides a structured approach to reviewing security requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Rather than focusing on isolated security features, developers can evaluate the application across multiple risk areas.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For security testing, also review OWASP MASTG, the Mobile Application Security Testing Guide.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">26. Practical Mini Project: Secure Notes App<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s build a simplified secure notes feature using Kotlin and Jetpack Compose.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Project Requirements<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The application will:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Accept a private note.<\/li>\n\n\n\n<li>Encrypt the note using AES-GCM.<\/li>\n\n\n\n<li>Use an Android Keystore-managed key.<\/li>\n\n\n\n<li>Store ciphertext locally.<\/li>\n\n\n\n<li>Decrypt the note when requested.<\/li>\n\n\n\n<li>Display clear error states.<\/li>\n\n\n\n<li>Avoid storing plaintext in persistent preferences.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Jetpack Compose UI\n        |\n        v\nSecureNotesViewModel\n        |\n        v\nSecureNotesRepository\n        |\n        +-- Android Keystore\n        |\n        +-- AES-GCM Encryption\n        |\n        v\nPrivate Encrypted File<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Create the Repository<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The following example uses the encryption manager created earlier.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class SecureNotesRepository(\n    private val context: Context,\n    private val encryptionManager:\n        SecureEncryptionManager\n) {\n\n    private val fileName =\n        \"secure_note.dat\"\n\n    fun saveNote(note: String) {\n\n        val encrypted =\n            encryptionManager.encrypt(note)\n\n        context.openFileOutput(\n            fileName,\n            Context.MODE_PRIVATE\n        ).bufferedWriter().use {\n            it.write(encrypted)\n        }\n    }\n\n    fun readNote(): String? {\n\n        val file = File(\n            context.filesDir,\n            fileName\n        )\n\n        if (!file.exists()) {\n            return null\n        }\n\n        val encrypted = file.readText()\n\n        return encryptionManager.decrypt(\n            encrypted\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Production Notes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is a small educational example.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Production code should consider:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>File size limits.<\/li>\n\n\n\n<li>Atomic writes.<\/li>\n\n\n\n<li>Appropriate background dispatchers.<\/li>\n\n\n\n<li>Backup exclusions.<\/li>\n\n\n\n<li>Key loss.<\/li>\n\n\n\n<li>Corrupt data handling.<\/li>\n\n\n\n<li>Multiple notes and database indexing.<\/li>\n\n\n\n<li>Authentication requirements.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The repository should receive application context rather than retaining an Activity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Define UI State<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>data class SecureNotesUiState(\n    val noteInput: String = \"\",\n    val decryptedNote: String = \"\",\n    val message: String? = null,\n    val isBusy: Boolean = false\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Create the ViewModel<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class SecureNotesViewModel(\n    private val repository: SecureNotesRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow(\n            SecureNotesUiState()\n        )\n\n    val uiState =\n        _uiState.asStateFlow()\n\n    fun updateNote(value: String) {\n        _uiState.update {\n            it.copy(\n                noteInput = value\n            )\n        }\n    }\n\n    fun saveNote() {\n\n        viewModelScope.launch {\n\n            _uiState.update {\n                it.copy(isBusy = true)\n            }\n\n            try {\n                val note =\n                    _uiState.value.noteInput\n\n                withContext(Dispatchers.IO) {\n                    repository.saveNote(note)\n                }\n\n                _uiState.update {\n                    it.copy(\n                        noteInput = \"\",\n                        message = \"Note saved\",\n                        isBusy = false\n                    )\n                }\n\n            } catch (e: CancellationException) {\n                throw e\n\n            } catch (e: Exception) {\n\n                _uiState.update {\n                    it.copy(\n                        message =\n                            \"Unable to save note\",\n                        isBusy = false\n                    )\n                }\n            }\n        }\n    }\n\n    fun loadNote() {\n\n        viewModelScope.launch {\n\n            _uiState.update {\n                it.copy(isBusy = true)\n            }\n\n            try {\n                val note =\n                    withContext(Dispatchers.IO) {\n                        repository.readNote()\n                    }\n\n                _uiState.update {\n                    it.copy(\n                        decryptedNote =\n                            note.orEmpty(),\n                        message = null,\n                        isBusy = false\n                    )\n                }\n\n            } catch (e: CancellationException) {\n                throw e\n\n            } catch (e: Exception) {\n\n                _uiState.update {\n                    it.copy(\n                        message =\n                            \"Unable to decrypt note\",\n                        isBusy = false\n                    )\n                }\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why This Design Is Better<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Cryptographic operations are separated from UI code.<\/li>\n\n\n\n<li>The ViewModel owns screen state.<\/li>\n\n\n\n<li>File operations run on a background dispatcher.<\/li>\n\n\n\n<li>Sensitive exception details are not displayed to users.<\/li>\n\n\n\n<li>The repository does not need an Activity reference.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Create the Jetpack Compose UI<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun SecureNotesScreen(\n    viewModel: SecureNotesViewModel\n) {\n\n    val state by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    Column(\n        modifier = Modifier\n            .fillMaxSize()\n            .padding(24.dp),\n        verticalArrangement =\n            Arrangement.spacedBy(16.dp)\n    ) {\n\n        Text(\n            text = \"Secure Notes\",\n            style =\n                MaterialTheme.typography\n                    .headlineMedium\n        )\n\n        OutlinedTextField(\n            value = state.noteInput,\n            onValueChange =\n                viewModel::updateNote,\n            label = {\n                Text(\"Private note\")\n            },\n            modifier = Modifier\n                .fillMaxWidth(),\n            minLines = 4\n        )\n\n        Button(\n            onClick = viewModel::saveNote,\n            enabled = !state.isBusy\n        ) {\n            Text(\"Encrypt &amp; Save\")\n        }\n\n        OutlinedButton(\n            onClick = viewModel::loadNote,\n            enabled = !state.isBusy\n        ) {\n            Text(\"Decrypt Note\")\n        }\n\n        state.message?.let {\n            Text(it)\n        }\n\n        if (\n            state.decryptedNote.isNotEmpty()\n        ) {\n            Text(\n                text = state.decryptedNote\n            )\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Security Consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The decrypted note is held in UI memory while displayed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Encryption at rest does not prevent sensitive information from appearing in memory or screenshots.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a production secure-notes application, consider screen-capture protection, automatic locking, authentication, and clearing sensitive UI state when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: Test Encryption<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Perform the following tests:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Save a private note.<\/li>\n\n\n\n<li>Confirm the file contains encrypted data.<\/li>\n\n\n\n<li>Load and decrypt the note.<\/li>\n\n\n\n<li>Modify the stored ciphertext.<\/li>\n\n\n\n<li>Verify that corrupted ciphertext is rejected.<\/li>\n\n\n\n<li>Restart the application.<\/li>\n\n\n\n<li>Confirm valid ciphertext can still be decrypted.<\/li>\n\n\n\n<li>Test device backup and restore behavior.<\/li>\n\n\n\n<li>Test app data clearing.<\/li>\n\n\n\n<li>Test on representative Android versions.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Important Warning<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Clearing application data generally removes the stored ciphertext and associated app-managed Keystore entries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The sample does not provide cloud recovery or cross-device synchronization.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">27. Common Android Security Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Hardcoding Private API Credentials<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Secrets embedded in an APK can be extracted.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Disabling TLS Validation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Accepting arbitrary certificates exposes users to network attacks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Logging Authentication Tokens<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Sensitive values may be exposed through logs or diagnostics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Storing Sensitive Data Without a Threat Model<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Choose protection based on the sensitivity of the information and expected threats.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Trusting Client-Side Authorization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Authorization must be enforced by the trusted backend.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Exporting Unnecessary Components<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exported components increase the application&#8217;s attack surface.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Ignoring Deep Link Validation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">External input must be validated and authorized.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Misusing Encryption<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Incorrect IV management or key handling can undermine otherwise strong algorithms.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Ignoring Backup and Key Recovery<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Device-bound keys may not survive backup restoration.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Treating Obfuscation as Complete Security<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Obfuscation is not a replacement for encryption, secure authentication, or backend authorization.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">28. Android Security Checklist<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before publishing an Android application, review the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use HTTPS for production network communication.<\/li>\n\n\n\n<li>Do not disable certificate validation.<\/li>\n\n\n\n<li>Avoid embedding private backend secrets.<\/li>\n\n\n\n<li>Use Android Keystore for suitable cryptographic keys.<\/li>\n\n\n\n<li>Use authenticated encryption for sensitive local data.<\/li>\n\n\n\n<li>Generate unique IVs for AES-GCM encryption.<\/li>\n\n\n\n<li>Handle encryption and decryption failures safely.<\/li>\n\n\n\n<li>Review application backup rules.<\/li>\n\n\n\n<li>Avoid logging passwords and tokens.<\/li>\n\n\n\n<li>Request only necessary permissions.<\/li>\n\n\n\n<li>Restrict exported Android components.<\/li>\n\n\n\n<li>Validate deep links and external Intent data.<\/li>\n\n\n\n<li>Protect sensitive WebView interfaces.<\/li>\n\n\n\n<li>Enforce authorization on the backend.<\/li>\n\n\n\n<li>Implement secure token expiration and logout.<\/li>\n\n\n\n<li>Review third-party dependencies.<\/li>\n\n\n\n<li>Enable appropriate release code shrinking.<\/li>\n\n\n\n<li>Test on supported Android versions.<\/li>\n\n\n\n<li>Review OWASP MASVS requirements.<\/li>\n\n\n\n<li>Perform security testing before release.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">29. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is Android Keystore?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android Keystore is a platform service that allows applications to generate and use cryptographic keys with system-enforced access restrictions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is Android Keystore hardware-backed?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It can be hardware-backed on supported devices and configurations. Hardware protection is not guaranteed for every key or device.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is AES-GCM encryption?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">AES-GCM is an authenticated encryption mode that protects both the confidentiality and integrity of encrypted data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is SharedPreferences encrypted?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Ordinary SharedPreferences does not automatically encrypt stored values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does DataStore encrypt data automatically?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Standard Jetpack DataStore does not provide automatic encryption of values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use EncryptedSharedPreferences?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">AndroidX Security Crypto APIs have been deprecated in recent releases. For new projects, review current guidance and choose a maintained storage and encryption approach appropriate to your application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can attackers extract API keys from Android applications?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Credentials embedded in application packages may be recovered through reverse engineering.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is HTTPS enough to secure an Android app?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. HTTPS protects network communication, but applications also need secure storage, authorization, input validation, and appropriate platform configuration.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should every Android app use certificate pinning?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Certificate pinning introduces maintenance and availability risks and is not generally necessary for every application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does R8 prevent reverse engineering?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. R8 makes code harder to analyze, but it does not prevent determined reverse engineering.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can encrypted data be restored to another device?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not automatically when the required Keystore key is device-bound and unavailable after restoration. Applications need an explicit recovery or migration strategy.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android application security requires more than adding encryption to a few stored values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Developers must consider how information is collected, processed, stored, transmitted, and eventually deleted.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining <strong>Kotlin, Android Keystore, AES-GCM encryption, secure storage design, HTTPS, Network Security Configuration, least-privilege permissions, and backend authorization<\/strong>, developers can significantly reduce common security risks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most important principle is:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Protect sensitive data throughout its lifecycle and never rely on client-side controls as the only security boundary.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Security should be considered from the beginning of application development rather than added only before release.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Regular reviews, dependency updates, and practical security testing help keep Android applications safer as platforms and threats evolve.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Official References<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/developer.android.com\/privacy-and-security\/security\" target=\"_blank\" rel=\"noopener\">Android Security Overview<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/privacy-and-security\/keystore\" target=\"_blank\" rel=\"noopener\">Android Keystore<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/privacy-and-security\/cryptography\" target=\"_blank\" rel=\"noopener\">Android Cryptography<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/privacy-and-security\/security-config\" target=\"_blank\" rel=\"noopener\">Network Security Configuration<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/identity\/data\/backup\" target=\"_blank\" rel=\"noopener\">Android Data Backup<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/guide\/topics\/permissions\/overview\" target=\"_blank\" rel=\"noopener\">Android Permissions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/identity\/sign-in\/biometric-auth\" target=\"_blank\" rel=\"noopener\">Android Biometric Authentication<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/mas.owasp.org\/MASVS\/\" target=\"_blank\" rel=\"noopener\">OWASP MASVS<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/mas.owasp.org\/MASTG\/\" target=\"_blank\" rel=\"noopener\">OWASP MASTG<\/a><\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Published by Moiks Developer Blog \u2014 Practical Android development tutorials using Kotlin, Jetpack Compose, and modern Android architecture.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to secure Android applications using Kotlin, Android Keystore, AES-GCM encryption, secure local storage, HTTPS, and Network Security Configuration. Explore authentication token protection, common security vulnerabilities, and a practical encrypted notes example for building safer Android apps.<\/p>\n","protected":false},"author":1,"featured_media":252,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":5,"footnotes":""},"categories":[14,16,3,333],"tags":[77,74,73,78,75,80,28,26,79,76],"class_list":["post-251","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-security","category-advanced-android","category-android-development","category-android-tutorials","tag-aes-gcm","tag-android-keystore","tag-android-security","tag-authentication","tag-data-encryption","tag-https","tag-jetpack-compose","tag-kotlin","tag-network-security","tag-secure-storage"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/251","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=251"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/251\/revisions"}],"predecessor-version":[{"id":253,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/251\/revisions\/253"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/252"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=251"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=251"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=251"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}