Android Secure SharedPreferences Using Facebook Conceal Encryption

Overview

SharedChamber Android

API Donate

Project : SharedChamber on top of SharedPreferences using Facebook Conceal
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 {
        implementation 'com.github.afiqiqmal:SharedChamber:2.5.1'

        //or

        implementation 'com.github.afiqiqmal:SharedChamber:2.5.1' {
            exclude group: 'com.google.code.gson', module: 'gson'
        }
}

Maven

<dependency>
	<groupId>com.github.afiqiqmal</groupId>
	<artifactId>SharedChamber</artifactId>
	<version>2.5.0</version>
</dependency>

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

SharedChamber.initChamber(this);

Permission need to use in your project. Please Allow it first if you need to use file save, 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"/>
Initialize
SharedChamber sharedChamber = new SharedChamber.ChamberBuilder(this)
        //.useThisPrefStorage("Android_Prefs")
        .setChamberType(ChamberType.KEY_256)  //ChamberType.KEY_256 or ChamberType.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
        .setPassword("Android") //default value - BuildConfig.APPLICATION_ID
        .setFolderName("testing") //create Folder for data stored: default is - "conceal_path"
        .setPrefListener(this) // listen to data changes 
        .buildChamber();

*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
sharedChamber.put(KEY,"Hello");
sharedChamber.put(KEY,1000000);
sharedChamber.put(KEY,100.00);
sharedChamber.put(KEY,new byte[]);
sharedChamber.put(KEY,new Map<String,String>());
...
...

for complex object might need use putModel which use gson

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

Files and Images

// 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");
sharedChamber.putFile(KEY,getFile,boolean deleteOldFiles);
// deleteOldFiles - true or false.. true - will delete choosen file and move to new path

