|

why do we need to use the Jetpack security in android?

Sharing is caring!

We need Jetpack Security in Android mainly because it helps developers easily and securely store sensitive data without having to implement complicated cryptography themselves.

What is Jetpack Security?

Jetpack Security (androidx.security) is an Android Jetpack library that provides robust and easy-to-use security best practices for storing data on a user’s device. It’s designed to simplify the process of encrypting files and shared preferences, handling the complex cryptography operations under the hood so developers can focus on building their apps.

The Core Problem It Solves

By default, data stored on an Android device (like in SharedPreferences or files) is not securely encrypted. If a device is lost, stolen, or compromised (e.g., through rooting), malicious actors can potentially access this sensitive data.

Jetpack Security provides a standardized, well-tested way to encrypt this data at rest.

Key Components and Features

1. EncryptedSharedPreferences

A secure replacement for the standard SharedPreferences that automatically encrypts keys and values.

  • What it encrypts: Both the keys and the values are encrypted. An attacker cannot even see what your preference keys are named (e.g., user_auth_token).

  • Use Case: Storing any sensitive configuration data, user tokens, session IDs, or small bits of sensitive user information.

2. EncryptedFile

A secure way to read and write files. It encrypts the entire file’s contents.

  • How it works: It uses FileOutputStream and FileInputStream but wraps them with cryptographic operations.

  • Use Case: Storing sensitive documents, cached data, or any other file that contains private information.

3. MasterKeys

This is the linchpin. JetSec needs a master key to encrypt and decrypt your data keys. The library provides a safe and standard way to handle this.

  • The Default: The MasterKeys.getOrCreate() method uses the AES256_GCM_SPEC specification, which is considered very secure. Crucially, this master key itself is stored in the Android Keystore system.

  • Why Keystore is Key: The Android Keystore is a hardware-backed secure container. The master key material is stored in a dedicated, isolated security chip (Trusted Execution Environment – TEE or Secure Element – SE) on modern devices. This makes it extremely difficult to extract, even from a rooted device.

How It Works Under the Hood

Jetpack Security uses a two-layer encryption system:

  1. Master Key: A single, strong key stored in the Android Keystore. This key is used to encrypt and decrypt…

  2. Data Keys: Individual keys for each file or set of preferences. These data keys are stored in the preferences or file metadata themselves, but they are encrypted by the master key.

This approach is efficient because you only have one key in the Keystore (which has limited space), and you can have as many data keys as you need.

Examples:

1. Using EncryptedSharedPreferences

import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys

// 1. Create or get the master key alias
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

// 2. Create EncryptedSharedPreferences
val sharedPreferences = EncryptedSharedPreferences.create(
    "secret_shared_prefs", // filename
    masterKeyAlias,
    context,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, // Encrypts keys
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM // Encrypts values
)

// 3. Use it like regular SharedPreferences, but now it's secure!
with(sharedPreferences.edit()) {
    putString("api_key", "your_very_sensitive_api_token_here")
    apply()
}

val savedToken = sharedPreferences.getString("api_key", "default")

2. Using EncryptedFile

import androidx.security.crypto.EncryptedFile
import androidx.security.crypto.MasterKeys

// 1. Create or get the master key alias
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

// 2. Create an EncryptedFile object
val secureFile = EncryptedFile.Builder(
    File(context.filesDir, "secure_data.dat"),
    context,
    masterKeyAlias,
    EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build()

// Write to the encrypted file
val dataToSave = "My secret text".toByteArray(StandardCharsets.UTF_8)
secureFile.openFileOutput().use { outputStream ->
    outputStream.write(dataToSave)
}

// Read from the encrypted file
val contents = secureFile.openFileInput().use { inputStream ->
    inputStream.readBytes().toString(StandardCharsets.UTF_8)
}

When Should You Use It?

Use Jetpack Security for:

  • User authentication tokens (OAuth tokens, session IDs)

  • Personally Identifiable Information (PII) – emails, addresses, phone numbers (if you must store them)

  • Any other sensitive data your app must persist locally (e.g., financial data, private user content).

When to Consider Alternatives:

  • For passwords/PINs: Always use the Credential Manager API or a biometric-promt to trigger authentication, never store these directly.

  • For highly sensitive data: Consider if storing the data locally is absolutely necessary. The most secure data is data you don’t store.

  • For large datasets: Encryption/decryption has a performance cost. For large databases, consider using SQLCipher (an encrypted SQLite database) or the Room Database with an encryption library.

Conclusion

Jetpack Security is the modern, Google-recommended standard for encrypting data at rest on Android. It abstracts away the immense complexity of cryptography and leverages the hardware-backed security of the Android Keystore, making it significantly more secure than most custom solutions and much easier to implement correctly. You should use it whenever you need to store sensitive information on the device.

0 0 votes
Article Rating

Similar Posts

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments