Skip to content

Android Secure SharedPreferences Kotlin Using Facebook Conceal Encryption

License

Notifications You must be signed in to change notification settings

afiqiqmal/SharedChamber-Kotlin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

95 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Conceal SharedPreferences Android

API Android Arsenal

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.5.2'

        //or

        compile 'com.github.afiqiqmal:ConcealSharedPreference-Android:1.5.2' {
            exclude group: 'com.google.code.gson', module: 'gson'
        }
}

Maven

<dependency>
	<groupId>com.github.afiqiqmal</groupId>
	<artifactId>ConcealSharedPreference-Android</artifactId>
	<version>1.5.2</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);

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)
        //.useThisPrefStorage("Android_Prefs")
        .sharedPrefsBackedKeyChain(CryptoType.KEY_256)  //CryptoType.KEY_256 or CryptoType.KEY_128
        .enableCrypto(true,true) //param 1 - enable value encryption , param 2 - enable key encryption
        .enableKeyPrefix(true, "walaoweh") //1- if false, prefix will be ignore
        .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>());

//using gson
concealPrefRepository.putModel(KEY, new Gson().fromJson(loadJSONFromAsset(context, "users.json"), User.class));
concealPrefRepository.putModel(KEY, new Gson().fromJson(loadJSONFromAsset(context, "users.json"), new TypeToken<ArrayList<Users>>(){}.getType()));

// 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("PREFIX") // optional - get default from global prefix
                .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 sharedpreferences data in List String

List<String> getAll = concealPrefRepository.getAllSharedPrefDataToString();

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);

//using gson
concealPrefRepository.getModel(KEY, User.class).toString();
concealPrefRepository.getModel(KEY, new TypeToken<ArrayList<Task>>(){}.getType()).toString();
.....

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(); // need to apply() or commit()

or

ConcealPrefRepository.UserPref().applyFirstName("Firstname"); //directly apply
ConcealPrefRepository.UserPref().applyLastName("Firstname"); //directly apply

Get User Detail

new ConcealPrefRepository.UserPref().getFirstName()
new ConcealPrefRepository.UserPref().getLastName()
new ConcealPrefRepository.UserPref().getEmail()
.....

Key prefix - Apply key with prefix

new ConcealPrefRepository.UserPref("KEY PREFIX").setFirstName("Firstname").apply();
new ConcealPrefRepository.UserPref("KEY PREFIX").setLastName("Firstname").apply();

Extra Usage for Conceal Encryption and Decryption

ConcealCrypto concealCrypto = new ConcealCrypto(this,CryptoType.KEY_256); // CryptoType.KEY_256 or CryptoType.KEY_128
concealCrypto.setEnableValueEncryption(true); //default true
concealCrypto.setEnableKeyEncryption(true); //default true
concealCrypto.setmEntityPassword("Android");
concealCrypto.setmEntityPassword(Entity.create("Android"));

OR

ConcealCrypto concealCrypto = new ConcealCrypto.CryptoBuilder(this)
                .setEnableValueEncryption(true) //default true
                .setEnableKeyEncryption(true) // default true
                .setKeyChain(CryptoType.KEY_256) // CryptoType.KEY_256 or CryptoType.KEY_128
                .createPassword("Mac OSX")
                .create();

Hash

concealCrypto.hashKey(plaintext); // SHA-256

Encrypt

concealCrypto.obscure(test); // encrypt using facebook conceal
concealCrypto.obscureWithIteration(test,4); // encrypt using basic base64 with iteration
concealCrypto.aesEncrypt("Hello World is World Hello Aes Cryption"); // encrypt using AES

//1-parameter is original location of file..it will move to other location set as in initialization
concealCrypto.obscureFile(File file,boolean deleteOldFile);

Decrypt

concealCrypto.deObscure(cipher); // decrypt using facebook conceal
concealCrypto.deObscureWithIteration(cipher,4); // decrypt using basic base64 with iteration
concealCrypto.aesDecrypt(cipher); // decrypt using AES

concealCrypto.deObscureFile(File file,boolean deleteOldFile);

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.