Security, Privacy, Ethics and GovernanceIntroductionAndroid applications operate inside a complex environment involving personal data, device hardware, cloud services, advertising networks, payment providers and third-party libraries. A seemingly simple application may access location, contacts, photographs, identifiers, health information or financial data. Security and privacy are therefore not optional features added near release; they are design responsibilities that influence architecture, user experience, testing and governance from the beginning. Security protects information and services against unauthorised access, alteration, disclosure and disruption. Privacy concerns how personal information is collected, used, shared, retained and deleted. Ethics asks whether an action is responsible and fair, even when it is technically legal. Governance establishes the policies, roles, controls and evidence needed to manage these responsibilities consistently. For an Android developer, the practical objective is not to make an application absolutely invulnerable—a condition that cannot be guaranteed—but to reduce risk, limit the consequences of failure and make trustworthy decisions visible to users and organisations. Learning ObjectivesBy the end of this chapter, a learner should be able to: - Explain confidentiality, integrity, availability, authenticity and accountability in mobile applications.
- Apply secure storage and encrypted communication principles in Android systems.
- Request least-privilege permissions and validate untrusted input.
- Describe safe authentication, session management and access control.
- Distinguish privacy, consent, ethics and legal compliance.
- Apply basic data-governance practices to collection, retention, sharing and deletion.
- Evaluate accessibility, intellectual-property and responsible-AI considerations.
- Analyse a mobile-app security and privacy scenario and recommend improvements.
1. The Security and Privacy Context of AndroidAn Android application includes more than its own source code. Its attack surface may include the application process, exported activities and services, content providers, intents, local databases, logs, backups, embedded web content, APIs, cloud infrastructure, software-development kits (SDKs), build pipelines and developer accounts. A useful security model is the CIA triad: | Property | Meaning in an Android application | Example control |
|---|
| Confidentiality | Only authorised parties can read information | Encryption and access control | | Integrity | Information and operations remain accurate and unaltered | Authenticated requests and validation | | Availability | Users can access legitimate functions when required | Resilience, rate limits and monitoring |
Two additional properties are important. Authenticity concerns whether a user, device, server or message is genuine. Accountability means that significant actions can be traced to responsible identities without collecting excessive personal information. Threat modelling provides a structured way to identify risk. A developer can ask: - What assets need protection?
- Who might attack or misuse the system?
- Through which entry points could an attack occur?
- What would be the impact of compromise?
- Which controls reduce likelihood or impact?
The STRIDE categories are a useful introductory model: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. Threat modelling should be revisited when features, dependencies, APIs or data flows change. 2. Secure Application ArchitectureSecurity is strongest when controls are layered. A mobile client should not be trusted merely because it is distributed through an official store. Attackers can inspect, modify, automate or run applications on compromised devices. Sensitive decisions—such as authorising a payment or granting an administrative role—must be enforced by a trusted backend, not only by client-side code. Important architectural principles include: - Secure defaults: Begin with the least exposure and require deliberate action to enable risky capabilities.
- Least privilege: Give each component only the permissions and data access necessary for its purpose.
- Separation of duties: Do not allow one token, service or role to perform unrelated high-risk operations.
- Defence in depth: Combine platform controls, application controls, server controls and monitoring.
- Fail securely: Errors should deny unauthorised actions without revealing secrets or internal structure.
- Minimise trust boundaries: Clearly identify where data crosses from the device to a server, SDK or external provider.
Android application components should not be exported unless external access is required. If a component must be exported, it should use explicit intents where practical, validate the caller and protect sensitive operations with appropriate permissions. Deep links and intent extras are untrusted input and must be checked before use. 3. Secure Storage3.1 Data classificationBefore selecting storage, classify information according to sensitivity. Public preferences, ordinary application settings, authentication tokens, personal records and payment information should not receive identical treatment. Classification supports decisions about encryption, retention, access, logging and deletion. Sensitive values should not be stored in source code, resources, version-control systems, screenshots, crash messages or ordinary logs. API keys embedded in an application should be treated as discoverable; they are not a substitute for server-side authorisation. 3.2 Android storage choicesAndroid provides several storage approaches: - Internal app-specific storage is ordinarily inaccessible to other applications and is suitable for private files, although it is not a complete defence against a compromised device.
- App-specific external storage may be useful for larger files, but developers must understand visibility, backup and device-removal behaviour.
- Shared media storage should be used only when the user-facing purpose requires sharing. Sensitive files should not be placed there casually.
- Room or SQLite databases provide structured storage. Database access still requires authorisation, input validation and, when appropriate, encryption.
- Preferences or DataStore are appropriate for small settings, not for arbitrary sensitive records.
- Android Keystore protects cryptographic keys by storing or using them in a platform-controlled environment. It should be used as part of a design rather than assumed to solve all storage problems.
Encryption protects data from particular forms of unauthorised access, but it does not correct excessive collection, weak authentication or insecure application logic. A lost key, unlocked device or malicious process with legitimate access can still expose data. 3.3 Tokens and secretsAccess tokens should be short-lived where practical, scoped to necessary functions and protected against accidental disclosure. Refresh tokens require stronger protection because they can create longer-lived access. Tokens should not be placed in URLs, copied to logs or transmitted through analytics events. On logout, locally stored credentials and tokens should be removed or invalidated according to the system design. Passwords should not be stored by the mobile client or backend in plaintext. A server should store password verifiers using a modern, deliberately slow password-hashing scheme with a unique salt for each password. Encryption and password hashing serve different purposes: encryption is reversible with a key; password hashing is designed for verification without recovering the original password. 4. Encrypted CommunicationAll sensitive communication should use current secure transport protocols, normally HTTPS using TLS. The server certificate and hostname must be validated by the platform networking stack. Developers should not disable certificate validation to “fix” development problems, accept all certificates, or transmit confidential values over unencrypted HTTP. Transport security provides confidentiality and integrity between endpoints, but it does not make an unsafe endpoint trustworthy. The application must still authenticate the server, authenticate the user where required, authorise each operation, validate responses and protect backend systems. Good communication practices include: - Use HTTPS consistently, including redirects and error paths.
- Avoid putting secrets or personal data in URLs because URLs may enter logs and browser history.
- Use request timeouts, bounded response sizes and rate limits.
- Validate server responses before displaying or processing them.
- Protect against replay where an operation has financial or safety consequences.
- Consider certificate pinning only after assessing operational risks such as certificate rotation, outages and recovery procedures.
- Keep dependencies and TLS configuration current.
A common mistake is assuming that encryption alone prevents manipulation. An encrypted connection can carry a malicious request from an authenticated but compromised account. Authorisation and business-rule validation remain necessary. 5. Least-Privilege PermissionsAndroid permissions are a user-facing security boundary. A permission should be requested only when the feature needs it, at the point of need, with a clear explanation of the benefit. Requesting a large group of permissions at first launch creates suspicion and increases potential harm. The least-privilege process is: - Identify the precise feature requirement.
- Determine whether a system picker or another privacy-preserving alternative avoids a broad permission.
- Declare only the required permission.
- Request it at runtime when the user reaches the relevant feature.
- Explain the purpose in clear, accurate language.
- Handle denial and limited access gracefully.
- Recheck permission state because users can change it later.
Permissions are not consent to unrelated processing. A user granting location access to find nearby stores does not automatically agree to indefinite location tracking or advertising profiling. The application must also respect platform policies and the promises made in its privacy notice. 6. Input Validation and Defensive ProcessingEvery value received from a user, intent, file, deep link, network response, clipboard, external application or SDK should be treated as untrusted. Validation should occur on the server as well as on the client because client controls can be bypassed. Validation includes: - Type validation: Confirm that a value is the expected data type.
- Range and length validation: Reject impossible dates, excessive text and unrealistic quantities.
- Allow-list validation: Accept known formats rather than attempting to enumerate every malicious format.
- Canonicalisation: Convert equivalent representations into a consistent form before checking them.
- Contextual output encoding: Encode data appropriately for HTML, SQL, JSON, shell commands or other contexts.
- Business-rule validation: Confirm that an operation is permitted for this user, object and state.
Parameterized database queries should be used instead of constructing SQL through string concatenation. Web content should be restricted, JavaScript should be enabled only when needed, and WebView bridges should expose minimal functionality. File names, MIME types and content should be checked; a filename extension alone does not establish file type or safety. Validation should fail closed. Error messages should help legitimate users without disclosing database structure, secrets, stack traces or whether sensitive accounts exist. 7. Authentication, Authorisation and SessionsAuthentication answers “Who are you?” Authorisation answers “What may you do?” These concepts must not be conflated. A successful login does not grant permission to read every record or perform every action. Safer authentication practices include: - Prefer established identity providers or platform-supported credential mechanisms when appropriate.
- Require strong, unique passwords when passwords are used.
- Offer multi-factor authentication for high-value accounts and operations.
- Use secure recovery processes; account recovery is part of authentication security.
- Apply rate limiting, anomaly detection and protections against automated guessing.
- Avoid revealing whether a username or email address exists.
- Use reauthentication for sensitive changes such as changing payment details.
Session tokens should be generated using a cryptographically secure random source, transmitted only over secure channels, stored with care and expired or revoked according to risk. Authorisation should be checked on every protected server operation. Object-level checks are essential: a user authorised to view one document must not gain access merely by changing an identifier in a request. Biometric authentication can improve usability, but biometric data should not be treated as a replaceable password. Where possible, applications should use platform biometric APIs that return an authentication result rather than collecting or storing raw biometric information. 8. Privacy by Design and ConsentPrivacy by design integrates privacy into architecture rather than adding a policy after implementation. Core principles include purpose limitation, data minimisation, accuracy, storage limitation, security and transparency. A practical data inventory records: | Question | Example |
|---|
| What is collected? | Email address, location, device event | | Why is it collected? | Account recovery, local search, fraud prevention | | Where is it stored? | Device database, regional cloud service | | Who receives it? | Service provider, support team, analytics vendor | | How long is it retained? | Until account deletion or a defined period | | How can it be deleted or corrected? | In-app control or verified support process |
Consent should be informed, specific, freely given and capable of withdrawal where consent is the legal basis. It should not be hidden in confusing language or bundled with unrelated purposes. A permission dialog is not a complete privacy notice. Users should understand what happens to data after it leaves the device. Privacy obligations vary by jurisdiction and sector. Depending on context, an organisation may need to address data-subject rights, breach notification, children’s privacy, health or financial data rules, cross-border transfers, processor contracts and records of processing. Developers should involve the organisation’s privacy or legal specialists rather than interpreting law independently. 9. Ethics, Accessibility and Intellectual PropertyLegal compliance is a minimum standard. Ethical development also considers foreseeable harm, fairness, autonomy and the interests of people who are not the paying customer. Dark patterns—such as confusing opt-outs, forced consent or intentionally difficult deletion—may increase short-term metrics while damaging trust and autonomy. Applications should be accessible to users with visual, auditory, motor or cognitive disabilities. Practical measures include meaningful content descriptions, sufficient contrast, scalable text, logical focus order, captions, alternatives to colour-only communication, touch targets large enough for reliable interaction and compatibility with screen readers. Accessibility testing should include real users or qualified evaluators, not only automated tools. Intellectual property includes source code, designs, icons, text, photographs, music, fonts, datasets and open-source components. A developer must verify licences, preserve required notices, comply with attribution conditions and avoid copying proprietary material. An open-source licence is not permission to ignore its conditions. Dependency inventories and software bills of materials help identify obligations and vulnerabilities. Ethical data use also requires examining secondary uses. Data collected for service delivery should not silently become a behavioural advertising dataset. Aggregation and anonymisation can reduce risk, but supposedly anonymous data may be re-identified when combined with other sources. Claims about anonymity should therefore be cautious and evidence-based. 10. Data Governance and Operational ResponsibilityGovernance converts principles into repeatable organisational practice. It identifies who owns data, who may access it, how decisions are approved and what evidence demonstrates compliance. A basic governance arrangement includes: - Data owner: Accountable for the purpose, quality and acceptable use of a data asset.
- Data steward: Manages definitions, access procedures, quality and lifecycle controls.
- System owner: Responsible for the technical service and its security configuration.
- Privacy or compliance function: Advises on obligations, assessments and rights requests.
- Developer and operations teams: Implement, test, monitor and remediate controls.
The data lifecycle is collection, use, sharing, storage, archival and deletion. Retention should have a defined purpose and schedule. Backups, caches, analytics exports and support tickets must be included in deletion planning. Access should be reviewed periodically, especially when staff change roles. Incident response should define preparation, detection, containment, eradication, recovery and lessons learned. Developers should know how to report a suspected exposed token, vulnerable dependency, lost device or inappropriate data disclosure. Logs should support investigation while avoiding passwords, full payment details and unnecessary personal information. Monitoring access to sensitive data is itself a privacy responsibility. Security testing may include code review, dependency scanning, static analysis, dynamic testing, permission review, authentication testing and controlled penetration testing. Test data should not contain real personal information unless strictly necessary and appropriately protected. 11. Artificial Intelligence and Third-Party SDKsAI features and third-party SDKs create additional governance questions. Before integrating an AI or analytics service, determine what data leaves the device, whether it is retained for training, where it is processed, whether users can opt out and how errors are corrected. Do not send passwords, private messages, health information or identifiable data to an external model merely because an API accepts it. AI-generated output may be inaccurate, biased or difficult to explain. High-impact decisions should include human oversight, appeal mechanisms and testing across relevant groups. Developers should document model purpose, data sources, limitations and monitoring arrangements. Every SDK expands the trust boundary. A library may collect identifiers, location or usage events independently of the application’s visible feature. Maintain a dependency inventory, review vendor documentation and permissions, pin or control versions, monitor vulnerabilities and remove unused libraries. A vendor’s privacy policy does not remove the application operator’s responsibility to understand data flows. 12. Illustrative Case: Community Health Appointment AppBackgroundA small organisation develops an Android application that allows patients to find clinics, book appointments and receive reminders. The first prototype stores patient names, appointment details and location history. It requests contacts, precise location, storage and notification permissions at first launch. A developer places an API token in the application source code and logs complete server responses during testing. ProblemA review identifies several risks: excessive permissions, disclosure of health-related information in logs, a token that can be extracted from the application, insecure assumptions that a logged-in user may access any appointment identifier, and unclear consent for location analytics. Some screens also lack labels for screen-reader users. AnalysisThe application contains sensitive personal and potentially health-related data. The impact of disclosure is high, so confidentiality, access control, retention and incident response require priority. The prototype also treats convenience as the main design goal rather than applying purpose limitation and least privilege. Approach and solutionThe team redesigns the system as follows: - Clinic search uses approximate location or a user-selected area before requesting precise location.
- Contacts and broad storage permissions are removed because they are not necessary.
- Appointment access is enforced on the server by checking both the authenticated user and the appointment owner.
- Communication uses HTTPS, short-lived access tokens and secure token storage supported by the platform.
- The embedded token is revoked and replaced with server-side credentials and scoped public configuration where appropriate.
- Logs are sanitised, access-controlled and reviewed for unnecessary personal data.
- A privacy notice explains collection, purposes, sharing, retention and deletion. Optional analytics requires a separate choice.
- The application adds screen-reader labels, scalable text, contrast checks and keyboard or switch-navigation testing.
- Dependencies are inventoried, vulnerabilities are monitored and an incident-response contact is published.
- A deletion workflow removes appointments and associated data according to legal and clinical retention requirements, while documenting any necessary exceptions.
OutcomeThe redesign reduces the amount of data collected, narrows the attack surface and makes access decisions enforceable. It also improves accessibility and gives users clearer control. The application is not “risk-free,” but its residual risks are understood, documented and monitored. Learning pointsSecurity and privacy improvements often reinforce usability: fewer intrusive permissions can increase trust, clear explanations reduce support requests and accessible interfaces serve a wider population. Most importantly, the controls are distributed across the client, backend, organisation and vendors; no single Android API can provide complete protection. 13. Challenges and LimitationsSecurity controls create trade-offs. Encryption can complicate search and recovery. Short sessions may reduce account takeover risk but inconvenience users. Detailed logs support investigation but may create privacy risk. Certificate pinning can strengthen selected threats while making recovery difficult if operational procedures are weak. Data minimisation can limit analytics and product experimentation. Threats also evolve. A secure design can become unsafe through an outdated library, a misconfigured cloud bucket, a new SDK, a compromised developer account or an organisational change. Security is therefore a continuous process involving patching, testing, monitoring, training and governance review. No control is perfect. Developers should communicate residual risk, document assumptions and prioritise protections according to likelihood, impact and affected populations. When a decision involves vulnerable users or high-consequence data, professional review is especially important. Best-Practice ChecklistBefore release, confirm that: - Sensitive data and threats have been identified.
- Only necessary permissions are declared and requested at the relevant feature.
- HTTPS and certificate validation are used correctly.
- Secrets are absent from source code, logs and URLs.
- Sensitive local data and cryptographic keys receive appropriate protection.
- Authentication, authorisation and object-level access checks are separate and tested.
- Inputs, deep links, files and server responses are validated.
- Privacy purposes, retention, sharing and deletion are documented.
- Consent and withdrawal mechanisms are understandable.
- Accessibility has been tested with platform tools and representative users.
- Dependencies, licences and vulnerabilities are reviewed.
- Incident reporting, revocation and recovery procedures exist.
- Release builds are tested, monitored and updated after deployment.
Chapter SummaryAndroid security, privacy, ethics and governance are connected disciplines. Security protects confidentiality, integrity and availability through layered architecture, secure storage, encrypted communication, least privilege, validation, authentication and authorisation. Privacy requires purpose limitation, minimisation, transparency, appropriate consent, retention control and user rights. Ethical practice extends beyond legal compliance to fairness, autonomy, accessibility and avoidance of manipulative design. Intellectual-property obligations apply to code, media, data and dependencies. Governance assigns responsibility across data owners, developers, operations teams, privacy specialists and vendors. A trustworthy application is created through continuous threat modelling, testing, monitoring, incident response and improvement rather than through one security feature. Key TermsConfidentiality: Protection against unauthorised disclosure of information. Integrity: Assurance that data and operations are accurate and not improperly altered. Availability: The ability of authorised users to access a service when needed. Authenticity: Confidence that an identity, device, server or message is genuine. Accountability: The ability to associate actions with responsible identities or processes. Threat modelling: A structured process for identifying assets, threats, vulnerabilities and controls. Least privilege: Granting only the permissions and access necessary for a task. Attack surface: The collection of interfaces through which a system may be attacked. Android Keystore: A platform facility for protecting and using cryptographic keys. Encryption: Reversible transformation of data using a key to protect confidentiality. Password hashing: One-way computational processing used to verify passwords without storing them directly. Authentication: Verification of an identity. Authorisation: Determination of which actions or resources an authenticated identity may use. Input validation: Checking that data conforms to expected type, format, range and business rules. Data minimisation: Collecting and processing no more personal data than necessary. Consent: An informed and meaningful agreement to a specified processing activity. Retention: The period for which information is kept. Accessibility: Designing technology so people with varied abilities can use it effectively. Data governance: Policies, roles and controls for responsible management of data. Threat surface: The set of components, interfaces and dependencies exposed to possible misuse or attack. Review QuestionsShort Answer Questions- What are the three properties in the CIA triad?
- Why should a client application not be trusted to enforce sensitive authorisation decisions by itself?
- What is the difference between authentication and authorisation?
- Give two examples of personal data that should not normally appear in application logs.
- Why is a runtime permission request not equivalent to complete privacy consent?
Long Answer Questions- Explain how secure storage, encrypted communication and access control work together in an Android application.
- Describe a least-privilege permission strategy for an application that offers location-based search.
- Discuss privacy by design, including data minimisation, purpose limitation, transparency and retention.
- Explain the responsibilities of developers, data owners, vendors and operations teams in data governance.
- Evaluate the ethical and accessibility responsibilities involved in releasing a public-service Android application.
Analytical / Application Questions- An application requests contacts, precise location, camera and storage permissions at first launch, although its main feature is displaying public articles. Analyse the risks and propose a redesigned permission and data strategy.
- A user can change an appointment identifier in an API request and view another patient’s appointment. Identify the security weakness, explain why client-side checks are insufficient and recommend server-side controls.
- A third-party analytics SDK begins sending device identifiers and location data to an overseas service. Develop a governance response covering investigation, user transparency, consent, vendor review, minimisation and possible remediation.
Multiple Choice Questions with AnswersQuestion 1Which principle requires an application to request only the access necessary for a feature? A. Least privilege B. Data duplication C. Open disclosure D. Availability maximisation Correct Answer: A. Least privilege Question 2What is the primary purpose of HTTPS with correctly validated TLS? A. To guarantee that every user is authorised B. To protect communication confidentiality and integrity in transit C. To prevent all malicious input D. To encrypt source code permanently Correct Answer: B. To protect communication confidentiality and integrity in transit Question 3Which statement correctly distinguishes authentication from authorisation? A. Authentication decides permissions; authorisation verifies identity B. Authentication verifies identity; authorisation determines permitted actions C. They are identical processes D. Authorisation is required only for administrators Correct Answer: B. Authentication verifies identity; authorisation determines permitted actions Question 4Which storage practice is unsafe? A. Using platform key-protection facilities for cryptographic keys B. Removing sensitive values from diagnostic logs C. Embedding a long-lived secret API credential in application source code D. Encrypting appropriately classified local data Correct Answer: C. Embedding a long-lived secret API credential in application source code Question 5Why should server-side validation be performed even when an Android interface validates input? A. Client controls can be bypassed or modified B. It makes all network communication unnecessary C. It eliminates the need for authentication D. It guarantees that users make no errors Correct Answer: A. Client controls can be bypassed or modified Question 6Which action best demonstrates data minimisation? A. Collecting precise location continuously for a local search feature B. Collecting only the approximate area needed to provide the requested search C. Collecting contacts in case future features need them D. Retaining all historical data indefinitely Correct Answer: B. Collecting only the approximate area needed to provide the requested search Question 7A user successfully logs in but attempts to read another user’s record by changing an identifier. What control is most directly required? A. Object-level authorisation on the server B. A larger application icon C. A longer privacy notice only D. Disabling all local notifications Correct Answer: A. Object-level authorisation on the server Question 8Which statement about biometric authentication is most appropriate? A. Applications should normally store raw fingerprints themselves B. Biometrics can never be used for sensitive actions C. Platform biometric APIs can provide an authentication result without exposing raw biometric data D. Biometric approval removes the need for server authorisation Correct Answer: C. Platform biometric APIs can provide an authentication result without exposing raw biometric data Question 9Why must third-party SDKs be included in privacy and security review? A. They cannot access data or network services B. They may expand data flows, permissions and the application trust boundary C. They automatically satisfy every legal requirement D. They replace the need for dependency updates Correct Answer: B. They may expand data flows, permissions and the application trust boundary Question 10Which practice best supports responsible data governance? A. Keeping undefined data indefinitely B. Assigning data ownership, defining retention and reviewing access C. Allowing every developer to access production data D. Deleting all security logs immediately Correct Answer: B. Assigning data ownership, defining retention and reviewing access
|