Simple hiding/obfuscation of strings in APK? - android

Sometimes you need to store a password in the app itself, such as a username/password for communicating with your own server. In these cases it's not possible to follow the normal process of storing passwords - i.e. hash the password, store the hash, compare to hashed user input - because you don't have any user input to compare the hash to. The password needs to be provided by the app itself. So how to protect the stored password in the APK? Would a password-generating function like the one below be reasonably secure?
Plain text:
String password = "$()&HDI?=!";
Simple obfuscation:
private String getPassword(){
String pool = "%&/#$()7?=!656sd8KJ%&HDI!!!G98y/&%=?=*^%&ft4%(";
return pool.substring(4, 7) + pool.substring(20, 24) + pool.substring(8, 11);
}
I know ProGuard has some obfuscation capabilities, but I'm curious about what the above "obfuscation" technique does when it's compiled, and how hard it would be for someone to figure it out by looking in the APK and/or using other more sophisticated techniques?

tl;dr If you know how to decompile APK, you can easily get the password, no matter how obfuscated the code was. Don't store passwords in APK, it's not secure.
I know ProGuard has some obfuscation capabilities, but I'm curious
about what the above "obfuscation" technique does when it's compiled,
and how hard it would be for someone to figure it out by looking in
the APK and/or using other more sophisticated techniques?
I will show you how easy it is. Here is an Android SSCCE which we will decompile:
MyActivity.java:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text = (TextView) findViewById(R.id.text);
text.setText(getPassword());
}
private String getPassword() {
String pool = "%&/#$()7?=!656sd8KJ%&HDI!!!G98y/&%=?=*^%&ft4%(";
return pool.substring(4, 7) + pool.substring(20, 24) + pool.substring(8, 11);
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
After compiling it and running we can see $()&HDI?=! on a TextView.
Let's decompile an APK:
unzip myapp.apk or right-click on the APK and Unzip here.
classes.dex file appears.
Convert classes.dex to JAR file with dex2jar. After executing dex2jar.sh classes.dex, classes_dex2jar.jar file
appears.
Using some Java decompiler on classes_dex2jar.jar, for example JD-GUI, we retrieve such Java code from MyActivity.class:
public class MyActivity extends Activity
{
private String getPassword()
{
return "%&/#$()7?=!656sd8KJ%&HDI!!!G98y/&%=?=*^%&ft4%(".substring(4, 7)
+ "%&/#$()7?=!656sd8KJ%&HDI!!!G98y/&%=?=*^%&ft4%(".substring(20, 24)
+ "%&/#$()7?=!656sd8KJ%&HDI!!!G98y/&%=?=*^%&ft4%(".substring(8, 11);
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(2130903040);
((TextView)findViewById(2131034112)).setText(getPassword());
}
}
ProGuard can't help much, the code will be still easily readable.
Based on the above, I can already give you an answer for this question:
Would a password-generating function like the one below be reasonably
secure?
No. As you can see, it increases difficulty of reading deobfuscated code by a tiny bit. We should not obfuscate the code in such way, because:
It gives an illusion of security.
It is a waste of developer's time.
It decreases readability of the code.
In the official Android documentation, in the Security and Design part, they're advising this to protect your Google Play public key:
To keep your public key safe from malicious users and hackers, do not
embed it in any code as a literal string. Instead, construct the
string at runtime from pieces or use bit manipulation (for example,
XOR with some other string) to hide the actual key. The key itself is
not secret information, but you do not want to make it easy for a
hacker or malicious user to replace the public key with another key.
Ok, so let's try that:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text = (TextView) findViewById(R.id.text);
text.setText(xor("A#NCyw&IHY", "ehge13ovux"));
}
private String xor(String a, String b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length() && i < b.length(); i++) {
sb.append((char) (a.charAt(i) ^ b.charAt(i)));
}
return sb.toString();
}
Gives $()&HDI?=! on a TextView, good.
Decompiled version:
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(2130903040);
((TextView)findViewById(2131034112)).setText(xor("A#NCyw&IHY", "ehge13ovux"));
}
private String xor(String paramString1, String paramString2)
{
StringBuilder localStringBuilder = new StringBuilder();
for (int i = 0; (i < paramString1.length()) && (i < paramString2.length()); i++) {
localStringBuilder.append((char)(paramString1.charAt(i) ^ paramString2.charAt(i)));
}
return localStringBuilder.toString();
}
Very similar situation like before.
Even if we had extremely complicated function soStrongObfuscationOneGetsBlind(), we can always run decompiled code and see what is it producing. Or debug it step-by-step.

