├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── styles.xml │ │ │ │ └── dimens.xml │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ ├── layout │ │ │ │ ├── row_user.xml │ │ │ │ └── activity_main.xml │ │ │ └── menu │ │ │ │ └── menu_main.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── net │ │ │ └── rehacktive │ │ │ └── waspdbexample │ │ │ ├── User.java │ │ │ ├── UserAdapter.java │ │ │ └── MainActivity.java │ └── androidTest │ │ └── java │ │ └── net │ │ └── rehacktive │ │ └── waspdbexample │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── waspdb ├── .gitignore ├── libs │ └── commons-io-2.4.jar ├── src │ ├── main │ │ ├── res │ │ │ └── values │ │ │ │ └── strings.xml │ │ ├── java │ │ │ └── net │ │ │ │ └── rehacktive │ │ │ │ └── waspdb │ │ │ │ ├── WaspObserver.java │ │ │ │ ├── internals │ │ │ │ ├── collision │ │ │ │ │ ├── exceptions │ │ │ │ │ │ ├── KeyNotFoundException.java │ │ │ │ │ │ └── KeyAlreadyExistsException.java │ │ │ │ │ ├── WaspDataPage.java │ │ │ │ │ ├── CipherManager.java │ │ │ │ │ ├── KryoStoreUtils.java │ │ │ │ │ └── CollisionHash.java │ │ │ │ └── utils │ │ │ │ │ ├── Salt.java │ │ │ │ │ └── Utils.java │ │ │ │ ├── WaspListener.java │ │ │ │ ├── WaspObservable.java │ │ │ │ ├── WaspHash.java │ │ │ │ ├── WaspDb.java │ │ │ │ └── WaspFactory.java │ │ └── AndroidManifest.xml │ └── androidTest │ │ └── java │ │ └── net │ │ └── rehacktive │ │ └── waspdb │ │ ├── User.java │ │ ├── UserWithNestedContent.java │ │ └── MainTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── images ├── hypercube.png └── wasp_comparison.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE.txt /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /waspdb/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':waspdb' 2 | -------------------------------------------------------------------------------- /images/hypercube.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/images/hypercube.png -------------------------------------------------------------------------------- /images/wasp_comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/images/wasp_comparison.png -------------------------------------------------------------------------------- /waspdb/libs/commons-io-2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/waspdb/libs/commons-io-2.4.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /waspdb/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | WaspDb 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rehacktive/waspdb/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /.idea/* 3 | *.iml 4 | .gradle 5 | /local.properties 6 | /.idea/workspace.xml 7 | /.idea/libraries 8 | .DS_Store 9 | /build 10 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | WaspDbExample 3 | 4 | Hello world! 5 | Settings 6 | 7 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/WaspObserver.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | /** 4 | * Created by stefano on 17/03/2015. 5 | */ 6 | public interface WaspObserver { 7 | 8 | void onChange(); 9 | } 10 | -------------------------------------------------------------------------------- /waspdb/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue May 10 18:13:21 BST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip 7 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/collision/exceptions/KeyNotFoundException.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.collision.exceptions; 2 | 3 | public class KeyNotFoundException extends Exception { 4 | 5 | public KeyNotFoundException(String string) { 6 | super(string); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/collision/exceptions/KeyAlreadyExistsException.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.collision.exceptions; 2 | 3 | public class KeyAlreadyExistsException extends Exception { 4 | 5 | public KeyAlreadyExistsException(String string) { 6 | super(string); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/WaspListener.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import android.util.Log; 4 | 5 | /** 6 | * Created by stefano on 17/03/2015. 7 | */ 8 | public abstract class WaspListener { 9 | 10 | abstract public void onDone(T ret); 11 | 12 | public void onError(String error) { 13 | Log.d("WASPDB", "" + error); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/utils/Salt.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.utils; 2 | 3 | /** 4 | * Created by stefano on 20/07/2015. 5 | */ 6 | public class Salt { 7 | 8 | private byte[] salt; 9 | 10 | public Salt() { 11 | } 12 | 13 | public Salt(byte[] salt) { 14 | this.salt = salt; 15 | } 16 | 17 | public byte[] getSalt() { 18 | return salt; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/src/androidTest/java/net/rehacktive/waspdbexample/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdbexample; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/row_user.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 4 | 6 | 8 | 9 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/collision/WaspDataPage.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.collision; 2 | 3 | /** 4 | * Created by stefano on 14/06/2016. 5 | */ 6 | 7 | public class WaspDataPage { 8 | 9 | private byte[] iv; 10 | private byte[] data; 11 | 12 | public WaspDataPage() { 13 | } 14 | 15 | public byte[] getIv() { 16 | return iv; 17 | } 18 | 19 | public void setIv(byte[] iv) { 20 | this.iv = iv; 21 | } 22 | 23 | public byte[] getData() { 24 | return data; 25 | } 26 | 27 | public void setData(byte[] data) { 28 | this.data = data; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/stefano/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /waspdb/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/stefano/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 9 | 10 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 22 5 | buildToolsVersion "21.1.2" 6 | 7 | defaultConfig { 8 | applicationId "net.rehacktive.waspdbexample" 9 | minSdkVersion 14 10 | targetSdkVersion 22 11 | versionCode 2 12 | versionName "1.1" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | 21 | 22 | lintOptions { 23 | abortOnError false 24 | } 25 | } 26 | 27 | dependencies { 28 | compile fileTree(dir: 'libs', include: ['*.jar']) 29 | compile 'com.android.support:appcompat-v7:22.0.0' 30 | compile project(':waspdb') 31 | } 32 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /app/src/main/java/net/rehacktive/waspdbexample/User.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdbexample; 2 | 3 | /** 4 | * Created by stefano on 28/07/2015. 5 | */ 6 | public class User { 7 | 8 | private String id; 9 | private String user_name; 10 | private String email; 11 | 12 | public User() { 13 | } 14 | 15 | public User(String username, String email) { 16 | this.user_name = username; 17 | this.email = email; 18 | this.id = ""+System.currentTimeMillis(); 19 | } 20 | 21 | public String getId() { 22 | return id; 23 | } 24 | 25 | public void setId(String id) { 26 | this.id = id; 27 | } 28 | 29 | public String getUser_name() { 30 | return user_name; 31 | } 32 | 33 | public void setUser_name(String user_name) { 34 | this.user_name = user_name; 35 | } 36 | 37 | public String getEmail() { 38 | return email; 39 | } 40 | 41 | public void setEmail(String email) { 42 | this.email = email; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/WaspObservable.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by stefano on 17/03/2015. 8 | */ 9 | public class WaspObservable { 10 | 11 | List observers; 12 | 13 | public void register(WaspObserver observer) { 14 | if (observers == null) 15 | observers = new ArrayList<>(); 16 | 17 | if (!observers.contains(observer)) 18 | observers.add(observer); 19 | } 20 | 21 | public void unregister(WaspObserver observer) { 22 | if (observers == null) return; 23 | 24 | observers.remove(observer); 25 | } 26 | 27 | public void notifyObservers() { 28 | try { 29 | if (observers == null) return; 30 | 31 | for (WaspObserver observer : observers) { 32 | if (observer != null) observer.onChange(); 33 | 34 | } 35 | } 36 | catch (Exception e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /waspdb/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | } 8 | 9 | android { 10 | packagingOptions { 11 | exclude 'META-INF/DEPENDENCIES.txt' 12 | exclude 'META-INF/LICENSE.txt' 13 | exclude 'META-INF/NOTICE.txt' 14 | exclude 'META-INF/NOTICE' 15 | exclude 'META-INF/LICENSE' 16 | exclude 'META-INF/DEPENDENCIES' 17 | exclude 'META-INF/notice.txt' 18 | exclude 'META-INF/license.txt' 19 | exclude 'META-INF/dependencies.txt' 20 | exclude 'META-INF/LGPL2.1' 21 | } 22 | 23 | compileSdkVersion 22 24 | buildToolsVersion "21.1.2" 25 | 26 | defaultConfig { 27 | minSdkVersion 14 28 | targetSdkVersion 22 29 | versionCode 1 30 | versionName "1.0" 31 | } 32 | 33 | lintOptions { 34 | abortOnError false 35 | } 36 | 37 | compileOptions { 38 | sourceCompatibility JavaVersion.VERSION_1_7 39 | targetCompatibility JavaVersion.VERSION_1_7 40 | } 41 | buildTypes { 42 | debug { 43 | buildConfigField "boolean", "IS_DEBUG", "true" 44 | } 45 | 46 | release { 47 | minifyEnabled false 48 | buildConfigField "boolean", "IS_DEBUG", "false" 49 | } 50 | } 51 | } 52 | 53 | dependencies { 54 | compile fileTree(dir: 'libs', include: ['*.jar']) 55 | compile 'com.esotericsoftware:kryo:3.0.3' 56 | } 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /waspdb/src/androidTest/java/net/rehacktive/waspdb/User.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | /** 4 | * Created by stefano on 17/03/2015. 5 | */ 6 | public class User { 7 | 8 | private int id; 9 | private String username; 10 | private String telephone; 11 | 12 | public User() { 13 | } 14 | 15 | public User(int id, String username, String telephone) { 16 | this.id = id; 17 | this.username = username; 18 | this.telephone = telephone; 19 | } 20 | 21 | public int getId() { 22 | return id; 23 | } 24 | 25 | public void setId(int id) { 26 | this.id = id; 27 | } 28 | 29 | public String getUsername() { 30 | return username; 31 | } 32 | 33 | public void setUsername(String username) { 34 | this.username = username; 35 | } 36 | 37 | public String getTelephone() { 38 | return telephone; 39 | } 40 | 41 | public void setTelephone(String telephone) { 42 | this.telephone = telephone; 43 | } 44 | 45 | @Override 46 | public boolean equals(Object o) { 47 | if (this == o) return true; 48 | if (o == null || getClass() != o.getClass()) return false; 49 | 50 | User user = (User) o; 51 | 52 | if (id != user.id) return false; 53 | if (telephone != null ? !telephone.equals(user.telephone) : user.telephone != null) 54 | return false; 55 | if (username != null ? !username.equals(user.username) : user.username != null) 56 | return false; 57 | 58 | return true; 59 | } 60 | 61 | @Override 62 | public int hashCode() { 63 | int result = id; 64 | result = 31 * result + (username != null ? username.hashCode() : 0); 65 | result = 31 * result + (telephone != null ? telephone.hashCode() : 0); 66 | return result; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /app/src/main/java/net/rehacktive/waspdbexample/UserAdapter.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdbexample; 2 | 3 | import android.content.Context; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.widget.BaseAdapter; 8 | import android.widget.TextView; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * Created by stefano on 31/07/2015. 14 | */ 15 | public class UserAdapter extends BaseAdapter { 16 | 17 | private List users; 18 | 19 | LayoutInflater mInflator; 20 | 21 | Context mContext; 22 | 23 | public UserAdapter(Context context) { 24 | mContext = context; 25 | mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 26 | } 27 | 28 | public void setUsers(List users) { 29 | this.users = users; 30 | } 31 | 32 | @Override 33 | public int getCount() { 34 | return users != null ? users.size() : 0; 35 | } 36 | 37 | @Override 38 | public User getItem(int i) { 39 | return users.get(i); 40 | } 41 | 42 | @Override 43 | public long getItemId(int i) { 44 | return i; 45 | } 46 | 47 | @Override 48 | public View getView(int position, View convertView, ViewGroup container) { 49 | 50 | Viewholder holder; 51 | 52 | final User t = getItem(position); 53 | 54 | if (convertView == null) { 55 | holder = new Viewholder(); 56 | convertView = mInflator.inflate(R.layout.row_user, container, false); 57 | holder.username = (TextView) convertView.findViewById(R.id.username); 58 | convertView.setTag(holder); 59 | 60 | } else { 61 | holder = (Viewholder) convertView.getTag(); 62 | } 63 | 64 | holder.username.setText(t.getUser_name()); 65 | 66 | return convertView; 67 | } 68 | 69 | private class Viewholder { 70 | TextView username; 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/utils/Utils.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.utils; 2 | 3 | import net.rehacktive.waspdb.internals.collision.CipherManager; 4 | 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.security.MessageDigest; 8 | import java.security.NoSuchAlgorithmException; 9 | import java.security.SecureRandom; 10 | 11 | import javax.crypto.SecretKeyFactory; 12 | 13 | 14 | public class Utils { 15 | 16 | public static String md5(String s) throws NoSuchAlgorithmException { 17 | MessageDigest messageDigest; 18 | try { 19 | messageDigest = MessageDigest.getInstance("MD5"); 20 | messageDigest.reset(); 21 | messageDigest.update(s.getBytes()); 22 | byte[] resultByte = messageDigest.digest(); 23 | String result = toHexString(resultByte); 24 | return result; 25 | } catch (NoSuchAlgorithmException e) { 26 | e.printStackTrace(); 27 | throw e; 28 | } 29 | } 30 | 31 | public static String toHexString(byte[] bytes) { 32 | char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; 33 | char[] hexChars = new char[bytes.length * 2]; 34 | int v; 35 | for ( int j = 0; j < bytes.length; j++ ) { 36 | v = bytes[j] & 0xFF; 37 | hexChars[j*2] = hexArray[v/16]; 38 | hexChars[j*2 + 1] = hexArray[v%16]; 39 | } 40 | return new String(hexChars); 41 | } 42 | 43 | public static boolean isEmpty(String s) { 44 | return s==null || s.trim().equals(""); 45 | } 46 | 47 | public static boolean checkForCryptoAvailable() { 48 | try { 49 | // Security.addProvider(new BouncyCastleProvider()); 50 | // for(String s : Security.getAlgorithms("Cipher")) 51 | // System.out.println(s); 52 | SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(CipherManager.key_algorithm); 53 | return true; 54 | } catch (NoSuchAlgorithmException e) { 55 | return false; 56 | } 57 | } 58 | 59 | public static boolean deleteRecursive(File path) throws FileNotFoundException { 60 | if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath()); 61 | boolean ret = true; 62 | if (path.isDirectory()){ 63 | for (File f : path.listFiles()){ 64 | ret = ret && deleteRecursive(f); 65 | } 66 | } 67 | return ret && path.delete(); 68 | } 69 | 70 | 71 | public static Salt generateSalt() { 72 | SecureRandom sr = new SecureRandom(); 73 | byte[] output = new byte[256]; 74 | sr.nextBytes(output); 75 | return new Salt(output); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /waspdb/src/androidTest/java/net/rehacktive/waspdb/UserWithNestedContent.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by stefano on 17/03/2015. 8 | */ 9 | public class UserWithNestedContent { 10 | 11 | public static int NUMBER_OF_FRIENDS = 20; 12 | 13 | private int id; 14 | private String username; 15 | private String telephone; 16 | private List friends; 17 | 18 | public UserWithNestedContent() { 19 | } 20 | 21 | public UserWithNestedContent(int id, String username, String telephone) { 22 | this.id = id; 23 | this.username = username; 24 | this.telephone = telephone; 25 | // generate list of friends 26 | this.friends = new ArrayList<>(); 27 | for (int i = 0; i < NUMBER_OF_FRIENDS; i++) { 28 | User p = new User(i, "test"+i, "123"); 29 | friends.add(p); 30 | } 31 | } 32 | 33 | public int getId() { 34 | return id; 35 | } 36 | 37 | public void setId(int id) { 38 | this.id = id; 39 | } 40 | 41 | public String getUsername() { 42 | return username; 43 | } 44 | 45 | public void setUsername(String username) { 46 | this.username = username; 47 | } 48 | 49 | public String getTelephone() { 50 | return telephone; 51 | } 52 | 53 | public void setTelephone(String telephone) { 54 | this.telephone = telephone; 55 | } 56 | 57 | public List getFriends() { 58 | return friends; 59 | } 60 | 61 | public void setFriends(List friends) { 62 | this.friends = friends; 63 | } 64 | 65 | @Override 66 | public boolean equals(Object o) { 67 | if (this == o) return true; 68 | if (o == null || getClass() != o.getClass()) return false; 69 | 70 | UserWithNestedContent person = (UserWithNestedContent) o; 71 | 72 | if (id != person.id) return false; 73 | if (telephone != null ? !telephone.equals(person.telephone) : person.telephone != null) 74 | return false; 75 | if (username != null ? !username.equals(person.username) : person.username != null) 76 | return false; 77 | 78 | return true; 79 | } 80 | 81 | @Override 82 | public int hashCode() { 83 | int result = id; 84 | result = 31 * result + (username != null ? username.hashCode() : 0); 85 | result = 31 * result + (telephone != null ? telephone.hashCode() : 0); 86 | return result; 87 | } 88 | 89 | @Override 90 | public String toString() { 91 | return "UserWithNestedContent{" + 92 | "id=" + id + 93 | ", username='" + username + '\'' + 94 | '}'; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/collision/CipherManager.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.collision; 2 | 3 | import java.security.InvalidAlgorithmParameterException; 4 | import java.security.InvalidKeyException; 5 | import java.security.Key; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.security.spec.InvalidKeySpecException; 8 | import java.security.spec.KeySpec; 9 | 10 | import javax.crypto.Cipher; 11 | import javax.crypto.NoSuchPaddingException; 12 | import javax.crypto.SecretKey; 13 | import javax.crypto.SecretKeyFactory; 14 | import javax.crypto.spec.IvParameterSpec; 15 | import javax.crypto.spec.PBEKeySpec; 16 | import javax.crypto.spec.SecretKeySpec; 17 | 18 | 19 | /** 20 | * Created by stefano on 06/08/2014. 21 | */ 22 | public class CipherManager { 23 | 24 | private int ITERATIONS = 10000; 25 | private int KEYSIZE = 256; 26 | 27 | public static String cipher_algorithm = "AES/CBC/PKCS7PADDING"; 28 | public static String key_algorithm = "PBKDF2WithHmacSHA1"; 29 | public static String secretKeyAlgorithm = "AES"; 30 | 31 | protected Key key; 32 | 33 | protected static CipherManager instance = null; 34 | 35 | private CipherManager() { 36 | // Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); 37 | // Provider[] providers = Security.getProviders(); 38 | // for (Provider provider : providers) { 39 | // Log.i("CRYPTO","provider: "+provider.getName()); 40 | // Set services = provider.getServices(); 41 | // for (Provider.Service service : services) { 42 | // Log.i("CRYPTO"," key_algorithm: "+service.getAlgorithm()); 43 | // } 44 | // } 45 | } 46 | 47 | public static CipherManager getInstance(char[] p, byte[] s) { 48 | if (instance == null) { 49 | instance = new CipherManager(); 50 | try { 51 | instance.generateSK(p, s); 52 | } 53 | catch(Exception e) { 54 | e.printStackTrace(); 55 | return null; 56 | } 57 | } 58 | return instance; 59 | } 60 | 61 | private void generateSK(char[] passPhrase, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException { 62 | SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(key_algorithm); 63 | 64 | KeySpec spec = new PBEKeySpec(passPhrase,salt,ITERATIONS, KEYSIZE); 65 | SecretKey secretKey = secretKeyFactory.generateSecret(spec); 66 | 67 | key = new SecretKeySpec(secretKey.getEncoded(), secretKeyAlgorithm); 68 | } 69 | 70 | protected Cipher getEncCipher() { 71 | try { 72 | Cipher cipher = Cipher.getInstance(cipher_algorithm); 73 | cipher.init(Cipher.ENCRYPT_MODE, key); 74 | 75 | return cipher; 76 | }catch (Exception e) { 77 | e.printStackTrace(); 78 | return null; 79 | } 80 | } 81 | 82 | protected Cipher getDecCipher(byte[] iv) { 83 | try { 84 | Cipher cipher = Cipher.getInstance(cipher_algorithm); 85 | IvParameterSpec ivParams = new IvParameterSpec(iv); 86 | cipher.init(Cipher.DECRYPT_MODE, key, ivParams); 87 | 88 | return cipher; 89 | }catch (Exception e) { 90 | e.printStackTrace(); 91 | return null; 92 | } 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/collision/KryoStoreUtils.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.collision; 2 | 3 | import com.esotericsoftware.kryo.Kryo; 4 | import com.esotericsoftware.kryo.io.Input; 5 | import com.esotericsoftware.kryo.io.Output; 6 | 7 | import java.io.File; 8 | import java.io.FileInputStream; 9 | import java.io.FileOutputStream; 10 | 11 | import javax.crypto.Cipher; 12 | 13 | 14 | public class KryoStoreUtils { 15 | 16 | private static String TAG = "KRYOSTORE"; 17 | private static Kryo kryoInstance; 18 | 19 | private static Kryo getKryoInstance() { 20 | if(kryoInstance==null) { 21 | kryoInstance = new Kryo(); 22 | kryoInstance.register(WaspDataPage.class); 23 | } 24 | return kryoInstance; 25 | } 26 | 27 | // generic i/o 28 | 29 | public static void serializeToDisk(Object obj, String filename, CipherManager cipherManager) throws Exception { 30 | try { 31 | //Long start = System.currentTimeMillis(); 32 | //Log.d(TAG,start+": starting serializeToDisk with password"); 33 | 34 | Output output = new Output(new FileOutputStream(filename)); 35 | WaspDataPage dataPage = new WaspDataPage(); 36 | if(cipherManager!=null) { 37 | Cipher cipher = cipherManager.getEncCipher(); 38 | dataPage.setIv(cipher.getIV()); 39 | dataPage.setData(cipher.doFinal(serialize(obj))); 40 | } else { 41 | dataPage.setData(serialize(obj)); 42 | } 43 | getKryoInstance().writeObject(output, dataPage); 44 | output.close(); 45 | 46 | //Long end = System.currentTimeMillis(); 47 | //Log.d(TAG,end+": starting serializeToDisk with password"); 48 | //Log.d(TAG,"total time (ms): "+(end-start)); 49 | } 50 | catch(Exception e) { 51 | e.printStackTrace(); 52 | throw new Exception("\nERROR on serializeToDisk:"+e.getMessage()); 53 | } 54 | } 55 | 56 | public static Object readFromDisk(String filename, Class type, CipherManager cipherManager) throws Exception { 57 | try { 58 | //Long start = System.currentTimeMillis(); 59 | //Log.d(TAG,start+": starting readFromDisk with password"); 60 | 61 | File f = new File(filename); 62 | Object hash; 63 | if(f.exists()) { 64 | Input input = new Input(new FileInputStream(f)); 65 | WaspDataPage dataPage = getKryoInstance().readObject(input, WaspDataPage.class); 66 | if(cipherManager!=null) { 67 | Cipher decipher = cipherManager.getDecCipher(dataPage.getIv()); 68 | hash = unserialize(decipher.doFinal(dataPage.getData()),type); 69 | } 70 | else { 71 | hash = unserialize(dataPage.getData(),type); 72 | } 73 | input.close(); 74 | 75 | //Long end = System.currentTimeMillis(); 76 | //Log.d(TAG,end+": starting readFromDisk with password"); 77 | //Log.d(TAG,"total time (ms): "+(end-start)); 78 | 79 | return hash; 80 | } 81 | else { 82 | throw new Exception("\nERROR on readFromDisk: can't find "+filename); 83 | } 84 | } 85 | catch(Exception e) { 86 | e.printStackTrace(); 87 | throw new Exception("\nERROR on readFromDisk:"+e.getMessage()); 88 | } 89 | } 90 | 91 | // serializer for keys 92 | public static byte[] serialize(Object o) { 93 | byte[] ret = new byte[CollisionHash.MAXFILESIZE*2]; 94 | Output output = new Output(ret); 95 | getKryoInstance().writeObject(output, o); 96 | return output.toBytes(); 97 | } 98 | 99 | public static Object unserialize(byte[] buffer, Class type) { 100 | Input input = new Input(buffer); 101 | return getKryoInstance().readObject(input, type); 102 | } 103 | 104 | // public static Object cloneObject(Object obj) { 105 | // return getKryoInstance().copy(obj); 106 | // } 107 | } 108 | -------------------------------------------------------------------------------- /app/src/main/java/net/rehacktive/waspdbexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdbexample; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.ActionBarActivity; 5 | import android.view.Menu; 6 | import android.view.MenuItem; 7 | import android.view.View; 8 | import android.widget.ListView; 9 | import android.widget.ProgressBar; 10 | 11 | import net.rehacktive.waspdb.WaspDb; 12 | import net.rehacktive.waspdb.WaspFactory; 13 | import net.rehacktive.waspdb.WaspHash; 14 | import net.rehacktive.waspdb.WaspListener; 15 | import net.rehacktive.waspdb.WaspObserver; 16 | 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | public class MainActivity extends ActionBarActivity { 21 | 22 | ProgressBar progressBar; 23 | // wasp objects 24 | WaspDb db; 25 | WaspHash hash; 26 | WaspObserver observer; 27 | 28 | UserAdapter adapter; 29 | 30 | @Override 31 | protected void onCreate(Bundle savedInstanceState) { 32 | 33 | super.onCreate(savedInstanceState); 34 | setContentView(R.layout.activity_main); 35 | 36 | progressBar = (ProgressBar) findViewById(R.id.progressBar); 37 | 38 | ListView userList = (ListView) findViewById(R.id.userlist); 39 | adapter = new UserAdapter(this); 40 | userList.setAdapter(adapter); 41 | 42 | if(db==null) { 43 | progressBar.setVisibility(View.VISIBLE); 44 | WaspFactory.openOrCreateDatabase(getFilesDir().getPath(), "example", "Passw0rd", new WaspListener() { 45 | @Override 46 | public void onDone(WaspDb waspDb) { 47 | db = waspDb; 48 | hash = db.openOrCreateHash("users"); 49 | 50 | progressBar.setVisibility(View.INVISIBLE); 51 | 52 | getUsers(); 53 | 54 | observer = new WaspObserver() { 55 | @Override 56 | public void onChange() { 57 | List users = hash.getAllValues(); 58 | adapter.setUsers(users); 59 | adapter.notifyDataSetChanged(); 60 | } 61 | }; 62 | 63 | hash.register(observer); 64 | } 65 | }); 66 | } 67 | } 68 | 69 | private void getUsers() { 70 | List users = hash.getAllValues(); 71 | if(users==null) 72 | users = new ArrayList<>(); 73 | 74 | adapter.setUsers(users); 75 | adapter.notifyDataSetChanged(); 76 | } 77 | 78 | private void addUser() { 79 | User user = new User("user "+System.currentTimeMillis(), ""); 80 | hash.put(user.getUser_name(),user); 81 | } 82 | 83 | private void flushUsers() { 84 | hash.flush(); 85 | } 86 | 87 | @Override 88 | protected void onDestroy() { 89 | super.onDestroy(); 90 | hash.unregister(observer); 91 | } 92 | 93 | @Override 94 | public boolean onCreateOptionsMenu(Menu menu) { 95 | // Inflate the menu; this adds items to the action bar if it is present. 96 | getMenuInflater().inflate(R.menu.menu_main, menu); 97 | return true; 98 | } 99 | 100 | @Override 101 | public boolean onOptionsItemSelected(MenuItem item) { 102 | // Handle action bar item clicks here. The action bar will 103 | // automatically handle clicks on the Home/Up button, so long 104 | // as you specify a parent activity in AndroidManifest.xml. 105 | int id = item.getItemId(); 106 | 107 | //noinspection SimplifiableIfStatement 108 | if (id == R.id.add_user) { 109 | addUser(); 110 | return true; 111 | } 112 | 113 | if (id == R.id.flush_user) { 114 | flushUsers(); 115 | return true; 116 | } 117 | 118 | return super.onOptionsItemSelected(item); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/WaspHash.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import net.rehacktive.waspdb.internals.collision.CollisionHash; 4 | import net.rehacktive.waspdb.internals.collision.exceptions.KeyNotFoundException; 5 | import net.rehacktive.waspdb.internals.collision.CipherManager; 6 | 7 | import org.apache.commons.io.FileUtils; 8 | 9 | import java.io.File; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | 13 | public class WaspHash extends WaspObservable { 14 | 15 | private String path; 16 | private CollisionHash hash; 17 | 18 | protected WaspHash() {} 19 | 20 | protected WaspHash(CipherManager cipherManager, String path) { 21 | super(); 22 | this.hash = new CollisionHash(path, cipherManager); 23 | this.path = path; 24 | } 25 | 26 | /** 27 | * Store a key/value pair 28 | * 29 | * @param key the Object key 30 | * @param value the Object value 31 | */ 32 | public Boolean put(Object key, Object value) { 33 | try { 34 | hash.updateObject(key, value); 35 | notifyObservers(); 36 | return true; 37 | } 38 | catch(Exception e) { 39 | e.printStackTrace(); 40 | return false; 41 | } 42 | } 43 | 44 | /** 45 | * Retrieve a value associated to the specific key 46 | * @param key the key 47 | * @param the value type 48 | * @return the object, casted automagically! 49 | */ 50 | public T get(Object key) { 51 | try { 52 | return (T) hash.retrieveObject(key); 53 | } 54 | catch(KeyNotFoundException k) { 55 | k.printStackTrace(); 56 | return null; 57 | } 58 | catch(Exception e) { 59 | e.printStackTrace(); 60 | return null; 61 | } 62 | } 63 | 64 | /** 65 | * Remove the value associated to the specific key 66 | * @param key the key 67 | * @return true if all okay, false if error 68 | */ 69 | public boolean remove(Object key) { 70 | try { 71 | Object obj = hash.removeObject(key); 72 | if(obj!=null) { 73 | notifyObservers(); 74 | return true; 75 | } 76 | return false; 77 | } 78 | catch(KeyNotFoundException k) { 79 | k.printStackTrace(); 80 | return false; 81 | } 82 | catch(Exception e) { 83 | e.printStackTrace(); 84 | return false; 85 | } 86 | } 87 | 88 | /** 89 | * Retrieve the list of key for this WaspHash 90 | * @param the key type 91 | * @return a list of keys, casted automagically 92 | */ 93 | public List getAllKeys() { 94 | try { 95 | return hash.getAllKeys(path); 96 | } 97 | catch(Exception e) { 98 | e.printStackTrace(); 99 | return null; 100 | } 101 | } 102 | 103 | /** 104 | * Retrieve the list of values for this WaspHash 105 | * @param the value type 106 | * @return a list of values, casted automagically 107 | */ 108 | public List getAllValues() { 109 | try { 110 | return hash.getAllValues(path); 111 | } 112 | catch(Exception e) { 113 | e.printStackTrace(); 114 | return null; 115 | } 116 | } 117 | 118 | /** 119 | * Retrieve the list of key/value for this WaspHash 120 | * @param the key type 121 | * @param the value type 122 | * @return a Java HashMap containing all key/values 123 | */ 124 | public HashMap getAllData() { 125 | try { 126 | return hash.getAllData(path); 127 | } 128 | catch(Exception e) { 129 | e.printStackTrace(); 130 | return null; 131 | } 132 | } 133 | 134 | /** 135 | * Flush the current WaspHash - all the key/values will be removed 136 | */ 137 | public void flush() { 138 | try { 139 | File currentDir = new File(path); 140 | for(File f : currentDir.listFiles()) { 141 | if(f.isDirectory()) 142 | FileUtils.deleteDirectory(f); 143 | else 144 | FileUtils.deleteQuietly(f); 145 | } 146 | 147 | notifyObservers(); 148 | } 149 | catch(Exception e) { 150 | e.printStackTrace(); 151 | } 152 | } 153 | 154 | /** 155 | * Return some information about this WaspHash 156 | * @return a string containing the infos 157 | */ 158 | @Override 159 | public String toString() { 160 | return "WaspHash [path=" + path + "] total size: (K) " + FileUtils.sizeOf(new File(path)); 161 | } 162 | 163 | 164 | } 165 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-WaspDb-green.svg?style=true)](https://android-arsenal.com/details/1/3482) 2 | 3 | last release: 1.1.1 4 | 5 | (note: this version is NOT compatible with 1.0, read the release message) 6 | 7 | 8 | # WaspDb 9 | WaspDB is a pure Java key/value (NoSQL) database library for Android. It supports AES256 encryption for all the disk storage. It's very small (the aar file is ~189 KB). 10 | 11 | Keys and Values are simple Java Objects. Everything is automatically serialized using the [Kryo](https://github.com/EsotericSoftware/kryo/) serialization library. 12 | 13 | Data is stored by an implementation of hashmaps on disk. 14 | 15 | 16 | ### QuickStart 17 | 18 | To use it with gradle (using jitpack.io): 19 | 20 | Add it in your root build.gradle at the end of repositories: 21 | 22 | ```groovy 23 | allprojects { 24 | repositories { 25 | ... 26 | maven { url "https://jitpack.io" } 27 | } 28 | } 29 | ``` 30 | Add the dependency 31 | 32 | ```groovy 33 | dependencies { 34 | ... 35 | compile 'com.github.rehacktive:waspdb:1.1.1' 36 | } 37 | ``` 38 | 39 | Ok, let's start. 40 | 41 | Let's assume a POJO (even with nested object, like Address): 42 | ```java 43 | class User { 44 | private String username; 45 | private String email; 46 | private String telephone; 47 | private Address address; 48 | 49 | public User() { 50 | } 51 | 52 | // getters and setters... 53 | } 54 | ``` 55 | 56 | No need to be Serializable or Parcelable or annotations or extending/implementing from other classes/interfaces, the only important thing is to have an **empty constructor**. 57 | 58 | **Create a database, a WaspHash and store a POJO** 59 | ```java 60 | // create a database, using the default files dir as path, database name and a password 61 | String path = getFilesDir().getPath(); 62 | String databaseName = "myDb"; 63 | String password = "passw0rd"; 64 | 65 | WaspDb db = WaspFactory.openOrCreateDatabase(path,databaseName,password); 66 | 67 | // now create an WaspHash, it's like a sql table 68 | WaspHash users = db.openOrCreateHash("users"); 69 | 70 | // now let's have a POJO 71 | User p = new User(); 72 | ... // do your stuff with your POJO! 73 | 74 | // and simply store it! 75 | users.put(p.getUsername(), p); 76 | ``` 77 | 78 | **To retrieve it**, it's just 79 | ```java 80 | User p = users.get("username1"); 81 | ``` 82 | 83 | **Need all your objects?** 84 | ```java 85 | List allUsers = users.getAllValues(); 86 | ``` 87 | 88 | It returns all the users, in a standard java List. 89 | 90 | Or you can **get all the keys** used 91 | ```java 92 | List keys = users.getAllKeys(); 93 | ``` 94 | or the actual **key/value map** (it's again a standard java class) 95 | ```java 96 | HashMap usersMap = users.getAllData(); 97 | ``` 98 | Please note that the process of creating an encrypted database is computationally expensive (10000 iterations to create the AES256 key), so also an async method is available: 99 | ```java 100 | WaspFactory.openOrCreateDatabase(path, databaseName, password, new WaspListener() { 101 | @Override 102 | public void onDone(WaspDb waspDb) { 103 | .... 104 | } 105 | }); 106 | ``` 107 | 108 | ### Why WaspDb 109 | I **hate** to store objects on sqlite! It's a lot of boiler code...for what? 110 | Okay, let's say in the polite way :) 111 | 112 | The object-relational impedance mismatch is a set of conceptual and technical difficulties that are often encountered when a relational database management system (RDBMS) is being used by a program written in an object-oriented programming language or style; particularly when objects or class definitions are mapped in a straightforward way to database tables or relational schema. 113 | (from wikipedia [https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch](https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch)) 114 | 115 | ### What WaspDb is NOT 116 | This is not a SQL database. It does not have a relational data model, it does not support SQL queries, and it provides no support for indexes, nor transactions. 117 | 118 | ### Features 119 | - it's pure java, it's standalone, no native stuff, it's not an ORM to SqlLite! 120 | 121 | - the database addresses up to 4294967296 keys for WaspHash...enough? :) 122 | 123 | ### Limitations 124 | - it's NOT transactional. So if you wanna store 10000, it will make 10000 actual write operations to disk in sequence. That means it will be slower (in this case) compared to transactional databases. (of course, if you store 100 items as a java List - so actually a single object - it will make a single(ish) write operation) 125 | 126 | ### Proguard 127 | If you use Proguard in your project, add this to your proguard rules in order to skip WaspDB/Kryo classes: 128 | 129 | -keep class net.rehacktive.waspdb.** { *; } 130 | -keep class com.esotericsoftware.kryo.** { *; } 131 | 132 | ### Performances 133 | 134 | I've used this project [https://github.com/Raizlabs/AndroidDatabaseLibraryComparison](https://github.com/Raizlabs/AndroidDatabaseLibraryComparison) to make some benchmarking. 135 | 136 | This is the "simple trial" (storing 50 objects) on a Nexus 5, using WaspDb's encryption feature: 137 | 138 | ![image](/images/wasp_comparison.png) 139 | 140 | It's even faster if you don't need encryption. 141 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /waspdb/src/androidTest/java/net/rehacktive/waspdb/MainTest.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import android.content.Context; 4 | import android.test.InstrumentationTestCase; 5 | import android.util.Log; 6 | 7 | import java.util.HashMap; 8 | import java.util.List; 9 | 10 | /** 11 | * Created by stefano on 30/07/2015. 12 | */ 13 | public class MainTest extends InstrumentationTestCase { 14 | 15 | String path; 16 | String dbName = "justAtestDb2"; 17 | String dbPwd = "passw0rd!"; 18 | 19 | Context ctx; 20 | 21 | WaspDb db; 22 | 23 | @Override 24 | protected void setUp() throws Exception { 25 | super.setUp(); 26 | ctx = getInstrumentation().getContext(); 27 | path = ctx.getFilesDir().getAbsolutePath(); 28 | 29 | db = WaspFactory.openOrCreateDatabase(path,dbName,dbPwd); 30 | } 31 | 32 | public void testDatabaseCreation() { 33 | WaspFactory.openOrCreateDatabase(path, dbName, dbPwd, new WaspListener() { 34 | @Override 35 | public void onDone(WaspDb ret) { 36 | assertTrue("testDatabaseCreation", WaspFactory.existsDatabase(path, dbName)); 37 | } 38 | }); 39 | 40 | } 41 | 42 | public void testCreateHash() throws Exception { 43 | db.openOrCreateHash("hash"); 44 | assertTrue("testCreateHash", db.existsHash("hash")); 45 | } 46 | 47 | public void testPut() throws Exception { 48 | int id = 1; 49 | UserWithNestedContent p = new UserWithNestedContent(id, "test", "123"); 50 | WaspHash hash = db.openOrCreateHash("hash"); 51 | hash.flush(); 52 | 53 | hash.put(id, p); 54 | 55 | UserWithNestedContent newPerson = hash.get(id); 56 | assertTrue("testPut", newPerson.equals(p) && newPerson.getFriends().size()==UserWithNestedContent.NUMBER_OF_FRIENDS); 57 | } 58 | 59 | public void testMultiplePut() throws Exception { 60 | WaspHash hash = db.openOrCreateHash("test12"); 61 | hash.flush(); 62 | 63 | Long start = System.currentTimeMillis(); 64 | int count = 300; 65 | for (int i = 0; i < count; i++) { 66 | UserWithNestedContent user = new UserWithNestedContent(i, "b" + i, ""); 67 | hash.put(user.getUsername(), user); 68 | } 69 | Long end = System.currentTimeMillis(); 70 | Log.d("WASPDEBUG MULTIPLE",(end-start)+" ms"); 71 | List result = hash.getAllKeys(); 72 | Long end2 = System.currentTimeMillis(); 73 | Log.d("WASPDEBUG MULTIPLE",(end2-end)+" ms for reading all"); 74 | assertTrue("testMultiplePut " + result.size(), result.size() == count); 75 | } 76 | 77 | public void testGetAllKeys() throws Exception { 78 | WaspHash hash = db.openOrCreateHash("users"); 79 | hash.flush(); 80 | 81 | int count = 10; 82 | for(int i=0; i result = hash.getAllKeys(); 88 | assertTrue("testGetAllKeys", result.size() == count); 89 | } 90 | 91 | public void testGetAllValues() throws Exception { 92 | WaspHash hash = db.openOrCreateHash("users"); 93 | hash.flush(); 94 | 95 | int count = 10; 96 | for(int i=0; i result = hash.getAllValues(); 102 | assertTrue("testGetAllValues", result.size() == count); 103 | } 104 | 105 | public void testGetAllData() throws Exception { 106 | WaspHash hash = db.openOrCreateHash("users"); 107 | hash.flush(); 108 | 109 | int count = 10; 110 | for(int i=0; i result = hash.getAllData(); 116 | assertTrue("testGetAllData", result.size() == count); 117 | } 118 | 119 | public void testRemove() throws Exception { 120 | WaspHash hash = db.openOrCreateHash("deleteHash"); 121 | 122 | UserWithNestedContent p = new UserWithNestedContent(1,"test","123"); 123 | 124 | hash.put(1,p); 125 | 126 | hash.remove(1); 127 | 128 | assertTrue("testDelete", hash.getAllKeys().size() == 0); 129 | } 130 | 131 | public void testHashFlush() throws Exception { 132 | WaspHash hash = db.openOrCreateHash("anotherHash"); 133 | 134 | UserWithNestedContent p = new UserWithNestedContent(1,"test","123"); 135 | 136 | hash.put(1,p); 137 | 138 | hash.flush(); 139 | 140 | assertTrue("testHashFlush", hash.getAllKeys().size() == 0); 141 | } 142 | 143 | public void testHashDelete() throws Exception { 144 | WaspHash hash = db.openOrCreateHash("anotherHashToDelete"); 145 | if(hash!=null) { 146 | db.removeHash("anotherHashToDelete"); 147 | assertTrue(!db.existsHash("anotherHashToDelete")); 148 | } else { 149 | fail(); 150 | } 151 | } 152 | 153 | public void testDatabaseDestroy() throws Exception { 154 | // TODO 155 | } 156 | 157 | public void testObserver() throws Exception { 158 | int id = 2; 159 | UserWithNestedContent p = new UserWithNestedContent(id,"test","123"); 160 | 161 | final WaspHash hash = db.openOrCreateHash("another_hash"); 162 | hash.flush(); 163 | 164 | hash.register(new WaspObserver() { 165 | @Override 166 | public void onChange() { 167 | assertTrue("testObserver", hash.getAllKeys().size() == 1); 168 | } 169 | }); 170 | 171 | hash.put(id, p); 172 | } 173 | 174 | 175 | } 176 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/WaspDb.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import net.rehacktive.waspdb.internals.collision.CipherManager; 4 | import net.rehacktive.waspdb.internals.utils.Utils; 5 | 6 | import java.io.File; 7 | import java.security.NoSuchAlgorithmException; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class WaspDb { 12 | 13 | /* 14 | * this object contains all main infos about database 15 | * this file is "kryonized" under {path}/dbname/db.data 16 | */ 17 | 18 | private String dbName; // db name 19 | private String path; // db path 20 | private CipherManager cipherManager; 21 | 22 | private List hashes; // all hashes used 23 | 24 | protected WaspDb() { 25 | } 26 | 27 | /** 28 | * Open/create a WaspHash instance 29 | * @param hashName name 30 | * @return 31 | */ 32 | public WaspHash openOrCreateHash(String hashName) { 33 | WaspHash hash; 34 | try { 35 | if(existsHash(hashName)) { 36 | hash = getHash(hashName); 37 | } else { 38 | hash = createHash(hashName); 39 | } 40 | return hash; 41 | } 42 | catch(Exception wfe) { 43 | wfe.printStackTrace(); 44 | return null; 45 | } 46 | } 47 | 48 | /** 49 | * Check if the WaspHash exists 50 | * @param hashName name 51 | * @return 52 | */ 53 | public boolean existsHash(String hashName) { 54 | try { 55 | String realname = Utils.md5(hashName); 56 | String directory = path+"/"+Utils.md5(dbName)+"/"+realname; 57 | return new File(directory).exists(); 58 | } 59 | catch(Exception e) { 60 | return false; 61 | } 62 | } 63 | 64 | protected WaspHash getHash(String hashName) { 65 | try { 66 | String realname = Utils.md5(hashName); 67 | String directory = path+"/"+Utils.md5(dbName)+"/"+realname; 68 | if(new File(directory).exists()) { // already exists 69 | WaspHash hash = new WaspHash(cipherManager,directory); 70 | return hash; 71 | } 72 | else { 73 | return null; 74 | } 75 | 76 | } catch (Exception e) { 77 | e.printStackTrace(); 78 | return null; 79 | } 80 | } 81 | 82 | protected WaspHash createHash(String hashName) { 83 | try { 84 | String realname = Utils.md5(hashName); 85 | String directory = path+"/"+Utils.md5(dbName)+"/"+realname; 86 | if(!new File(directory).exists()) { // if not exists 87 | // create a new one 88 | if(new File(directory).mkdir()) { 89 | WaspHash hash = new WaspHash(cipherManager,directory); 90 | 91 | if(hashes==null) hashes = new ArrayList(); 92 | hashes.add(hashName); 93 | persist(); // update db data on disk 94 | return hash; 95 | } 96 | else { 97 | return null; 98 | } 99 | } else { 100 | return getHash(hashName); 101 | } 102 | } catch(Exception e) { 103 | e.printStackTrace(); 104 | return null; 105 | } 106 | } 107 | 108 | /** 109 | * Delete the specified WaspHash 110 | * @param hashName name 111 | * @return 112 | */ 113 | public boolean removeHash(String hashName) { 114 | try { 115 | String realname = Utils.md5(hashName); 116 | String directory = path+"/"+Utils.md5(dbName)+"/"+realname; 117 | if(new File(directory).exists()) { // if exists 118 | // delete recursively 119 | try { 120 | Utils.deleteRecursive(new File(directory)); 121 | 122 | if(hashes!=null) hashes.remove(hashName); 123 | persist(); // update db data on disk 124 | 125 | return true; 126 | } 127 | catch(Exception e) { 128 | return false; 129 | } 130 | } else { 131 | return false; 132 | } 133 | } catch(Exception e) { 134 | e.printStackTrace(); 135 | return false; 136 | } 137 | } 138 | 139 | /** 140 | * Return a list of all WaspHash names associated to this database 141 | * @return 142 | */ 143 | public List getAllHashes() { 144 | return hashes; 145 | } 146 | 147 | protected String getName() throws NoSuchAlgorithmException { 148 | return Utils.md5(dbName); 149 | } 150 | 151 | protected void setName(String name) { 152 | this.dbName = name; 153 | } 154 | 155 | protected String getPath() { 156 | return path; 157 | } 158 | 159 | protected void setPath(String path) { 160 | this.path = path; 161 | } 162 | 163 | /** 164 | * Get information about this instance 165 | * @return a string containing some information 166 | */ 167 | @Override 168 | public String toString() { 169 | return "WaspDb [name=" + dbName + ", path=" + path + ", cipher enabled = " 170 | + (cipherManager!=null) + "]"; 171 | } 172 | 173 | private void persist() { 174 | WaspFactory.storeDatabase(this, cipherManager); 175 | } 176 | 177 | protected CipherManager getCipherManager() { 178 | return cipherManager; 179 | } 180 | 181 | protected void setCipherManager(CipherManager cm) { 182 | this.cipherManager = cm; 183 | } 184 | 185 | protected void clearCipherInformation() { 186 | this.cipherManager = null; 187 | } 188 | 189 | 190 | } 191 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/WaspFactory.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb; 2 | 3 | import android.os.AsyncTask; 4 | 5 | import net.rehacktive.waspdb.internals.collision.KryoStoreUtils; 6 | import net.rehacktive.waspdb.internals.collision.CipherManager; 7 | import net.rehacktive.waspdb.internals.utils.Salt; 8 | import net.rehacktive.waspdb.internals.utils.Utils; 9 | 10 | import java.io.File; 11 | 12 | public class WaspFactory { 13 | 14 | private static final String DB_NAME = "data.db"; 15 | private static final String SALT_NAME = "salt"; 16 | 17 | /** 18 | * Asynchronously open/create a WaspDb instance 19 | * the operation requires some time, according to device CPU power 20 | * @param path the path for the database folder - use Context.getFilesDir().getPath() 21 | * @param name name of the database 22 | * @param password password - set as null if you don't need encryption / for better performances 23 | * @param listener a WaspListener instance, to get the database when is ready 24 | */ 25 | public static void openOrCreateDatabase(final String path, final String name, final String password, final WaspListener listener) { 26 | new AsyncTask() { 27 | 28 | WaspDb db = null; 29 | 30 | @Override 31 | protected Void doInBackground(Void... params) { 32 | if(WaspFactory.existsDatabase(path, name)) { 33 | db = WaspFactory.loadDatabase(path, name, password); 34 | } else { 35 | db = WaspFactory.createDatabase(path, name, password); 36 | } 37 | return null; 38 | } 39 | 40 | @Override 41 | protected void onPostExecute(Void aVoid) { 42 | super.onPostExecute(aVoid); 43 | if(db!=null) { 44 | listener.onDone(db); 45 | } else { 46 | listener.onError("error on openOrCreateDatabase"); 47 | } 48 | } 49 | }.execute(); 50 | 51 | } 52 | 53 | /** 54 | * Synchronous call to create the database - use outside of the main thread! 55 | * @param path the path for the database folder - use Context.getFilesDir().getPath() 56 | * @param name name of the database 57 | * @param password password - set as null if you don't need encryption / for better performances 58 | * @return 59 | */ 60 | public static WaspDb openOrCreateDatabase(String path, String name, String password) { 61 | if(WaspFactory.existsDatabase(path, name)) { 62 | return WaspFactory.loadDatabase(path, name, password); 63 | } else { 64 | return WaspFactory.createDatabase(path, name, password); 65 | } 66 | } 67 | 68 | /** 69 | * Destroy the database and remove all the data 70 | * @param db the database object to destroy 71 | * @return 72 | */ 73 | public static boolean destroyDatabase(WaspDb db) { 74 | try { 75 | String directory = db.getPath()+"/"+Utils.md5(db.getName())+"/"; 76 | if(new File(directory).exists()) { // if exists 77 | // delete recursively 78 | try { 79 | Utils.deleteRecursive(new File(directory)); 80 | return true; 81 | } 82 | catch(Exception e) { 83 | return false; 84 | } 85 | } else { 86 | return true; 87 | } 88 | } catch(Exception e) { 89 | e.printStackTrace(); 90 | return false; 91 | } 92 | } 93 | 94 | // PROTECTED 95 | 96 | protected static boolean existsDatabase(String path, String name) { 97 | try { 98 | WaspDb db = new WaspDb(); 99 | db.setPath(path); 100 | db.setName(name); 101 | String directory; 102 | directory = db.getPath()+"/"+db.getName(); 103 | 104 | return (new File(directory).exists()); 105 | } catch (Exception e) { 106 | return false; 107 | } 108 | } 109 | 110 | protected static WaspDb createDatabase(final String path, final String name, final String password) { 111 | if(password!=null && !Utils.checkForCryptoAvailable()) return null; 112 | Salt salt = Utils.generateSalt(); 113 | WaspDb db = new WaspDb(); 114 | db.setName(name); 115 | db.setPath(path); 116 | try { 117 | CipherManager cipherManager = null; 118 | if (!Utils.isEmpty(password)) { 119 | cipherManager = CipherManager.getInstance(password.toCharArray(), salt.getSalt()); 120 | } 121 | 122 | boolean ret = storeDatabase(db, cipherManager); 123 | if (ret) { 124 | KryoStoreUtils.serializeToDisk(salt, db.getPath()+"/"+db.getName()+"/"+SALT_NAME, null); 125 | db.setCipherManager(cipherManager); // set the ciphermanager in the object 126 | return db; 127 | } else return null; 128 | } 129 | catch(Exception e) { 130 | e.printStackTrace(); 131 | return null; 132 | } 133 | } 134 | 135 | protected static boolean storeDatabase(WaspDb db, CipherManager cipherManager) { 136 | try { 137 | String directory = db.getPath()+"/"+db.getName(); 138 | //if((new File(directory).exists())) throw new WaspFatalException("database already exists"); 139 | boolean success = true; 140 | if(!(new File(directory).exists())) success = (new File(directory)).mkdir(); 141 | if(success) { 142 | // do not store the cipherManager 143 | db.clearCipherInformation(); 144 | KryoStoreUtils.serializeToDisk(db, db.getPath() + "/" + db.getName() + "/" + DB_NAME, cipherManager); 145 | db.setCipherManager(cipherManager); 146 | 147 | return true; 148 | } else { 149 | return false; 150 | } 151 | } catch (Exception e) { 152 | e.printStackTrace(); 153 | return false; 154 | } 155 | } 156 | 157 | protected static WaspDb loadDatabase(final String path, final String name, final String password) { 158 | if(password!=null && !Utils.checkForCryptoAvailable()) return null; 159 | CipherManager cipherManager = null; 160 | try { 161 | String realname = Utils.md5(name); 162 | WaspDb db; 163 | 164 | Salt salt = (Salt) KryoStoreUtils.readFromDisk(path + "/" + realname +"/"+SALT_NAME,Salt.class, null); 165 | if(!Utils.isEmpty(password)) 166 | cipherManager = CipherManager.getInstance(password.toCharArray(),salt.getSalt()); 167 | db = (WaspDb) KryoStoreUtils.readFromDisk(path + "/" + realname + "/" + DB_NAME, WaspDb.class, cipherManager); 168 | 169 | db.setPath(path); // refresh the path to the current one 170 | db.setCipherManager(cipherManager); // set the password in the object 171 | return db; 172 | } catch (Exception e) { 173 | e.printStackTrace(); 174 | return null; 175 | } 176 | } 177 | 178 | } 179 | -------------------------------------------------------------------------------- /waspdb/src/main/java/net/rehacktive/waspdb/internals/collision/CollisionHash.java: -------------------------------------------------------------------------------- 1 | package net.rehacktive.waspdb.internals.collision; 2 | 3 | import android.util.Log; 4 | 5 | import net.rehacktive.waspdb.internals.collision.exceptions.KeyAlreadyExistsException; 6 | import net.rehacktive.waspdb.internals.collision.exceptions.KeyNotFoundException; 7 | import net.rehacktive.waspdb.internals.utils.Utils; 8 | 9 | import org.apache.commons.io.FileUtils; 10 | 11 | import java.io.File; 12 | import java.io.FileNotFoundException; 13 | import java.security.MessageDigest; 14 | import java.security.NoSuchAlgorithmException; 15 | import java.util.ArrayList; 16 | import java.util.HashMap; 17 | import java.util.List; 18 | 19 | 20 | public class CollisionHash { 21 | 22 | protected String path; 23 | protected String ext = ".cube"; 24 | 25 | protected static int MAXFILESIZE = 65536; 26 | 27 | private CipherManager cipherManager; 28 | 29 | private static String TAG = "COLLISIONHASH"; 30 | 31 | private static String[] cubes = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; 32 | 33 | // public methods 34 | 35 | public CollisionHash(String path, CipherManager cipherManager) { 36 | this.path = path; 37 | this.cipherManager = cipherManager; 38 | } 39 | 40 | public void storeObject(Object key, Object value) throws Exception { 41 | storeObject(key, value,false); 42 | } 43 | 44 | public void updateObject(Object key, Object value) throws Exception { 45 | storeObject(key,value,true); 46 | } 47 | 48 | public void storeObject(Object key, Object value, boolean update) throws Exception { 49 | try { 50 | String searchKey = getSearchKey(key); // calculate searchKey for file to store 51 | HashMap hash = getHashFromKey(searchKey); // return the hash from the key - it's size is < MAXSIZE-1 52 | 53 | if(!hash.containsKey(key) || update) { 54 | hash.put(key, value); // add value 55 | storeHashByKey(hash,searchKey); // store hash 56 | } 57 | else { 58 | throw new KeyAlreadyExistsException("key already exists for value "+hash.get(key)); 59 | } 60 | } catch(Exception e) { 61 | throw e; 62 | } 63 | } 64 | 65 | public Object retrieveObject(Object key) throws Exception { 66 | return retrieveObject(key, false); 67 | } 68 | 69 | 70 | public Object removeObject(Object key) throws Exception { 71 | return retrieveObject(key, true); 72 | } 73 | 74 | public HashMap getAllData(String p) throws Exception { 75 | if(p==null) p = path; 76 | HashMap ret = new HashMap(); 77 | 78 | for(String s : cubes) { 79 | String currentPath = p+"/"+s; 80 | if(new File(currentPath).isDirectory()) { 81 | ret.putAll(getAllData(currentPath)); 82 | } 83 | if(new File(currentPath+ext).exists()) { 84 | HashMap data; 85 | data = (HashMap) KryoStoreUtils.readFromDisk(currentPath+ext, HashMap.class, cipherManager); 86 | ret.putAll(data); 87 | } 88 | } 89 | return ret; 90 | } 91 | 92 | public List getAllKeys(String p) throws Exception { 93 | if(p==null) p = path; 94 | List ret = new ArrayList(); 95 | 96 | for(String s : cubes) { 97 | String currentPath = p+"/"+s; 98 | if(new File(currentPath).isDirectory()) { 99 | ret.addAll(getAllKeys(currentPath)); 100 | } 101 | if(new File(currentPath+ext).exists()) { 102 | HashMap data; 103 | data = (HashMap) KryoStoreUtils.readFromDisk(currentPath+ext, HashMap.class,cipherManager); 104 | ret.addAll(data.keySet()); 105 | } 106 | } 107 | return ret; 108 | } 109 | 110 | public List getAllValues(String p) throws Exception { 111 | if(p==null) p = path; 112 | List ret = new ArrayList(); 113 | 114 | for(String s : cubes) { 115 | String currentPath = p+"/"+s; 116 | if(new File(currentPath).isDirectory()) { 117 | ret.addAll(getAllValues(currentPath)); 118 | } 119 | if(new File(currentPath+ext).exists()) { 120 | HashMap data; 121 | data = (HashMap) KryoStoreUtils.readFromDisk(currentPath+ext, HashMap.class,cipherManager); 122 | ret.addAll(data.values()); 123 | } 124 | } 125 | return ret; 126 | } 127 | 128 | // private methods 129 | 130 | private Object retrieveObject(Object key, boolean remove) throws Exception { 131 | Object ret = null; 132 | try { 133 | String searchKey = getSearchKey(key); // calculate searchKey for file to store 134 | HashMap hash = getHashFromKey(searchKey); // return the hash from the key - it's size is < MAXSIZE-1 135 | ret = hash.get(key); 136 | if(ret!=null) { 137 | Log.d(TAG, System.currentTimeMillis()+": object found with key "+key); 138 | if(remove) { 139 | hash.remove(key); 140 | storeHashByKey(hash,searchKey); // store hash 141 | Log.d(TAG, System.currentTimeMillis()+": object removed with key "+key); 142 | } 143 | } 144 | else { 145 | throw new KeyNotFoundException("key not found for key "+key); 146 | } 147 | } catch(Exception e) { 148 | throw e; 149 | } 150 | return ret; 151 | } 152 | 153 | protected void explodeCube(String file) throws Exception { 154 | Log.d(TAG,"cube full:"+file); 155 | // the cube is full 156 | // get the working directory 157 | String tmpFile = file.substring(0,file.length()-6)+"tmp"+ext; 158 | // original file 159 | File file1 = new File(file); 160 | // tmp file 161 | File file2 = new File(tmpFile); 162 | // Rename file 163 | boolean success = file1.renameTo(file2); 164 | if(success) Log.d(TAG,"created temporary file"); 165 | 166 | String newdirPath = file.substring(0,file.length()-5); 167 | File newdir = new File(newdirPath);; 168 | try { 169 | 170 | // create a directory with tmp name 171 | if(newdir.mkdir()) { 172 | Log.d(TAG,"created new directory:"+newdirPath); 173 | // read content of the file 174 | HashMap hash; 175 | hash = (HashMap) KryoStoreUtils.readFromDisk(tmpFile,HashMap.class,cipherManager); 176 | // and store it's content inside the new directory 177 | for(Object k : hash.keySet()) { 178 | //String key = (String) k; 179 | Object o = hash.get(k); 180 | storeObject(k, o); 181 | } 182 | // remove the tmp file 183 | file2.delete(); 184 | } else { 185 | Log.d(TAG, "can't create "+newdirPath); 186 | throw new Exception(); 187 | } 188 | } 189 | catch(Exception e) { 190 | e.printStackTrace(); 191 | // if something goes wrong during split 192 | // remove the new directory 193 | deleteRecursive(newdir); 194 | // and restore original cube 195 | success = file2.renameTo(file1); 196 | if(success) { 197 | Log.d(TAG,"restored original cube"); 198 | throw new Exception("Unable to add more data - no more space left?"); 199 | } 200 | else throw new Exception("FATAL ON FILESYSTEM DURING ADDING MORE DATA - possible corrupted data!!!"); 201 | } 202 | Log.d(TAG, "explosion done"); 203 | } 204 | 205 | // previously on CollisionStructure 206 | 207 | public String getSearchKey(Object key) throws NoSuchAlgorithmException { 208 | // transform a key to a searchKey for the collision! 209 | final MessageDigest messageDigest = MessageDigest.getInstance("MD5"); 210 | messageDigest.reset(); 211 | messageDigest.update(KryoStoreUtils.serialize(key)); 212 | final byte[] resultByte = messageDigest.digest(); 213 | final String result = Utils.toHexString(resultByte); 214 | String searchKey = result.substring(0,8); 215 | //Log.d("XXX","getSearchKey: "+searchKey+" for key "+key); 216 | return searchKey; 217 | } 218 | 219 | public String getFileFromSearchKey(String searchKey) { 220 | String filePath = ""; 221 | for(int i=searchKey.length();i>0;i--) { 222 | filePath = path; 223 | for(int j=0;j MAXFILESIZE && hash.size() > 1) { 253 | explodeCube(file); 254 | // then recall this method again (recursive) to use the next byte of the key and find the correct file 255 | return getHashFromKey(searchKey); 256 | } 257 | } 258 | // return 259 | return hash; 260 | } 261 | 262 | protected boolean deleteRecursive(File path) throws FileNotFoundException { 263 | if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath()); 264 | boolean ret = true; 265 | if (path.isDirectory()){ 266 | for (File f : path.listFiles()){ 267 | ret = ret && deleteRecursive(f); 268 | } 269 | } 270 | return ret && path.delete(); 271 | } 272 | 273 | public void storeHashByKey(HashMap hash, String searchKey) throws Exception { 274 | // simply serialize the hash to the file addressed by the key 275 | String file = getFileFromSearchKey(searchKey); 276 | KryoStoreUtils.serializeToDisk(hash, file, cipherManager); 277 | // the file exists, according to the getHashFromKey feature, and it's not full 278 | } 279 | 280 | } 281 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------