Android: Use Password Technology to securely save credenandroid

Source: Internet
Author: User
Using Cryptography to store credentials safely

Http://android-developers.blogspot.com/2013/02/using-cryptography-to-store-credentials.html

Posted by Trevor Johns, Android developer Relations Team

Following our talk "security and privacy in Android apps" at Google I/O last year, average people had
Specific questions about how to use cryptography in Android. snapshot 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.

An anti-Pattern

A common (but incorrect) pattern that we 've recently become aware of is to useSecureRandomAs
A means of generating deterministic key material, which wowould then be used to encrypt local credential caches. Examples are not hard to find, such as 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 wocould 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 shocould be stored withMODE_PRIVATEFlag
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 usingSecureRandomIn the way described above. Starting with Android 4.2, the defaultSecureRandomProvider is OpenSSL, and a developer can
No longer overrideSecureRandom'S internal state. Consider the following code:

  SecureRandom secureRandom = new SecureRandom();  byte[] b = new byte[] { (byte) 1 };  secureRandom.setSeed(b);  // Prior to Android 4.2, the next line would always return the same number!  System.out.println(secureRandom.nextInt());

The old bouncy castle-based implementation allowed overriding the internally generated,/dev/urandom based Key for eachSecureRandomInstance. Developers which attempted to explicitly seed the random number generator
Wocould find that their seed replaces, not supplements, the existing seed (contrary to the Reference
Implementation's documentation). Under OpenSSL, this error-prone behavior is no longer possible.

Unfortunately, applications who relied on the old behavior will find that output fromSecureRandomChanges 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.

The right way

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

public static SecretKey generateKey() throws NoSuchAlgorithmException {    // Generate a 256-bit key    final int outputKeyLength = 256;    SecureRandom secureRandom = new SecureRandom();    // Do *not* seed secureRandom! Automatically seeded from system entropy.    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");    keyGenerator.init(outputKeyLength, secureRandom);    SecretKey key = keyGenerator.generateKey();    return key;}

Note that the security of this approach relies on safeguarding the generated key, which is predicated on the security of the internal storage. Leaving the target file unencrypted (but setMODE_PRIVATE) Wocould provide
Similar security.

Even more security

If your app needs additional encryption, a recommended approach is to require a passphase or pin to access your application. this passphrase cocould be fed into pbkdf2 to generate the encryption key. (pbkdf2 is a commonly used algorithm for deriving key material
From a passphrase, using a technique known as "Key stretching".) Android provides an implementation of this algorithm insideSecretKeyFactoryAsPBKDF2WithHmacSHA1:

public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {    // Number of PBKDF2 hardening rounds to use. Larger values increase    // computation time. You should select a value that causes computation    // to take >100ms.    final int iterations = 1000;     // Generate a 256-bit key    final int outputKeyLength = 256;    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");    KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);    SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);    return secretKey;}

The salt shoshould be a random string, again generated usingSecureRandomAnd persisted on internal storage alongside any encrypted data. This is important to mitigate the risk of attackers using a rainbow table to precompute
Password hashes.

Check your apps for proper use of securerandom

As mentioned above and in the new security features in jelly bean, the default implementation
OfSecureRandomIs changed in Android 4.2. using it to deterministically Generate Keys is no longer possible.

If you're one of the developers who's been generating keys the wrong way, we recommend upgrading your app today to prevent Subtle problems as more users upgrade to devices running Android 4.2 or later

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.