//put images
sharedChamber.put(KEY, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
sharedChamber.put(KEY, File file);
sharedChamber.putDrawable(KEY, Drawable ID);
...
...
For Method Chaining
new SharedChamber.Editor("PREFIX") // optional - get default from global prefix
                .put(KEY,"Hello")
                .put(KEY,1000000)
                .put(KEY,true)
                .put(KEY,new byte[])
                .put(KEY,getFile,boolean deleteOldFiles);
                .put(KEY, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .put(KEY, imageFile)
                .put(KEY,STRING_LIST)
                .put(KEY,FLOAT_LIST)
		.putModel(KEY, new Gson().fromJson(loadJSONFromAsset(context, "users.json"), User.class));
                ...
                ...
                .apply(); //.commit();
Get total data
System.out.println(sharedChamber.getPrefsSize());
Get all sharedpreferences data
Map<String,String> getAll = sharedChamber.getEverythingInChamberInMap();
Get all sharedpreferences data in List String
List<String> getAll = sharedChamber.getEverythingInChamberInList();
Get all encrypted Files inside created folder
List<CryptoFile> getFiles = sharedChamber.getAllChamberFiles();
Fetching data
sharedChamber.getString(KEY);
sharedChamber.getString(KEY,DEFAULT_VALUE);
sharedChamber.getInt(KEY);
sharedChamber.getInt(KEY,DEFAULT_VALUE);
sharedChamber.getDouble(KEY);
sharedChamber.getDouble(KEY,DEFAULT_VALUE);

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

Bitmap bitmap = sharedChamber.getImage(KEY);   //return String path
File enc_file = sharedChamber.getFile(KEY,true);    //return File
// this getImage and getFile will totally decrypted selected file/image. You need to encrypt it back.
// just call sharedChamber.putImage(KEY,bitmap); or sharedChamber.putFile(KEY,enc_file,true);
........
Clear key and SharedPreferences
sharedChamber.destroyChamber(); //clear key
sharedChamber.clearChamber(); // clear all

sharedChamber.remove(KEY1,KEY2,KEY3,KEY4) //String... keys
sharedChamber.removeFile(KEY); //delete assosiate file (images and files) return boolean
Check if key exists
sharedChamber.contains(KEY); // return boolean
Get SharedPreferences
sharedChamber.getChamber();
Listener Data Changes
public class BaseActivity extends AppCompatActivity implements OnDataChamberChangeListener{
    ....
    @Override
    public void onDataChange(String key,String value) {
         //code here
    }
}
Easier Save User Detail Preferences
new SharedChamber.UserChamber()
.setFirstName("Firstname")
.setLastName("Lasname")
.setEmail("[email protected]")
.....
.apply(); // need to apply() or commit()

or

SharedChamber.UserChamber().applyFirstName("Firstname"); //directly apply
SharedChamber.UserChamber().applyLastName("Firstname"); //directly apply
Get User Detail
new SharedChamber.UserChamber().getFirstName()
new SharedChamber.UserChamber().getLastName()
new SharedChamber.UserChamber().getEmail()
.....
Key prefix - Apply key with prefix
new SharedChamber.UserChamber("KEY PREFIX").setFirstName("Firstname").apply();
new SharedChamber.UserChamber("KEY PREFIX").setLastName("Firstname").apply();

Extra Usage for Conceal Encryption and Decryption

SecretChamber secretChamber = new SecretBuilder(this)
                .setEnableValueEncryption(true) //default true
                .setEnableKeyEncryption(true) // default true
                .setChamberType(ChamberType.KEY_256) // ChamberType.KEY_256 or ChamberType.KEY_128
                .setPassword("Mac OSX")
                .buildSecret();
Hash
secretChamber.vaultHash(plaintext); // SHA-256
Encrypt
secretChamber.lockVault(test); // encrypt using facebook conceal
secretChamber.lockVaultBase(test,4); // encrypt using basic base64 with iteration
secretChamber.lockVaultAes("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
secretChamber.lockVaultFile(File file,boolean deleteOldFile);

Decrypt
secretChamber.openVault(cipher); // decrypt using facebook conceal
secretChamber.openVaultBase(cipher,4); // decrypt using basic base64 with iteration
secretChamber.openVaultAes(cipher); // decrypt using AES

secretChamber.openVaultFile(File file,boolean deleteOldFile);

Proguard

-keep class com.facebook.crypto.** { *; }
-keep class com.facebook.jni.** { *; }
-keepclassmembers class com.facebook.cipher.jni.** { *; }
-dontwarn com.facebook.**

TODO

  1. Set Preferences for specific user
  2. Able to switch Preferences between user

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.

You might also like...
Android injection using the Anvil compiler plugin

Tangle creates Dagger bindings for Android classes using the Anvil Kotlin compiler plugin. This is meant to be an alternative to Hilt, for those who'd prefer to enjoy the faster compilation and better flexibility of Anvil.

A simple library for validating user input in forms using annotations.
A simple library for validating user input in forms using annotations.

ValidationKomensky for Android A simple library for validating user input in forms using annotations. Features: Validate all views at once and show fe

This project is an add-on for the excellent J2V8 Project. It allows users to debug JS running in V8 using Chrome DevTools. Uses Stetho for communication with Chrome DevTools.

J2V8-Debugger This project is an add-on for the excellent J2V8 Project. It allows users to debug JS running in V8 using Chrome DevTools. Uses Stetho f

Generate helper methods for compose navigation using KSP

Compose NavGen Generate helper methods for compose navigation using KSP. 🚧 You can try it now, but it's still under development. 🚧 TODO Support defa

Extensions to encrypt DataStore using Tink

encrypted-datastore Extensions to encrypt DataStore using Tink. ⚠️ This tiny library will be maintained until an official solution for DataStore encry

Format numbers using a string pattern with this simple number formatted like ##-####-##

AndroidPattern Format numbers using a string pattern with this simple number formatted like ##-####-## Installation To get a Git project into your bui

DEMOMovieDB - Client App using movieDB with Kotlin
DEMOMovieDB - Client App using movieDB with Kotlin

DEMOMovieDB DEMOMovieDB is a gorgeous client application for TMDb on Android, bu

λRPC allows using code with high-order functions as a service
λRPC allows using code with high-order functions as a service

λRPC Simple native RPC with high order functions support. Inspired by @altavir and Communicator. λRPC allows using code with high-order functions as a

A universal memory dumper using Frida

Fridump Fridump (v0.1) is an open source memory dumping tool, primarily aimed to penetration testers and developers. Fridump is using the Frida framew

Comments
  • keeping a reference to the context statically

    keeping a reference to the context statically

    Hi, i may have it wrong, but from the code it seems like the context passed to the PreferencesBuilder is saved statically inside ConcealPrefRepository.concealCrypto. this may cause memory issues since the context will not be released. you may want to use the application context or a weak reference perhaps.

    opened by itaybia 0
  • Cannot get nativeLoad method

    Cannot get nativeLoad method

    I found this error when the app initialize.

    Cannot get nativeLoad method
        java.lang.NoSuchMethodException: nativeLoad [class java.lang.String, class java.lang.ClassLoader, class java.lang.String]
        at java.lang.Class.getMethod(Class.java:2068)
            at java.lang.Class.getDeclaredMethod(Class.java:2047)
            at com.facebook.soloader.SoLoader.getNativeLoadRuntimeMethod(SoLoader.java:297)
            at com.facebook.soloader.SoLoader.initSoLoader(SoLoader.java:249)
            at com.facebook.soloader.SoLoader.initImpl(SoLoader.java:156)
            at com.facebook.soloader.SoLoader.init(SoLoader.java:131)
            at com.facebook.soloader.SoLoader.init(SoLoader.java:115)
            at com.facebook.soloader.SoLoader.init(SoLoader.java:142)
            at com.chamber.java.library.SharedChamber.initChamber(SharedChamber.java:86)
    

    it might be similar to this? https://github.com/facebook/fresco/issues/2115

    help wanted 
    opened by yoesdinar 3
  • Manifest merger failed with multiple errors!!

    Manifest merger failed with multiple errors!!

    Gradle build failed with error message "Manifest merger failed with multiple errors" My App's manifest has allow_backup property set to false which conflicts with this library.

    I feel you dont need to specify allow_backup because you are writing a library!!

    help wanted 
    opened by nag-dbs 0
  • repository is needed

    repository is needed

    It would be helpful to add this piece of code on Installation :)

    allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }
    
    help wanted 
    opened by turastory 0
Releases(2.6.0)
Owner
Hafiq
Android | Laravel | NuxtJs | Senior Software Engineer
Hafiq
Expirable Disk Lru Cache is a secure(with encryption) wrapper for [DiskLruCache](https://github.com/JakeWharton/DiskLruCache) that allows expiring of key/value pairs by specifying evictionTimeSpan. It has very simple API.

ExpirableDiskLruCache ExpirableDiskLruCache is a wrapper for DiskLruCache that allows expiring of key/value pairs by specifying evictionTimeSpan. It h

Vijay Rawat 24 Oct 3, 2022
A lightweight library for config and using SharedPreferences

preferences-helper SharePreferences is very popular with any project and all most all project has SharePreferences for saving data. This library will

Khang Tran 23 May 8, 2021
a SharedPreferences replacement for Android with multiprocess support

DEPRECATED - no longer actively maintained Tray - a SharedPreferences replacement for Android If you have read the documentation of the SharedPreferen

HCI @ gcx 2.3k Nov 17, 2022
Recover deleted messages for whatsapp and Facebook lets you recover messages that sender deleted

Recover deleted messages for whatsapp and Facebook lets you recover messages that sender deleted. It also recover deleted media Images, Audio, Video etc

S M Khurram Khan 6 Jul 17, 2022
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.

Secure-preferences - Deprecated Please use EncryptedSharedPreferences from androidx.security in preferenced to secure-preference. (There are no active

Scott Alexander-Bown 1.5k Dec 24, 2022
✔️ Secure, simple key-value storage for Android

Hawk 2.0 Secure, simple key-value storage for android Important Note This version has no backward compatibility with Hawk 1+ versions. If you still wa

Orhan Obut 3.9k Dec 20, 2022
Android library to easily serialize and cache your objects to disk using key/value pairs.

Deprecated This project is no longer maintained. No new issues or pull requests will be accepted. You can still use the source or fork the project to

Anup Cowkur 667 Dec 22, 2022
A set of helper classes for using dagger 1 with Android components such as Applications, Activities, Fragments, BroadcastReceivers, and Services.

##fb-android-dagger A set of helper classes for using dagger with Android components such as Applications, Activities, Fragments, BroadcastReceivers,

Andy Dennie 283 Nov 11, 2022
Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platform the code is running.

Trail Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platfor

Mauricio Togneri 13 Aug 29, 2022
recompose is a tool for converting Android layouts in XML to Kotlin code using Jetpack Compose.

recompose is a tool for converting Android layouts in XML to Kotlin code using Jetpack Compose.

Sebastian Kaspari 565 Jan 2, 2023