ConcealSharedPreference


Source link: https://github.com/afiqiqmal/ConcealSharedPreference-Android

Conceal SharedPreferences Android

Project : Secure Android SharedPreferences Using Conceal Crypto by Facebook
Description
Conceal provides a set of Java APIs to perform cryptography on Android. It was designed to be able to encrypt large files on disk in a fast and memory efficient manner. Implementation on SharedPreferences of Android would be great data Encryption and Decryption. Currently supported Facebook Conceal V2.0

Installation

Gradle

dependencies {

compile 'com.github.afiqiqmal:ConcealSharedPreference-Android:1.3.0' 
}

Maven

<dependency>  <groupId>com.github.afiqiqmal</groupId>  <artifactId>ConcealSharedPreference-Android</artifactId>  <version>1.3.0</version> </dependency> 

Method

Usage

First of All

it needed to first init in Application class in oncreate method or on Base Activity Class. or everything is not working =D

ConcealPrefRepository.applicationInit(this, false);

Permission need to use in your project. Please Allow it first, or it will affect .putImage and .putFile method

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

SharedPreferences initialize

ConcealPrefRepository concealPrefRepository = new ConcealPrefRepository.PreferencesBuilder(this)

.useDefaultPrefStorage()

//.useThisPrefStorage("Android_Prefs")

.sharedPrefsBackedKeyChain(CryptoConfig.KEY_256)  //CryptoConfig.KEY_256 or CryptoConfig.KEY_128

.enableCrypto(true,true) //param 1 - enable value encryption , param 2 - enable key encryption

.createPassword("Android") //default value - BuildConfig.APPLICATION_ID

.setFolderName("testing") //create Folder for data stored: default is - "conceal_path"

.setPrefListener(this) // listen to data changes 

.create();
  *setFolderName - folder will be hidden. To see, enable show hidden folder in storage

 - data stored here only images and files

 - sharedpreferences are not store here

 - created folder by default YOURSTORAGE/.conceal_path/images

  - for images - in folder /images

 - for files - in folder /files 

Save data

concealPrefRepository.putString(KEY,"Hello");
 concealPrefRepository.putInt(KEY,1000000);
 concealPrefRepository.putDouble(KEY,100.00);
 concealPrefRepository.putbyte(KEY,new byte[]);
 concealPrefRepository.putMap(KEY,new Map<String,String>())  // Files and Images will be encrypted // prefix of this encrypted images and files start with "conceal_enc_"; File getFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/testing.pdf");
 concealPrefRepository.putFile(KEY,getFile,boolean deleteOldFiles);
 // deleteOldFiles - true or false.. true - will delete choosen file and move to new path  //put images concealPrefRepository.putImage(KEY, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
 concealPrefRepository.putImage(KEY, File file);
 ........... 

OR

