EncryptedPreferences


Source link: https://github.com/PDDStudio/EncryptedPreferences

EncryptedPreferences

An Android Library to securely read and write encrypted values to your SharedPreferences.

Reason & Explanation

When developing an Android application you often save primitive values to your application's internal storage using SharedPreferences.

All values written to your SharedPreferences are stored unencrypted in a simple and plain .xml file inside your application's internal directory. In case you save sensitive or important data here, it can be easily read (and modified) by users with a rooted phone. To avoid this, I created EncryptedPreferences.

EncryptedPreferences is a simple wrapper around the official SharedPreferences API, which saves all data (containing both, keys and values) encrypted using Advanced Encryption Standard (AES/256 bit key). The library takes care about all heavy lifting, so all you have to do is to read and write your preferences as usual.

EncryptedPreferences aims to have the same API as the official SharedPreferences, to make it as easy as possible to integrate it into your application.

Getting Started

Add the library as dependency

Add the library as dependency to your app's build.gradle file.

dependencies {

  compile 'com.pddstudio:encrypted-preferences:1.3.0' 
}
 

Make sure you're always using the latest version, which can be found on Maven Central.

Start using EncryptedPreferences

To start using EncryptedPreferences you have to create a new instance using the EncryptedPreferences.Builder.

Example:

EncryptedPreferences encryptedPreferences = new EncryptedPreferences.Builder(this).withEncryptionPassword("password").build();

Note: Starting with version 1.2.0 the support for default (password/key) configuration is deprecated due to security reasons. Therefore it's now required to specify your own password using the Builder's .withEncryptionPassword("password") method. If no password is set a RuntimeException will be thrown.

Once you created your EncryptedPreferences instance, you can read and write values.

Saving Values:

encryptedPreferences.edit()
.putString(TEST_KEY_VALUE_STRING, "testString")
.putFloat(TEST_KEY_VALUE_FLOAT, 1.5f)
.putLong(TEST_KEY_VALUE_LONG, 10L)
.putBoolean(TEST_KEY_VALUE_BOOLEAN, false)
.apply();

Note: As with the official SharedPreferences API, make sure to call apply() in order to save your changes!

Reading Values:

private void printValues() {
  Log.d("MainActivity", TEST_KEY_VALUE_STRING + " => " + encryptedPreferences.getString(TEST_KEY_VALUE_STRING, TEST_KEY_VALUE_STRING));
  Log.d("MainActivity", TEST_KEY_VALUE_FLOAT + " => " + encryptedPreferences.getFloat(TEST_KEY_VALUE_FLOAT, 0));
  Log.d("MainActivity", TEST_KEY_VALUE_LONG + " => " + encryptedPreferences.getLong(TEST_KEY_VALUE_LONG, 0));
  Log.d("MainActivity", TEST_KEY_VALUE_BOOLEAN + " => " + encryptedPreferences.getBoolean(TEST_KEY_VALUE_BOOLEAN, true));
 
}

Listening for Changes:

Beginning with version 1.2.0 it is possible to get notified when a value changed (added/updated/removed).

You can receive change events by implementing the EncryptedPreferences.OnSharedPreferenceChangeListener interface into your Activity/Fragment (or custom component). Make sure to respect your component's lifecycle and register/unregister the listener(s) to avoid unwanted behaviours.

@Override protected void onCreate() {
  super.onCreate();
  //some other stuff here...
 //register the listener  encryptedPreferences.registerOnSharedPreferenceChangeListener(this);
 
}

@Override protected void onDestroy() {
  //unregister the listener before destroying the Activity/Fragment  encryptedPreferences.unregisterOnSharedPreferenceChangeListener(this);
  super.onDestroy();
 
}
  @Override public void onSharedPreferenceChanged(EncryptedPreferences encryptedPreferences, String key) {
  //do your stuff with the changed data here  Log.d("MainActivity", "onSharedPreferenceChanged() => key: " + key);
 
}

For more information about how to read and write data to SharedPreferences, head over to the official Android Developer Guide.

Utilities:

Since version 1.0.1 EncryptedPreferences has a utility class, which might come in handy for several usecases beside persisting data. The EncryptedPreferences.Utils class is bound to your EncryptedPreferences instance and uses the same configuration.

You can retrieve the EncryptedPreferences.Utils instance by calling getUtils() on your EncryptedPreferences object.

Example:

private void utilsExample() {
  //get the encrypted value for an api key while debugging, so we don't have to save the original api key as plain text in production.  String encryptedApiKey = encryptedPreferences.getUtils().encryptStringValue("SOME_API_KEY_HERE");
  Log.d("MainActivity", "encryptedApiKey => " + encryptedApiKey);
  //in production we simply use the utility method with the encrypted value which we got from debugging.  String decryptedApiKey = encryptedPreferences.getUtils().decryptStringValue(encryptedApiKey);
  Log.d("MainActivity", "decryptedApiKey => " + decryptedApiKey);
 
}

Third-Party Libraries

This library is using AESCrypt-Android by scottyab.

About & Contact

  • In case you've a question feel free to hit me up via E-Mail (patrick.pddstudio[at]googlemail.com)
  • or Google+ / Hangouts

License


 Copyright 2016 Patrick J

Licensed under the Apache License, Version 2.0 (the "License");

  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. 

Resources

Description is not available now, but it is coming soon!

Android animated recording view.

Animation that creates a pentagon shape with showing buttons on the click of floating action button. This project illustrated the use case of ValueAnimator and how to create and add views dynamically.

A lightweight library which helps to create a view stack as a replacement for fragments and activities, provides transitions and persistence.

This library provides you an RTL Spinner with the Material style. You can use it like any regular Spinner. Add RTL floating label text, hint and error messages.

A powerful image picker which support multi mode and huge image.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes