scottyab / secure-preferences

Android Shared preference wrapper than encrypts the values of Shared Preferences. It's not bullet proof security but rather a quick win for incrementally making your android app more secure.
1.53k stars 235 forks source link

Handle prefs migration #33

Open scottyab opened 9 years ago

scottyab commented 9 years ago

Handle changes to key generation. As similar library does handle the migration of breaking changes with upgrade strategy simple to SQLlitehelper.onUpdate()

inktomi commented 8 years ago

This would be fantastic. It's hard to drop this into a pre-existing app as-is. Really simple implementation would be something like this (probably needing some updates around file names and such)

    SharedPreferences oldPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, 0);
    if( !oldPrefs.getAll().isEmpty() )
    {
        Logger.d("Converting old prefs to new ones.");
        // Move everything over.
        for(Map.Entry<String, ?> entry : oldPrefs.getAll().entrySet())
        {
            Object value = entry.getValue();

            if( value instanceof String )
            {
                editor.putString(entry.getKey(), (String) value);
            }
            else if( value instanceof Integer )
            {
                editor.putInt(entry.getKey(), (Integer) value);
            }
            else if( value instanceof Long )
            {
                editor.putLong(entry.getKey(), (Long) value);
            }
            else if( value instanceof Float )
            {
                editor.putFloat(entry.getKey(), (Float) value);
            }
            else if( value instanceof Boolean )
            {
                editor.putBoolean(entry.getKey(), (Boolean) value);
            }
            else if( value instanceof Set )
            {
                editor.putStringSet(entry.getKey(), (Set<String>) value);
            }
            else if ( sLoggingEnabled )
            {
                Log.e(TAG, "Unknown key type for key " + entry.getKey());
            }
        }

        editor.commit();

        // Clear old prefs.
        oldPrefs.edit().clear().commit();
    }