Related

Android - LIBGDX FileHandle doesn't write to local file

In my game, there is a highscore that is supposed to be saved.
private void saveHighscore()
{
FileHandle file = Gdx.files.local("asdwdasfwad/asdawwafs.txt");
String highscoreString = Integer.toString(this.highscore);
file.writeString(highscoreString, false);
Gdx.app.log("saving", "saving");
}
private int loadHighscore()
{
FileHandle file = Gdx.files.local("asdwdasfwad/asdawwafs.txt");
String highscoreString = file.readString();
int highscore = Integer.parseInt(highscoreString);
Gdx.app.log("loading", "loading");
return highscore;
}
When I run this on my phone, "saving" is logged into the console without any errors, even though the path I have specified (asdwdasfwad/asdawwafs.txt) doesn't even exist. Even if I use an existent path, no file is created.
Not a direct answer to your problem, but since you just want to save a highscore:
You can just use Preferences for this. Its an class provided by libGDX that allows you to easily save small data.
For further information visit the official documentation page:
Click here

Writing XPKeywords in Exif

I want to write XPKeywords in a Jpeg Image. Till now I am using Sansaleen java api for writing Exif tags in Jpeg images. I am able to write most of the tags like subject, comment, author, rating but I am not able to write Windows XP Keywords. I am using below code:
public static TiffOutputField getTiffOutputFieldKeyword(
TiffOutputSet outputSet, String metaDataToChange) {
TiffOutputField imageHistoryPre = outputSet
.findField(TiffConstants.EXIF_TAG_XPKEYWORDS);
if (imageHistoryPre != null) {
outputSet.removeField(TiffConstants.EXIF_TAG_XPKEYWORDS);
}
TiffOutputField tiffOutputField = new TiffOutputField(
TiffConstants.EXIF_TAG_XPKEYWORDS,
TiffFieldTypeConstants.FIELD_TYPE_BYTE,
metaDataToChange.length(), metaDataToChange.getBytes("UTF-16"));
return tiffOutputField;
}
I have googled this issue and came to know that XP_Keyword accept special encoded in UCS2 so I have updated my code. But still not able to write complete tags. Tags are semi-colon separated.
Please let me know if there present any resolution for the above issue or is there any other java/android lib which can write Tags in Jpeg files.
Got it working:
public static TiffOutputField getTiffOutputFieldKeyword(
TiffOutputSet outputSet, String metaDataToChange) {
TiffOutputField imageHistoryPre = outputSet
.findField(TiffConstants.EXIF_TAG_XPKEYWORDS);
if (imageHistoryPre != null) {
outputSet.removeField(TiffConstants.EXIF_TAG_XPKEYWORDS);
}
TiffOutputField tiffOutputField = new TiffOutputField(
TiffConstants.EXIF_TAG_XPKEYWORDS,
TiffFieldTypeConstants.FIELD_TYPE_BYTE,
metaDataToChange.getBytes("UTF-16").length, metaDataToChange.getBytes("UTF-16"));
return tiffOutputField;
}
Just use length of Bytes in "UTF-16" and then write. Also, Make sure you trim the characters to not include any spaces. Also, please give a try by separating string with Semicolon(;) as By default Windows take semicolon separated keywords.

Enabling independent third-parties to localize Android applications; localization data outside of app's APK

