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