Stop Storing Secrets Wrong: The Right Way to Encrypt Data in Android
Article Summary
Chamod Lakmal from PickMe reveals why most Android apps store secrets dangerously wrong. Hardcoded keys and SharedPreferences encryption are fundamentally broken, leaving user data vulnerable to extraction.
This technical deep-dive demonstrates how to implement enterprise-grade encryption in Android using the Android Keystore system. The article provides production-ready code with clean architecture patterns, covering everything from basic implementation to advanced features like biometric authentication and key attestation.
Key Takeaways
- Android Keystore provides hardware-backed, non-extractable keys tied to specific devices
- Each encryption generates unique IV preventing identical plaintext producing identical ciphertext
- Implementation uses AES/CBC/PKCS7 with suspend functions for non-blocking operations
- Key attestation verifies keys created in secure hardware, not by malicious apps
- Architecture follows dependency injection with DataStore for modern Android development
The article delivers a complete, testable encryption module that meets GDPR, PCI DSS, and HIPAA compliance standards while maintaining clean code architecture.
About This Article
Android developers need to handle cryptographic keys across different device types and Android versions. The challenge is maintaining backward compatibility since the APIs changed significantly between Android 30 and earlier versions.
Chamod Lakmal's approach uses conditional checks with Build.VERSION.SDK_INT to support both the modern setUserAuthenticationParameters() method and the older setUserAuthenticationValidityDurationSeconds() method. This allows biometric authentication to work across all Android versions.
The modular architecture uses dependency injection, which makes unit testing easier through mocking and allows integration testing on multiple device types. This approach ensures that encryption operations preserve data integrity and meet GDPR, PCI DSS, and HIPAA compliance requirements.