I have the requirement of developing an Android application that loads localized text from external resources outside of its primary APK. The reason for this is to enable third-parties to independently provide translations of the application. The application currently has a single English localization with a fairly large number of strings (~2,000).
I would prefer not to break away form Android's resource system; e.g., I would like to provide the primary-language localized strings in strings.xml just like in any Android app.
To accomplish this, I have created a class which extends android.content.res.Resources, overriding the three getText methods. The overriding implementations will return resources from the external localization source when possible, and otherwise forward the request to the super.getText() implementation.
Resources wrapper:
public class IntegratedResources extends Resources {
private ResourceIntegrator ri;
public IntegratedResources(AssetManager assets, DisplayMetrics metrics, Configuration config, ResourceIntegrator ri) {
super(assets, metrics, config);
this.ri = ri;
}
#Override
public CharSequence getText(int id)
throws NotFoundException {
return ri == null ? super.getText(id) : ri.getText(id);
}
#Override
public CharSequence getText(int id, CharSequence def)
throws NotFoundException {
return ri == null ? super.getText(id, def) : ri.getText(id, def);
}
#Override
public CharSequence[] getTextArray(int id)
throws NotFoundException {
return ri == null ? super.getTextArray(id) : ri.getTextArray(id);
}
}
I then created a ContextWrapper implementation to wrap an Activity's context. The context wrapper's getResources() method will return the IntegratedResources object above.
ContextWrapper:
public class IntegratedResourceContext extends ContextWrapper {
private IntegratedResources integratedResources;
public IntegratedResourceContext(Activity activity, String packageName)
throws NameNotFoundException {
super(activity);
ResourceIntegrator ri = packageName == null ? null : new ResourceIntegrator(activity, packageName);
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
integratedResources = new IntegratedResources(activity.getAssets(), displayMetrics,
activity.getResources().getConfiguration(), ri);
}
#Override
public Resources getResources() {
return integratedResources;
}
}
And finally we have the "ResourceIntegrator" class, which picks resources out of a specified installed third-party localization APK. A different implementation could be created to pull them from an XML or properties file if desired.
ResourceIntegrator:
public class ResourceIntegrator {
private Resources rBase;
private Resources rExternal;
private String externalPackageName;
private Map<Integer, Integer> baseIdToExternalId = new HashMap<Integer, Integer>();
public ResourceIntegrator(Context context, String externalPackageName)
throws NameNotFoundException {
super();
rBase = context.getResources();
this.externalPackageName = externalPackageName;
if (externalPackageName != null) {
PackageManager pm = context.getPackageManager();
rExternal = pm.getResourcesForApplication(externalPackageName);
}
}
public CharSequence getText(int id, CharSequence def) {
if (rExternal == null) {
return rBase.getText(id, def);
}
Integer externalId = baseIdToExternalId.get(id);
if (externalId == null) {
// Not loaded yet.
externalId = loadExternal(id);
}
if (externalId == 0) {
// Resource does not exist in external resources, return from base.
return rBase.getText(id, def);
} else {
// Resource has a value in external resources, return it.
return rExternal.getText(externalId);
}
}
public CharSequence getText(int id)
throws NotFoundException {
if (rExternal == null) {
return rBase.getText(id);
}
Integer externalId = baseIdToExternalId.get(id);
if (externalId == null) {
// Not loaded yet.
externalId = loadExternal(id);
}
if (externalId == 0) {
// Resource does not exist in external resources, return from base.
return rBase.getText(id);
} else {
// Resource has a value in external resources, return it.
return rExternal.getText(externalId);
}
}
public CharSequence[] getTextArray(int id)
throws NotFoundException {
if (rExternal == null) {
return rBase.getTextArray(id);
}
Integer externalId = baseIdToExternalId.get(id);
if (externalId == null) {
// Not loaded yet.
externalId = loadExternal(id);
}
if (externalId == 0) {
// Resource does not exist in external resources, return from base.
return rBase.getTextArray(id);
} else {
// Resource has a value in external resources, return it.
return rExternal.getTextArray(externalId);
}
}
private int loadExternal(int baseId) {
int externalId;
try {
String entryName = rBase.getResourceEntryName(baseId);
String typeName = rBase.getResourceTypeName(baseId);
externalId = rExternal.getIdentifier(entryName, typeName, externalPackageName);
} catch (NotFoundException ex) {
externalId = 0;
}
baseIdToExternalId.put(baseId, externalId);
return externalId;
}
}
My question to stackoverflow is whether the above implementation is a good idea, whether it's using the API properly, and whether its design is future-proof against the unknown versions of Android of tomorrow. I've not seen anyone doing this before, and can't seem to find anything about solving this problem in the docs or on the web.
The underlying requirement of allowing independent third-party translations is fairly critical. It is not currently feasible to internally maintain dozens of translations for this application, and I have no capability to vet user-provided translations for quality. In the case that this design is a very bad idea and no similar alternative is available, then localization may have to be done without Android's resource-management system altogether.
In the event that this is a good idea, please feel free to use and improve the above code.
My question to stackoverflow is whether the above is a good idea
I will be stunned if it is a complete solution, since you cannot force Android to use your custom ContextWrapper. It should work for any place where you manually call getString(), getText(), and the like, but I do not see how it will work anywhere that Android accesses those resources beyond one of your activities. There are many places where you cannot call getText() and so on yourself, such as:
the home screen launcher
the information for your app in Settings
the recent tasks list
Moreover, you will have perpetual versioning problems, unless you plan to never add new strings. You have no way of forcing third-party translations to support new strings, and so you will wind up with an app with a mix of translated and non-translated strings.
whether it's using the API properly
That seems OK.
whether its design is future-proof against the unknown versions of Android of tomorrow
The number of places where Android will access the resources itself is likely to increase, rather than decrease.
It is not currently feasible to internally maintain dozens of translations for this application, and I have no capability to vet user-provided translations for quality.
Then only support languages that you are willing to manage yourself. First, as I have noted, I do not see how this will be a complete solution, on a couple of fronts. Second, you seem to think that your approach will cause you to not be blamed for poor translations, and while it will probably reduce how much blame you get, it will not eliminate such blame. I agree with Squonk in this regard.
I admire your zeal for offering more translations, but, personally, I wouldn't go down this particular path.
I don't think your technique will work for resource references in layouts. These are resolved by the LayoutInflater and ultimately by the TypedArray implementation, which invokes private methods to load the resources.

