Using Cryptography to Store Credentials Safely | Android …

Posted by Trevor Johns, Android Developer Relations team

Following our talk "Security and Privacy in Android Apps" at Google I/O last year, many people had specific questions about how to use cryptography in Android. Many of those revolved around which APIs to use for a specific purpose. Let's look at how to use cryptography to safely store user credentials, such as passwords and auth tokens, on local storage.

A common (but incorrect) pattern that we've recently become aware of is to use SecureRandom as a means of generating deterministic key material, which would then be used to encrypt local credential caches. Examples are not hard to find, such as here, here, here, and elsewhere.

In this pattern, rather than storing an encryption key directly as a string inside an APK, the code uses a proxy string to generate the key instead similar to a passphrase. This essentially obfuscates the key so that it's not readily visible to attackers. However, a skilled attacker would be able to easily see around this strategy. We don't recommend it.

The fact is, Android's existing security model already provides plenty of protection for this kind of data. User credentials should be stored with the MODE_PRIVATE flag set and stored in internal storage, rather than on an SD card, since permissions aren't enforced on external storage. Combined with device encryption, this provides protection from most types of attacks targeting credentials.

However, there's another problem with using SecureRandom in the way described above. Starting with Android 4.2, the default SecureRandom provider is OpenSSL, and a developer can no longer override SecureRandoms internal state. Consider the following code:

The old Bouncy Castle-based implementation allowed overriding the internally generated, /dev/urandom based key for each SecureRandom instance. Developers which attempted to explicitly seed the random number generator would find that their seed replaces, not supplements, the existing seed (contrary to the reference implementations documentation). Under OpenSSL, this error-prone behavior is no longer possible.

Unfortunately, applications who relied on the old behavior will find that the output from SecureRandom changes randomly every time their application starts up. (This is actually a very desirable trait for a random number generator!) Attempting to obfuscate encryption keys in this manner will no longer work.

A more reasonable approach is simply to generate a truly random AES key when an application is first launched:

Note that the security of this approach relies on safeguarding the generated key, which is is predicated on the security of the internal storage. Leaving the target file unencrypted (but set to MODE_PRIVATE) would provide similar security.

See the rest here:
Using Cryptography to Store Credentials Safely | Android ...

Related Posts
This entry was posted in $1$s. Bookmark the permalink.