new ConcealPrefRepository.Editor()

  .putString(KEY,"Hello")

  .putInt(KEY,1000000)

  .putBoolean(KEY,true)

  .putByte(KEY,new byte[])

  .putFile(KEY,getFile,boolean deleteOldFiles);

  .putImage(KEY, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

  .putImage(KEY, imageFile)

  .putListString(KEY,STRING_LIST)

  .putListFloat(KEY,FLOAT_LIST)

  .........

  .apply();
 //.commit();

Get total data

System.out.println(concealPrefRepository.getPrefsSize());

Get all sharedpreferences data

Map<String,String> getAll = concealPrefRepository.getAllSharedPrefData();

Get all encrypted Files inside created folder

List<CryptoFile> getFiles = concealPrefRepository.getAllConcealEncryptedFiles();

Fetching data

concealPrefRepository.getString(KEY);
 concealPrefRepository.getString(KEY,DEFAULT_VALUE);
 concealPrefRepository.getInt(KEY);
 concealPrefRepository.getInt(KEY,DEFAULT_VALUE);
 concealPrefRepository.getDouble(KEY);
 concealPrefRepository.getDouble(KEY,DEFAULT_VALUE);
 .....  Bitmap bitmap = concealPrefRepository.getImage(KEY);

//return String path File enc_file = concealPrefRepository.getFile(KEY,true);

 //return File // this getImage and getFile will totally decrypted selected file/image. You need to encrypt it back. // just call concealPrefRepository.putImage(KEY,bitmap);
 or concealPrefRepository.putFile(KEY,enc_file,true);
 ........

Clear key and SharedPreferences

concealPrefRepository.destroyCrypto();
 //clear key concealPrefRepository.destroySharedPreferences();
 // clear all  concealPrefRepository.remove(KEY1,KEY2,KEY3,KEY4) //String... keys concealPrefRepository.removeFile(KEY);
 //delete assosiate file (images and files) return boolean 

Check if key exists

concealPrefRepository.contains(KEY);
 // return boolean

Get SharedPreferences

concealPrefRepository.getPreferences();

Listener Data Changes

public class BaseActivity extends AppCompatActivity implements OnDataChangeListener{

  ....
  @Override
  public void onDataChange(String key,String value) {

 //code here
  
}
 
}

Easier Save User Detail Preferences

new ConcealPrefRepository.UserPref() .setFirstName("Firstname") .setLastName("Lasname") .setEmail("[email protected]") ..... .apply();

//get user details Log.d("TAG",new ConcealPrefRepository.UserPref().getFirstName());
 Log.d("TAG",new ConcealPrefRepository.UserPref().getLastName());
 Log.d("TAG",new ConcealPrefRepository.UserPref().getEmail());
 ..... 

Extra Usage for Conceal Encryption and Decryption

ConcealCrypto concealCrypto = new ConcealCrypto(this,CryptoConfig.KEY_256);
 // CryptoConfig.KEY_256 or CryptoConfig.KEY_128 concealCrypto.setEnableCrypto(true);
 //default true concealCrypto.setmEntityPassword("Android");
 concealCrypto.setmEntityPassword(Entity.create("Android"));
  String test = "Hello World"; String cipher =  concealCrypto.obscure(test);
 //encrypt String dec = concealCrypto.deObscure(cipher);
 //decrypt Log.d("Display", cipher+" ===== "+dec);
  String cipher =  concealCrypto.obscureWithIteration(test,4);
 //encrypt with 4 times iteration String dec = concealCrypto.deObscureWithIteration(cipher,4);
 //decrypt with 4 times iteration Log.d("Display", cipher+" ===== "+dec);

  

OR

ConcealCrypto concealCrypto1 = new ConcealCrypto.CryptoBuilder(this)

  .setEnableCrypto(true) //default true

  .setKeyChain(CryptoConfig.KEY_256) // CryptoConfig.KEY_256 or CryptoConfig.KEY_128

  .createPassword("Mac OSX")

.create();

String test = "Hello World"; String cipher =  concealCrypto.obscure(test);
 //encrypt String dec = concealCrypto.deObscure(cipher);
 //decrypt Log.d("Display", cipher+" ===== "+dec);

 String cipher =  concealCrypto.obscureWithIteration(test,4);
 //encrypt with 4 times iteration String dec = concealCrypto.deObscureWithIteration(cipher,4);
 //decrypt with 4 times iteration Log.d("Display", cipher+" ===== "+dec);

//special case for files and images concealCrypto.obscureFile(File file,boolean deleteOldFile);
 concealCrypto.deObscureFile(File file,boolean deleteOldFile);
 // 1-parameter is original location of file..it will move to other location set as in initialization  //if want to use hashing concealCrypto.hashKey(plaintext);
 // SHA-256 

Proguard

-keep,allowobfuscation @interface com.facebook.crypto.proguard.annotations.DoNotStrip -keep,allowobfuscation @interface com.facebook.crypto.proguard.annotations.KeepGettersAndSetters  # Do not strip any method/class that is annotated with @DoNotStrip -keep @com.facebook.crypto.proguard.annotations.DoNotStrip class * -keepclassmembers class * {

  @com.facebook.crypto.proguard.annotations.DoNotStrip *; 
}
  -keepclassmembers @com.facebook.crypto.proguard.annotations.KeepGettersAndSetters class * {

void set*(***);

*** get*();
 
}
 

Or more simpler proguard

-keep class com.facebook.** {
 *; 
}
 -keep interface com.facebook.** {
 *; 
}
 -dontwarn com.facebook.** 

Credit

Facebook Conceal - Conceal provides easy Android APIs for performing fast encryption and authentication of data.
Documentation - Here

Licence

open source project that is licensed under the MIT license. Please refer to the license file for more information.

Resources

Annotate methods to use as listeners for a sensor.

With this library you can implement RecyclerView.Adapter in a few lines.

Library for data transmission via sound waves, to facilitate the implementation of communication technology for sound waves by the programmers. This library prototype specifically makes the transformation and transmission of certain information into sound waves in the application that it is implemented and also makes the receipt of the same information transmitted.

A simple and reusable RecyclerView adapter.

This library wraps the Location APIs in RxJava 2 Observables, Singles, Maybes and Completables. No more managing GoogleApiClients! Also, the resolution of the location settings check is optionally handled by the lib.

Prevent screen from turning off until your user is looking at the screen.

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