user credentials on android [duplicate]

I am creating an application which connects to the server using username/password and I would like to enable the option "Save password" so the user wouldn't have to type the password each time the application starts.
I was trying to do it with Shared Preferences but am not sure if this is the best solution.
I would appreciate any suggestion on how to store user values/settings in Android application.
In general SharedPreferences are your best bet for storing preferences, so in general I'd recommend that approach for saving application and user settings.
The only area of concern here is what you're saving. Passwords are always a tricky thing to store, and I'd be particularly wary of storing them as clear text. The Android architecture is such that your application's SharedPreferences are sandboxed to prevent other applications from being able to access the values so there's some security there, but physical access to a phone could potentially allow access to the values.
If possible I'd consider modifying the server to use a negotiated token for providing access, something like OAuth. Alternatively you may need to construct some sort of cryptographic store, though that's non-trivial. At the very least, make sure you're encrypting the password before writing it to disk.
I agree with Reto and fiXedd. Objectively speaking it doesn't make a lot of sense investing significant time and effort into encrypting passwords in SharedPreferences since any attacker that has access to your preferences file is fairly likely to also have access to your application's binary, and therefore the keys to unencrypt the password.
However, that being said, there does seem to be a publicity initiative going on identifying mobile applications that store their passwords in cleartext in SharedPreferences and shining unfavorable light on those applications. See http://blogs.wsj.com/digits/2011/06/08/some-top-apps-put-data-at-risk/ and http://viaforensics.com/appwatchdog for some examples.
While we need more attention paid to security in general, I would argue that this sort of attention on this one particular issue doesn't actually significantly increase our overall security. However, perceptions being as they are, here's a solution to encrypt the data you place in SharedPreferences.
Simply wrap your own SharedPreferences object in this one, and any data you read/write will be automatically encrypted and decrypted. eg.
final SharedPreferences prefs = new ObscuredSharedPreferences(
this, this.getSharedPreferences(MY_PREFS_FILE_NAME, Context.MODE_PRIVATE) );
// eg.
prefs.edit().putString("foo","bar").commit();
prefs.getString("foo", null);
Here's the code for the class:
/**
* Warning, this gives a false sense of security. If an attacker has enough access to
* acquire your password store, then he almost certainly has enough access to acquire your
* source binary and figure out your encryption key. However, it will prevent casual
* investigators from acquiring passwords, and thereby may prevent undesired negative
* publicity.
*/
public class ObscuredSharedPreferences implements SharedPreferences {
protected static final String UTF8 = "utf-8";
private static final char[] SEKRIT = ... ; // INSERT A RANDOM PASSWORD HERE.
// Don't use anything you wouldn't want to
// get out there if someone decompiled
// your app.
protected SharedPreferences delegate;
protected Context context;
public ObscuredSharedPreferences(Context context, SharedPreferences delegate) {
this.delegate = delegate;
this.context = context;
}
public class Editor implements SharedPreferences.Editor {
protected SharedPreferences.Editor delegate;
public Editor() {
this.delegate = ObscuredSharedPreferences.this.delegate.edit();
}
#Override
public Editor putBoolean(String key, boolean value) {
delegate.putString(key, encrypt(Boolean.toString(value)));
return this;
}
#Override
public Editor putFloat(String key, float value) {
delegate.putString(key, encrypt(Float.toString(value)));
return this;
}
#Override
public Editor putInt(String key, int value) {
delegate.putString(key, encrypt(Integer.toString(value)));
return this;
}
#Override
public Editor putLong(String key, long value) {
delegate.putString(key, encrypt(Long.toString(value)));
return this;
}
#Override
public Editor putString(String key, String value) {
delegate.putString(key, encrypt(value));
return this;
}
#Override
public void apply() {
delegate.apply();
}
#Override
public Editor clear() {
delegate.clear();
return this;
}
#Override
public boolean commit() {
return delegate.commit();
}
#Override
public Editor remove(String s) {
delegate.remove(s);
return this;
}
}
public Editor edit() {
return new Editor();
}
#Override
public Map<String, ?> getAll() {
throw new UnsupportedOperationException(); // left as an exercise to the reader
}
#Override
public boolean getBoolean(String key, boolean defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Boolean.parseBoolean(decrypt(v)) : defValue;
}
#Override
public float getFloat(String key, float defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Float.parseFloat(decrypt(v)) : defValue;
}
#Override
public int getInt(String key, int defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Integer.parseInt(decrypt(v)) : defValue;
}
#Override
public long getLong(String key, long defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Long.parseLong(decrypt(v)) : defValue;
}
#Override
public String getString(String key, String defValue) {
final String v = delegate.getString(key, null);
return v != null ? decrypt(v) : defValue;
}
#Override
public boolean contains(String s) {
return delegate.contains(s);
}
#Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
#Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
protected String encrypt( String value ) {
try {
final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),UTF8);
} catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected String decrypt(String value){
try {
final byte[] bytes = value!=null ? Base64.decode(value,Base64.DEFAULT) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(pbeCipher.doFinal(bytes),UTF8);
} catch( Exception e) {
throw new RuntimeException(e);
}
}
}
About the simplest way to store a single preference in an Android Activity is to do something like this:
Editor e = this.getPreferences(Context.MODE_PRIVATE).edit();
e.putString("password", mPassword);
e.commit();
If you're worried about the security of these then you could always encrypt the password before storing it.
Using the snippet provided by Richard, you can encrypt the password before saving it. The preferences API however doesn't provide an easy way to intercept the value and encrypt it - you can block it being saved via an OnPreferenceChange listener, and you theoretically could modify it through a preferenceChangeListener, but that results in an endless loop.
I had earlier suggested adding a "hidden" preference in order to accomplish this. It's definitely not the best way. I'm going to present two other options that I consider to be more viable.
First, the simplest, is in a preferenceChangeListener, you can grab the entered value, encrypt it, and then save it to an alternative preferences file:
public boolean onPreferenceChange(Preference preference, Object newValue) {
// get our "secure" shared preferences file.
SharedPreferences secure = context.getSharedPreferences(
"SECURE",
Context.MODE_PRIVATE
);
String encryptedText = null;
// encrypt and set the preference.
try {
encryptedText = SimpleCrypto.encrypt(Preferences.SEED,(String)newValue);
Editor editor = secure.getEditor();
editor.putString("encryptedPassword",encryptedText);
editor.commit();
}
catch (Exception e) {
e.printStackTrace();
}
// always return false.
return false;
}
The second way, and the way I now prefer, is to create your own custom preference, extending EditTextPreference, #Override'ing the setText() and getText() methods, so that setText() encrypts the password, and getText() returns null.
Okay; it's been a while since the answer is kind-of mixed, but here's a few common answers. I researched this like crazy and it was hard to build a good answer
The MODE_PRIVATE method is considered generally safe, if you assume that the user didn't root the device. Your data is stored in plain text in a part of the file system that can only be accessed by the original program. This makings grabbing the password with another app on a rooted device easy. Then again, do you want to support rooted devices?
AES is still the best encryption you can do. Remember to look this up if you are starting a new implementation if it's been a while since I posted this. The largest issue with this is "What to do with the encryption key?"
So, now we are at the "What to do with the key?" portion. This is the hard part. Getting the key turns out to be not that bad. You can use a key derivation function to take some password and make it a pretty secure key. You do get into issues like "how many passes do you do with PKFDF2?", but that's another topic
Ideally, you store the AES key off the device. You have to figure out a good way to retrieve the key from the server safely, reliably, and securely though
You have a login sequence of some sort (even the original login sequence you do for remote access). You can do two runs of your key generator on the same password. How this works is that you derive the key twice with a new salt and a new secure initialization vector. You store one of those generated passwords on the device, and you use the second password as the AES key.
When you log in, you re-derive the key on the local login and compare it to the stored key. Once that is done, you use derive key #2 for AES.
Using the "generally safe" approach, you encrypt the data using AES and store the key in MODE_PRIVATE. This is recommended by a recent-ish Android blog post. Not incredibly secure, but way better for some people over plain text
You can do a lot of variations of these. For example, instead of a full login sequence, you can do a quick PIN (derived). The quick PIN might not be as secure as a full login sequence, but it's many times more secure than plain text
I know this is a little bit of necromancy, but you should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.
This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.
SampleSyncAdapter is an example that makes use of stored account credentials.
I'll throw my hat into the ring just to talk about securing passwords in general on Android. On Android, the device binary should be considered compromised - this is the same for any end application which is in direct user control. Conceptually, a hacker could use the necessary access to the binary to decompile it and root out your encrypted passwords and etc.
As such there's two suggestions I'd like to throw out there if security is a major concern for you:
1) Don't store the actual password. Store a granted access token and use the access token and the signature of the phone to authenticate the session server-side. The benefit to this is that you can make the token have a limited duration, you're not compromising the original password and you have a good signature that you can use to correlate to traffic later (to for instance check for intrusion attempts and invalidate the token rendering it useless).
2) Utilize 2 factor authentication. This may be more annoying and intrusive but for some compliance situations unavoidable.
This is a supplemental answer for those arriving here based on the question title (like I did) and don't need to deal with the security issues related to saving passwords.
How to use Shared Preferences
User settings are generally saved locally in Android using SharedPreferences with a key-value pair. You use the String key to save or look up the associated value.
Write to Shared Preferences
String key = "myInt";
int valueToSave = 10;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, valueToSave).commit();
Use apply() instead of commit() to save in the background rather than immediately.
Read from Shared Preferences
String key = "myInt";
int defaultValue = 0;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
int savedValue = sharedPref.getInt(key, defaultValue);
The default value is used if the key isn't found.
Notes
Rather than using a local key String in multiple places like I did above, it would be better to use a constant in a single location. You could use something like this at the top of your settings activity:
final static String PREF_MY_INT_KEY = "myInt";
I used an int in my example, but you can also use putString(), putBoolean(), getString(), getBoolean(), etc.
See the documentation for more details.
There are multiple ways to get SharedPreferences. See this answer for what to look out for.
You can also check out this little lib, containing the functionality you mention.
https://github.com/kovmarci86/android-secure-preferences
It is similar to some of the other aproaches here. Hope helps :)
This answer is based on a suggested approach by Mark. A custom version of the EditTextPreference class is created which converts back and forth between the plain text seen in the view and an encrypted version of the password stored in the preferences storage.
As has been pointed out by most who have answered on this thread, this is not a very secure technique, although the degree of security depends partly on the encryption/decryption code used. But it's fairly simple and convenient, and will thwart most casual snooping.
Here is the code for the custom EditTextPreference class:
package com.Merlinia.OutBack_Client;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
import android.util.Base64;
import com.Merlinia.MEncryption_Main.MEncryptionUserPassword;
/**
* This class extends the EditTextPreference view, providing encryption and decryption services for
* OutBack user passwords. The passwords in the preferences store are first encrypted using the
* MEncryption classes and then converted to string using Base64 since the preferences store can not
* store byte arrays.
*
* This is largely copied from this article, except for the encryption/decryption parts:
* https://groups.google.com/forum/#!topic/android-developers/pMYNEVXMa6M
*/
public class EditPasswordPreference extends EditTextPreference {
// Constructor - needed despite what compiler says, otherwise app crashes
public EditPasswordPreference(Context context) {
super(context);
}
// Constructor - needed despite what compiler says, otherwise app crashes
public EditPasswordPreference(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
// Constructor - needed despite what compiler says, otherwise app crashes
public EditPasswordPreference(Context context, AttributeSet attributeSet, int defaultStyle) {
super(context, attributeSet, defaultStyle);
}
/**
* Override the method that gets a preference from the preferences storage, for display by the
* EditText view. This gets the base64 password, converts it to a byte array, and then decrypts
* it so it can be displayed in plain text.
* #return OutBack user password in plain text
*/
#Override
public String getText() {
String decryptedPassword;
try {
decryptedPassword = MEncryptionUserPassword.aesDecrypt(
Base64.decode(getSharedPreferences().getString(getKey(), ""), Base64.DEFAULT));
} catch (Exception e) {
e.printStackTrace();
decryptedPassword = "";
}
return decryptedPassword;
}
/**
* Override the method that gets a text string from the EditText view and stores the value in
* the preferences storage. This encrypts the password into a byte array and then encodes that
* in base64 format.
* #param passwordText OutBack user password in plain text
*/
#Override
public void setText(String passwordText) {
byte[] encryptedPassword;
try {
encryptedPassword = MEncryptionUserPassword.aesEncrypt(passwordText);
} catch (Exception e) {
e.printStackTrace();
encryptedPassword = new byte[0];
}
getSharedPreferences().edit().putString(getKey(),
Base64.encodeToString(encryptedPassword, Base64.DEFAULT))
.commit();
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue)
getEditText().setText(getText());
else
super.onSetInitialValue(restoreValue, defaultValue);
}
}
This shows how it can be used - this is the "items" file that drives the preferences display. Note it contains three ordinary EditTextPreference views and one of the custom EditPasswordPreference views.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="#string/useraccountname_key"
android:title="#string/useraccountname_title"
android:summary="#string/useraccountname_summary"
android:defaultValue="#string/useraccountname_default"
/>
<com.Merlinia.OutBack_Client.EditPasswordPreference
android:key="#string/useraccountpassword_key"
android:title="#string/useraccountpassword_title"
android:summary="#string/useraccountpassword_summary"
android:defaultValue="#string/useraccountpassword_default"
/>
<EditTextPreference
android:key="#string/outbackserverip_key"
android:title="#string/outbackserverip_title"
android:summary="#string/outbackserverip_summary"
android:defaultValue="#string/outbackserverip_default"
/>
<EditTextPreference
android:key="#string/outbackserverport_key"
android:title="#string/outbackserverport_title"
android:summary="#string/outbackserverport_summary"
android:defaultValue="#string/outbackserverport_default"
/>
</PreferenceScreen>
As for the actual encryption/decryption, that is left as an exercise for the reader. I'm currently using some code based on this article http://zenu.wordpress.com/2011/09/21/aes-128bit-cross-platform-java-and-c-encryption-compatibility/, although with different values for the key and the initialization vector.
First of all I think User's data shouldn't be stored on phone, and if it is must to store data somewhere on the phone it should be encrypted with in the apps private data. Security of users credentials should be the priority of the application.
The sensitive data should be stored securely or not at all. In the event of a lost device or malware infection, data stored insecurely can be compromised.
I use the Android KeyStore to encrypt the password using RSA in ECB mode and then save it in the SharedPreferences.
When I want the password back I read the encrypted one from the SharedPreferences and decrypt it using the KeyStore.
With this method you generate a public/private Key-pair where the private one is safely stored and managed by Android.
Here is a link on how to do this: Android KeyStore Tutorial
As others already pointed out you can use SharedPreferences generally but if you would like to store data encrypted it's a bit inconvenient. Fortunately, there is an easier and quicker way to encrypt data now since there is an implementation of SharedPreferences that encrypts keys and values. You can use EncryptedSharedPreferences in Android JetPack Security.
Just add AndroidX Security into your build.gradle:
implementation 'androidx.security:security-crypto:1.0.0-rc01'
And you can use it like this:
String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
// use the shared preferences and editor as you normally would
SharedPreferences.Editor editor = sharedPreferences.edit();
See more details: https://android-developers.googleblog.com/2020/02/data-encryption-on-android-with-jetpack.html
Official docs: https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences
This is how I am doing it.
This does not give errors in strict mode.
public class UserPreferenceUtil
{
private static final String THEME = "THEME";
private static final String LANGUAGE = "LANGUAGE";
public static String getLanguagePreference(Context context)
{
String lang = getPreferenceByKey(context,LANGUAGE);
if( lang==null || "System".equalsIgnoreCase(lang))
{
return null;
}
return lang;
}
public static void saveLanguagePreference(Context context,String value)
{
savePreferenceKeyValue(context, LANGUAGE,value);
}
public static String getThemePreference(Context context)
{
return getPreferenceByKey(context,THEME);
}
public static void saveThemePreference(Context context, String value)
{
savePreferenceKeyValue(context,THEME,value);
}
public static String getPreferenceByKey(Context context, String preferenceKey )
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String value = sharedPreferences.getString(preferenceKey, null);
return value;
}
private static void savePreferenceKeyValue(Context context, String preferenceKey, String value)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceKey,value);
editor.apply();
}
}
My app does not need a password. However, rather than saving passwords or encrypted passwords, I would save a one-way hash. When the user logs in, I will hash the input the same way and match it with the stored hash.
you need to use the sqlite, security apit to store the passwords.
here is best example, which stores passwords, -- passwordsafe.
here is link for the source and explanation --
http://code.google.com/p/android-passwordsafe/
shared preferences is easiest way to store our application data. but it is possible that anyone can clear our shared preferences data through application manager.so i don't think it is completely safe for our application.

Using java.util.regex in Android apps - are there issues with this?

In an Android app I have a utility class that I use to parse strings for 2 regEx's. I compile the 2 patterns in a static initializer so they only get compiled once, then activities can use the parsing methods statically.
This works fine except that the first time the class is accessed and loaded, and the static initializer compiles the pattern, the UI hangs for close to a MINUTE while it compiles the pattern! After the first time, it flies on all subsequent calls to parseString().
My regEx that I am using is rather large - 847 characters, but in a normal java webapp this is lightning fast. I am testing this so far only in the emulator with a 1.5 AVD.
Could this just be an emulator issue or is there some other reason that this pattern is taking so long to compile?
private static final String exp1 = "(insertratherlong---847character--regexhere)";
private static Pattern regex1 = null;
private static final String newLineAndTagsExp = "[<>\\s]";
private static Pattern regexNewLineAndTags = null;
static {
regex1 = Pattern.compile(exp1, Pattern.CASE_INSENSITIVE);
regexNewLineAndTags = Pattern.compile(newLineAndTagsExp);
}
public static String parseString(CharSequence inputStr) {
String replacementStr = "replaceMentText";
String resultString = "none";
try {
Matcher regexMatcher = regex1.matcher(inputStr);
try {
resultString = regexMatcher.replaceAll(replacementStr);
} catch (IllegalArgumentException ex) {
} catch (IndexOutOfBoundsException ex) {
}
} catch (PatternSyntaxException ex) {
}
return resultString;
}
please file a reproduceable test case at http://code.google.com/p/android/issues/entry and i'll have a look. note that i will need a regular expression that reproduces the problem. (our regular expressions are implemented by ICU4C, so the compilation actually happens in native code and this may end up being an ICU bug, but if you file an Android bug i'll worry about upstream.)
If you launched with debugging you can expect it to be about twice as slow as a regular launch. However a minute does seem extraordinary. Some things to suggest, i. look at the console output to see if warnings are being spat out, ii. when it is doing the compile, in the debugger press 'pause' and just see what it is doing. There are ways to get the source, but even so just looking at the call stack may reveal something.

Categories

Resources