├── lib
├── .gitignore
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── github
│ │ │ └── gfx
│ │ │ └── util
│ │ │ └── encrypt
│ │ │ ├── Encryption.java
│ │ │ └── EncryptedSharedPreferences.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── gfx
│ │ └── util
│ │ └── encrypt
│ │ ├── LegacyEncryptionTest.java
│ │ ├── EncryptionTest.java
│ │ └── EncryptedSharedPreferencesTest.java
├── coveralls.gradle
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── .gitignore
├── .coveralls.yml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .travis.yml
├── gradle.properties
├── metadata.gradle
├── CHANGES.md
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/lib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':lib'
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle/
2 | .idea/
3 | local.properties
4 | .DS_Store
5 | build/
6 |
--------------------------------------------------------------------------------
/.coveralls.yml:
--------------------------------------------------------------------------------
1 | service_name: travis-ci
2 | repo_token: Ss8EAcPzm5uGpcj6bvSKXDWBuJzbYw2Ng
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gfx/Android-EncryptUtils/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/lib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Mar 16 10:41:20 JST 2015
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.2.1-bin.zip
7 |
--------------------------------------------------------------------------------
/lib/coveralls.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 | apply plugin: 'jacoco'
3 | apply plugin: 'com.github.kt3k.coveralls'
4 |
5 | buildscript {
6 | repositories {
7 | mavenCentral()
8 | }
9 |
10 | dependencies {
11 | classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.+'
12 | }
13 | }
14 |
15 | coveralls {
16 | jacocoReportPath 'build/outputs/reports/coverage/debug/report.xml'
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/lib/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 /usr/local/opt/android-sdk/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 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | env:
3 | - TARGET=android-10 ABI=armeabi
4 | - TARGET=android-19 ABI=armeabi-v7a
5 | - TARGET=android-21 ABI=armeabi-v7a
6 | matrix:
7 | allow_failures:
8 | - env: "TARGET=android-21 ABI=armeabi-v7a"
9 | before_install:
10 | - export TERM=dumb # to get clean gradle output
11 | - android list targets # for debugging
12 | - echo no | android create avd --force -n test -t $TARGET -b $ABI
13 | - emulator -avd test -no-skin -no-audio -no-window &
14 | - ./gradlew tasks # install dependencies while the eumulator is booting
15 | - android-wait-for-emulator
16 | script:
17 | - ./gradlew --stacktrace lint
18 | - export COVERAGE=true
19 | - ./gradlew --stacktrace connectedCheck || (adb logcat -t 100 '*:E' && false)
20 | after_success:
21 | - ./gradlew --stacktrace -b lib/coveralls.gradle coveralls
22 | after_script:
23 | - android delete avd -n test
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Settings specified in this file will override any Gradle settings
5 | # configured through the IDE.
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
19 | org.gradle.daemon=true
20 |
--------------------------------------------------------------------------------
/metadata.gradle:
--------------------------------------------------------------------------------
1 | // Artifact Metadata
2 |
3 | // see https://github.com/chrisbanes/gradle-mvn-push/blob/master/gradle-mvn-push.gradle
4 |
5 | def versionCode(versionName) {
6 | def parts = versionName.split(/\./).collect {
7 | Integer.parseInt(it)
8 | }
9 | return parts[0] * 1000000 + parts[1] * 1000 + parts[2]
10 | }
11 |
12 | ext.VERSION_NAME = '2.0.0'
13 | ext.VERSION_CODE = versionCode(ext.VERSION_NAME)
14 | ext.GROUP = 'com.github.gfx.util.encrypt'
15 |
16 | ext.POM_NAME = 'Android EncryptUtils'
17 | ext.POM_DESCRIPTION = 'A set of classes to conceal credentials'
18 | ext.POM_ARTIFACT_ID = 'android-encrypt-utils'
19 | ext.POM_PACKAGING = 'aar'
20 |
21 | def GITHUB_ID = "gfx/Android-EncryptUtils"
22 | def REPOSITORY_URL = "https://github.com/${GITHUB_ID}"
23 | def REPOSITORY_SCM = "scm:git@github.com:${GITHUB_ID}.git"
24 |
25 | ext.POM_URL = REPOSITORY_URL
26 | ext.POM_SCM_URL = REPOSITORY_URL
27 | ext.POM_SCM_CONNECTION = REPOSITORY_SCM
28 | ext.POM_SCM_DEV_CONNECTION = REPOSITORY_SCM
29 | ext.POM_LICENCE_NAME = 'Apache License 2.0'
30 | ext.POM_LICENCE_URL = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
31 | ext.POM_LICENCE_DIST = 'repo'
32 | ext.POM_DEVELOPER_ID = 'gfx'
33 | ext.POM_DEVELOPER_NAME = 'FUJI Goro'
34 | ext.POM_DEVELOPER_EMAIL = 'gfuji@cpan.org'
35 |
36 |
--------------------------------------------------------------------------------
/CHANGES.md:
--------------------------------------------------------------------------------
1 | # The Revision History of Android-EncryptUtils
2 |
3 | ## v2.0.0 2014-11-21 01:37:06+0900
4 |
5 | * Add new interfaces that takes a `javax.crypto.Cipher` instance and deprecate old ones
6 | * Deprecated interfaces uses AES/CTR/PKC5Padding algorithm mode with the default provider, which could **break existing data on OS updates**
7 | * Add Encryption.getDefaultCipher() to get a Cipher instance with `AES/CTR/PKC5Padding`` with `AndroidOpenSSL` security provider
8 | * Note that `AndroidOpenSSL` is not available on Ginger Bread (API level 10), so you have to get a cipher instance
9 | with an available security provider, e.g. `BC` (*BouncyCastle*)
10 | * Migration from 1.x: Use `new EncryptedSharedPreferences(Encryption.getDefaultCipher(), context)` instead of
11 | `new EncryptedSharedPreferences(context)`; this changes the cipher algorithm, though.
12 |
13 | ## v1.2.1 2014-07-23 23:29:49+0900
14 |
15 | * Fix a crash issue where the length of ANDROID_ID < 16 (#2 #3; thanks to tomorrowkey)
16 |
17 | ## v1.2.0 2014-06-18 07:50:43+0900
18 |
19 | * Change the atrifact id from `encrypt-utils` to `android-encrypt-utils`
20 |
21 | ## v1.1.0 2014-06-18 07:32:18+0900
22 |
23 | * Add a constructor `new EncryptedSharedPreferences(SharedPreferences, Context)`,
24 | where the second argument is used to make a default private key.
25 |
26 | ## v1.0.0 2014-06-15 11:54:49+0900
27 |
28 | * Initial release
29 |
--------------------------------------------------------------------------------
/lib/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'android-sdk-manager'
2 | apply plugin: 'com.android.library'
3 | apply plugin: 'android-power-assert'
4 |
5 | apply from: '../metadata.gradle'
6 | //apply from: 'https://raw.githubusercontent.com/chrisbanes/gradle-mvn-push/master/gradle-mvn-push.gradle'
7 | apply from: 'https://raw.githubusercontent.com/shamanland/gradle-mvn-push/master/gradle-mvn-push.gradle'
8 |
9 | def COVERAGE = Boolean.parseBoolean(System.getenv('COVERAGE'))
10 |
11 | android {
12 | compileSdkVersion 22
13 | buildToolsVersion '22.0.0'
14 | defaultConfig {
15 | minSdkVersion 10 // 2.3.3
16 | targetSdkVersion 22
17 | versionCode VERSION_CODE
18 | versionName VERSION_NAME
19 | }
20 |
21 | compileOptions {
22 | encoding 'UTF-8'
23 | sourceCompatibility JavaVersion.VERSION_1_7
24 | targetCompatibility JavaVersion.VERSION_1_7
25 | }
26 |
27 | if (COVERAGE) {
28 | println("[NOTE] coverage enabled.")
29 | jacoco {
30 | version '0.7.+'
31 | }
32 | buildTypes {
33 | debug {
34 | testCoverageEnabled true
35 | }
36 | }
37 | }
38 | }
39 |
40 | dependencies {
41 | compile 'com.android.support:support-annotations:+'
42 | androidTestCompile 'org.apache.commons:commons-lang3:+'
43 | androidTestCompile 'org.apache.commons:commons-io:+'
44 | }
45 |
46 |
47 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This library is obsolete. Use [androidx.security.crypto.EncryptedSharedPreferences](https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences.html) instead.
2 |
3 | ----
4 |
5 | # Android-EncryptUtils [](https://travis-ci.org/gfx/Android-EncryptUtils) [](https://coveralls.io/r/gfx/Android-EncryptUtils?branch=master)
6 |
7 | This is a set of class libraries that provides a way to save credentials in Android devices.
8 |
9 | Note that this is not perfectly secure because private keys could not be concealed so the attacker
10 | are able to decrypt data if they have the device and enough time. However, this library should
11 | prevent data from 10-minutes cracking.
12 |
13 | ## Gradle Dependencies
14 |
15 | ```gradle
16 | dependencies {
17 | compile 'com.github.gfx.util.encrypt:android-encrypt-utils:2.0.0'
18 | }
19 | ```
20 |
21 | ## Encryption
22 |
23 | This is a utility to encrypt and decrypt credentials.
24 | `Encryption` creates a private key from `context`'s
25 | packag name and `ANDROID_ID` by default.
26 |
27 | ```java
28 | Encryption encryption = new Encryption(Encryption.getDefaultCipher() ,context);
29 | String plainText = ...;
30 | String encrypted = encryption.encrypt(plainText);
31 | String decrypted = encryption.decrypt(encrypted);
32 |
33 | assert plainText.equals(decrypted);
34 | ```
35 |
36 | You can also specify a private key instead of a context.
37 |
38 | ```java
39 | byte[] privateKey = ...;
40 | assert privateKey.length == 16; // you must ensure!
41 | Encryption encryption = new Encryption(Encryption.getDefaultCipher(), privateKey);
42 | ```
43 |
44 | ## EncryptedSharedPreferences
45 |
46 | This is an implementation of SharedPreferences that encrypts data.
47 |
48 | ```java
49 | SharedPreferences prefs = new EncryptedSharedPreferences(Encryption.getDefaultCipher(), context);
50 |
51 | prefs.editor()
52 | .putString("email", email)
53 | .putString("password", password)
54 | .apply();
55 | ```
56 |
57 | ### HOW DATA ARE STORED
58 |
59 | As `SharedPreferences` does, `EncryptedSHaredPreferences` saves data in XML and its values
60 | are encrypted in [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) while
61 | its keys are just encoded in Base64 format.
62 |
63 | The following content is an example of shared preferences file:
64 |
65 | ```xml
66 |
67 |
71 | ```
72 |
73 | ## AUTHOR
74 |
75 | FUJI Goro (gfx)
76 |
77 | ## LICENSE
78 |
79 | This is a free software licensed in Apache License 2.0. See [LICENSE](LICENSE) for details.
80 |
--------------------------------------------------------------------------------
/lib/src/androidTest/java/com/github/gfx/util/encrypt/LegacyEncryptionTest.java:
--------------------------------------------------------------------------------
1 | package com.github.gfx.util.encrypt;
2 |
3 | import android.content.ContentResolver;
4 | import android.content.Context;
5 | import android.test.AndroidTestCase;
6 | import android.test.mock.MockContext;
7 |
8 | import org.apache.commons.lang3.RandomStringUtils;
9 | import org.apache.commons.lang3.StringUtils;
10 |
11 | import java.util.Arrays;
12 |
13 | @SuppressWarnings({"Assert", "Deprecated"})
14 | public class LegacyEncryptionTest extends AndroidTestCase {
15 |
16 | public void testTooShortPrivateKey() throws Exception {
17 | try {
18 | new Encryption("?");
19 | fail();
20 | } catch (IllegalArgumentException e) {
21 | // OK
22 | }
23 | }
24 |
25 | public void testTooLongPrivateKey() throws Exception {
26 | try {
27 | new Encryption(StringUtils.repeat(".", Encryption.KEY_LENGTH+1));
28 | fail();
29 | } catch (IllegalArgumentException e) {
30 | // OK
31 | }
32 | }
33 |
34 |
35 | public void testEncryptDecrypt() throws Exception {
36 | for (int privateKeyPattern = 0; privateKeyPattern < 10; privateKeyPattern++) {
37 | String privateKey = RandomStringUtils.randomAscii(16);
38 | Encryption encryption = new Encryption(privateKey);
39 |
40 | for (int len = 1; len < 10000; len *= 2) {
41 | for (int i = 0; i < 100; i++) {
42 | String s = RandomStringUtils.randomAscii(len);
43 | String encrypted = encryption.encrypt(s);
44 | String decrypted = encryption.decrypt(encrypted);
45 | assert !s.equals(encrypted);
46 | assert decrypted.equals(s);
47 | }
48 | }
49 | }
50 | }
51 |
52 | public void testMultiByteString() throws Exception {
53 | String privateKey = RandomStringUtils.randomAscii(16);
54 | Encryption encryption = new Encryption(privateKey);
55 |
56 | String s = "日本語の混じった文字列。 Hello, world!";
57 | String encrypted = encryption.encrypt(s);
58 | String decrypted = encryption.decrypt(encrypted);
59 |
60 | assert !s.equals(encrypted);
61 | assert decrypted.equals(s);
62 |
63 | String decrypted2nd = encryption.decrypt(encrypted);
64 |
65 | assert decrypted2nd.equals(decrypted);
66 | }
67 |
68 | public void testUsingDefaultPrivateKey() throws Exception {
69 | Encryption encryption = new Encryption(getContext());
70 |
71 | String s = "Hello, world!";
72 | String encrypted = encryption.encrypt(s);
73 | String decrypted = encryption.decrypt(encrypted);
74 |
75 | assert !s.equals(encrypted);
76 | assert decrypted.equals(s);
77 |
78 | String decrypted2nd = new Encryption(getContext()).decrypt(encrypted);
79 |
80 | assert decrypted2nd.equals(decrypted);
81 | }
82 |
83 | public void testBadEncryption() throws Exception {
84 | Encryption encryption = new Encryption(getContext());
85 |
86 | try {
87 | encryption.decrypt("foo");
88 | fail();
89 | } catch (Encryption.UnexpectedDecryptionStateException e) {
90 | // ok
91 | }
92 | }
93 | }
94 |
95 |
--------------------------------------------------------------------------------
/lib/src/androidTest/java/com/github/gfx/util/encrypt/EncryptionTest.java:
--------------------------------------------------------------------------------
1 | package com.github.gfx.util.encrypt;
2 |
3 | import org.apache.commons.lang3.RandomStringUtils;
4 | import org.apache.commons.lang3.StringUtils;
5 |
6 | import android.annotation.TargetApi;
7 | import android.content.ContentResolver;
8 | import android.content.Context;
9 | import android.os.Build;
10 | import android.test.AndroidTestCase;
11 | import android.test.mock.MockContext;
12 | import java.util.Arrays;
13 |
14 | @SuppressWarnings("Assert")
15 | public class EncryptionTest extends AndroidTestCase {
16 | private boolean defaultCipherNotAvailable() {
17 | return Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH;
18 | }
19 |
20 | public void testDefaultPrivateKeyForContext() throws Exception {
21 | final Context context = getContext();
22 |
23 | byte[] k1 = Encryption.getDefaultPrivateKey(new MockContext() {
24 | @Override
25 | public String getPackageName() {
26 | return "a";
27 | }
28 |
29 | @Override
30 | public ContentResolver getContentResolver() {
31 | return context.getContentResolver();
32 | }
33 | });
34 | byte[] k2 = Encryption.getDefaultPrivateKey(new MockContext() {
35 | @Override
36 | public String getPackageName() {
37 | return "b";
38 | }
39 |
40 | @Override
41 | public ContentResolver getContentResolver() {
42 | return context.getContentResolver();
43 | }
44 | });
45 |
46 | assert !Arrays.equals(k1, k2);
47 | }
48 |
49 | public void testTooShortPrivateKey() throws Exception {
50 | if (defaultCipherNotAvailable()) return;
51 |
52 | try {
53 | new Encryption(Encryption.getDefaultCipher(), "?");
54 | fail();
55 | } catch (IllegalArgumentException e) {
56 | // OK
57 | }
58 | }
59 |
60 | public void testTooLongPrivateKey() throws Exception {
61 | if (defaultCipherNotAvailable()) return;
62 |
63 | try {
64 | new Encryption(Encryption.getDefaultCipher(), StringUtils.repeat(".", Encryption.KEY_LENGTH+1));
65 | fail();
66 | } catch (IllegalArgumentException e) {
67 | // OK
68 | }
69 | }
70 |
71 |
72 | public void testEncryptDecrypt() throws Exception {
73 | if (defaultCipherNotAvailable()) return;
74 |
75 | for (int privateKeyPattern = 0; privateKeyPattern < 10; privateKeyPattern++) {
76 | String privateKey = RandomStringUtils.randomAscii(16);
77 | Encryption encryption = new Encryption(Encryption.getDefaultCipher(), privateKey);
78 |
79 | for (int len = 1; len < 10000; len *= 2) {
80 | for (int i = 0; i < 100; i++) {
81 | String s = RandomStringUtils.randomAscii(len);
82 | String encrypted = encryption.encrypt(s);
83 | String decrypted = encryption.decrypt(encrypted);
84 | assert !s.equals(encrypted);
85 | assert decrypted.equals(s);
86 | }
87 | }
88 | }
89 | }
90 |
91 | public void testMultiByteString() throws Exception {
92 | if (defaultCipherNotAvailable()) return;
93 |
94 | String privateKey = RandomStringUtils.randomAscii(16);
95 | Encryption encryption = new Encryption(Encryption.getDefaultCipher(), privateKey);
96 |
97 | String s = "日本語の混じった文字列。 Hello, world!";
98 | String encrypted = encryption.encrypt(s);
99 | String decrypted = encryption.decrypt(encrypted);
100 |
101 | assert !s.equals(encrypted);
102 | assert decrypted.equals(s);
103 |
104 | String decrypted2nd = encryption.decrypt(encrypted);
105 |
106 | assert decrypted2nd.equals(decrypted);
107 | }
108 |
109 | public void testUsingDefaultPrivateKey() throws Exception {
110 | if (defaultCipherNotAvailable()) return;
111 |
112 | Encryption encryption = new Encryption(Encryption.getDefaultCipher(), getContext());
113 |
114 | String s = "Hello, world!";
115 | String encrypted = encryption.encrypt(s);
116 | String decrypted = encryption.decrypt(encrypted);
117 |
118 | assert !s.equals(encrypted);
119 | assert decrypted.equals(s);
120 |
121 | String decrypted2nd = new Encryption(Encryption.getDefaultCipher(), getContext()).decrypt(encrypted);
122 |
123 | assert decrypted2nd.equals(decrypted);
124 | }
125 |
126 | public void testBadEncryption() throws Exception {
127 | if (defaultCipherNotAvailable()) return;
128 |
129 | Encryption encryption = new Encryption(Encryption.getDefaultCipher(), getContext());
130 |
131 | try {
132 | encryption.decrypt("foo");
133 | fail();
134 | } catch (Encryption.UnexpectedDecryptionStateException e) {
135 | // ok
136 | }
137 | }
138 | }
139 |
140 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/github/gfx/util/encrypt/Encryption.java:
--------------------------------------------------------------------------------
1 | package com.github.gfx.util.encrypt;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.annotation.TargetApi;
5 | import android.content.ContentResolver;
6 | import android.content.Context;
7 | import android.os.Build;
8 | import android.provider.Settings;
9 | import android.support.annotation.NonNull;
10 | import android.util.Base64;
11 |
12 | import java.nio.charset.Charset;
13 | import java.security.MessageDigest;
14 | import java.security.NoSuchAlgorithmException;
15 | import java.security.NoSuchProviderException;
16 |
17 | import javax.crypto.Cipher;
18 | import javax.crypto.NoSuchPaddingException;
19 | import javax.crypto.spec.IvParameterSpec;
20 | import javax.crypto.spec.SecretKeySpec;
21 |
22 | /**
23 | * This class performs encryption and decryption for plain texts.
24 | * Note that this class is not thread-safe so you have to lock calling methods
25 | * explicitly.
26 | */
27 | @SuppressLint("Assert")
28 | public class Encryption {
29 |
30 | private static final String TAG = Encryption.class.getSimpleName();
31 |
32 | /**
33 | * The default security provider, "AndroidOpenSSL", which is not available on Android 2.3.x.
34 | */
35 | public static final String DEFAULT_PROVIDER = "AndroidOpenSSL";
36 |
37 | /**
38 | * The default algorithm mode, "AES/CBC/PKCS5Padding".
39 | */
40 | public static final String DEFAULT_ALGORITHM_MODE = "AES/CBC/PKCS5Padding";
41 |
42 | private static final String LEGACY_ALGORITHM_MODE = "AES/CTR/PKCS5Padding"; // CTR/PKCS5Padding makes no sense
43 |
44 | private static final Charset CHARSET = Charset.forName("UTF-8");
45 |
46 | public static final int KEY_LENGTH = 128 / 8;
47 |
48 | /**
49 | * @return A {@link javax.crypto.Cipher} instance with "AES/CBC/PKC5Padding" transformation.
50 | */
51 | @NonNull
52 | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
53 | public static Cipher getDefaultCipher() {
54 | try {
55 | return Cipher.getInstance(DEFAULT_ALGORITHM_MODE, DEFAULT_PROVIDER);
56 | } catch (NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException e) {
57 | throw new AssertionError(e);
58 | }
59 | }
60 |
61 | @Deprecated
62 | @NonNull
63 | public static Cipher getLegacyDefaultCipher() {
64 | try {
65 | return Cipher.getInstance(LEGACY_ALGORITHM_MODE);
66 | } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
67 | throw new AssertionError(e);
68 | }
69 | }
70 |
71 | @NonNull
72 | public static byte[] getDefaultPrivateKey(@NonNull Context context) {
73 | ContentResolver contentResolver = context.getContentResolver();
74 | byte[] androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
75 | .getBytes(CHARSET);
76 | assert androidId.length == KEY_LENGTH;
77 |
78 | byte[] packageDigest = md5(context.getPackageName().getBytes(CHARSET));
79 | assert packageDigest.length == KEY_LENGTH;
80 |
81 | for (int i = 0; i < androidId.length; i++) {
82 | packageDigest[i] ^= androidId[i];
83 | }
84 | return packageDigest; // mix of androidId and packageDigest
85 | }
86 |
87 | private static byte[] md5(byte[] value) {
88 | MessageDigest md5;
89 | try {
90 | md5 = MessageDigest.getInstance("MD5");
91 | } catch (NoSuchAlgorithmException e) {
92 | throw new AssertionError(e);
93 | }
94 | return md5.digest(value);
95 | }
96 |
97 |
98 | @NonNull
99 | private static SecretKeySpec createKeySpec(@NonNull Cipher cipher, @NonNull byte[] privateKey) {
100 | if (privateKey.length < KEY_LENGTH) {
101 | throw new IllegalArgumentException("private key is too short."
102 | + " Expected=" + KEY_LENGTH + " but got=" + privateKey.length);
103 | } else if (privateKey.length > KEY_LENGTH) {
104 | throw new IllegalArgumentException("private key is too long."
105 | + " Expected=" + KEY_LENGTH + " but got=" + privateKey.length);
106 | }
107 | return new SecretKeySpec(privateKey, cipher.getAlgorithm());
108 | }
109 |
110 |
111 | private final SecretKeySpec secretKeySpec;
112 |
113 | private final Cipher cipher;
114 |
115 | @Deprecated
116 | public Encryption(@NonNull Context context) {
117 | this(getLegacyDefaultCipher(), getDefaultPrivateKey(context));
118 | }
119 |
120 | @Deprecated
121 | public Encryption(@NonNull String privateKey) {
122 | this(getLegacyDefaultCipher(), privateKey.getBytes(CHARSET));
123 | }
124 |
125 | @Deprecated
126 | public Encryption(@NonNull byte[] privateKey) {
127 | this(getLegacyDefaultCipher(), privateKey);
128 | }
129 |
130 | public Encryption(@NonNull Cipher cipher, @NonNull Context context) {
131 | this(cipher, getDefaultPrivateKey(context));
132 | }
133 |
134 | public Encryption(@NonNull Cipher cipher, @NonNull String privateKey) {
135 | this(cipher, privateKey.getBytes(CHARSET));
136 | }
137 |
138 | public Encryption(@NonNull Cipher cipher, @NonNull byte[] privateKey) {
139 | this(cipher, createKeySpec(cipher, privateKey));
140 | }
141 |
142 | public Encryption(@NonNull Cipher cipher, @NonNull SecretKeySpec secretKeySpec) {
143 | this.cipher = cipher;
144 | this.secretKeySpec = secretKeySpec;
145 | }
146 |
147 | @NonNull
148 | public String encrypt(@NonNull String plainText) {
149 | byte[] encrypted;
150 |
151 | try {
152 | cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
153 | encrypted = cipher.doFinal(plainText.getBytes(CHARSET));
154 | } catch (Exception e) {
155 | throw new UnexpectedEncryptionStateException(e);
156 | }
157 | byte[] iv = cipher.getIV();
158 |
159 | byte[] buffer = new byte[iv.length + encrypted.length];
160 | System.arraycopy(iv, 0, buffer, 0, iv.length);
161 | System.arraycopy(encrypted, 0, buffer, iv.length, encrypted.length);
162 | return Base64.encodeToString(buffer, Base64.NO_WRAP);
163 | }
164 |
165 | @NonNull
166 | public String decrypt(@NonNull String encrypted) {
167 | byte[] buffer = Base64.decode(encrypted.getBytes(CHARSET), Base64.NO_WRAP);
168 | byte[] decrypted;
169 |
170 | try {
171 | cipher.init(Cipher.DECRYPT_MODE, secretKeySpec,
172 | new IvParameterSpec(buffer, 0, KEY_LENGTH));
173 | decrypted = cipher.doFinal(buffer, KEY_LENGTH, buffer.length - KEY_LENGTH);
174 | } catch (Exception e) {
175 | throw new UnexpectedDecryptionStateException(e);
176 | }
177 | return new String(decrypted, CHARSET);
178 | }
179 |
180 | public class UnexpectedStateException extends RuntimeException {
181 |
182 | public UnexpectedStateException(Throwable throwable) {
183 | super(throwable);
184 | }
185 | }
186 |
187 | public class UnexpectedEncryptionStateException extends UnexpectedStateException {
188 |
189 | public UnexpectedEncryptionStateException(Throwable throwable) {
190 | super(throwable);
191 | }
192 | }
193 |
194 | public class UnexpectedDecryptionStateException extends UnexpectedStateException {
195 |
196 | public UnexpectedDecryptionStateException(Throwable throwable) {
197 | super(throwable);
198 | }
199 | }
200 |
201 | }
202 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/github/gfx/util/encrypt/EncryptedSharedPreferences.java:
--------------------------------------------------------------------------------
1 | package com.github.gfx.util.encrypt;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.annotation.TargetApi;
5 | import android.content.Context;
6 | import android.content.SharedPreferences;
7 | import android.os.Build;
8 | import android.support.annotation.NonNull;
9 | import android.support.annotation.Nullable;
10 | import android.util.Base64;
11 |
12 | import java.nio.charset.Charset;
13 | import java.util.HashMap;
14 | import java.util.IdentityHashMap;
15 | import java.util.Map;
16 | import java.util.Set;
17 |
18 | import javax.crypto.Cipher;
19 |
20 | /**
21 | * A {@link android.content.SharedPreferences} implementation where its values are encrypted by
22 | * {@link com.github.gfx.util.encrypt.Encryption}.
23 | *
24 | * @see com.github.gfx.util.encrypt.Encryption
25 | */
26 | public class EncryptedSharedPreferences implements SharedPreferences {
27 |
28 | @NonNull
29 | private static Charset CHARSET = Charset.forName("UTF-8");
30 |
31 | /* package */
32 | @NonNull
33 | static String getDefaultPreferenceName(@NonNull Context context) {
34 | return context.getPackageName() + "_preferences_encrypted";
35 | }
36 |
37 | @NonNull
38 | private static SharedPreferences getDefaultSharedPreferences(@NonNull Context context) {
39 | String preferenceName = getDefaultPreferenceName(context);
40 | return context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
41 | }
42 |
43 | private final SharedPreferences base;
44 |
45 | private final Encryption encryption;
46 |
47 | private final IdentityHashMap
48 | listenerWrappers = new IdentityHashMap<>();
49 |
50 | /**
51 | * Creates a default wrapper class for {@link android.content.Context}. The private key for
52 | * {@link com.github.gfx.util.encrypt.Encryption} is determined by {@code
53 | * android.provider.Settings.Secure.ANDROID_ID}.
54 | *
55 | * @param cipher - A {@link javax.crypto.Cipher} instance. Use {@code Encryption.getDefaultCipher()} if you don't want to think about it.
56 | * @param context - an application context used to get a base {@link android.content.SharedPreferences}
57 | * and {@link com.github.gfx.util.encrypt.Encryption}
58 | */
59 | public EncryptedSharedPreferences(@NonNull Cipher cipher, @NonNull Context context) {
60 | this(getDefaultSharedPreferences(context), new Encryption(cipher, context));
61 | }
62 |
63 | public EncryptedSharedPreferences(@NonNull Cipher cipher, @NonNull SharedPreferences base,
64 | @NonNull Context contextForDefaultPrivateKey) {
65 | this(base, new Encryption(cipher, contextForDefaultPrivateKey));
66 | }
67 |
68 | public EncryptedSharedPreferences(@NonNull Cipher cipher, @NonNull SharedPreferences base,
69 | @NonNull String privateKey) {
70 | this(base, new Encryption(cipher, privateKey));
71 | }
72 |
73 | public EncryptedSharedPreferences(@NonNull SharedPreferences base,
74 | @NonNull Encryption encryption) {
75 | this.base = base;
76 | this.encryption = encryption;
77 | }
78 |
79 | @Deprecated
80 | public EncryptedSharedPreferences(@NonNull Context context) {
81 | this(getDefaultSharedPreferences(context), new Encryption(context));
82 | }
83 |
84 | @Deprecated
85 | public EncryptedSharedPreferences(@NonNull SharedPreferences base,
86 | @NonNull Context contextForDefaultPrivateKey) {
87 | this(base, new Encryption(contextForDefaultPrivateKey));
88 | }
89 |
90 | @Deprecated
91 | public EncryptedSharedPreferences(@NonNull SharedPreferences base,
92 | @NonNull String privateKey) {
93 | this(base, new Encryption(privateKey));
94 | }
95 |
96 |
97 | @NonNull
98 | private String encodeKey(@NonNull String value) {
99 | return Base64.encodeToString(value.getBytes(CHARSET), Base64.NO_WRAP);
100 | }
101 |
102 | @NonNull
103 | private String decodeKey(@NonNull String value) {
104 | return new String(Base64.decode(value.getBytes(CHARSET), Base64.NO_WRAP), CHARSET);
105 | }
106 |
107 | @NonNull
108 | private String encodeValue(@NonNull String value) {
109 | return encryption.encrypt(value);
110 | }
111 |
112 | @NonNull
113 | private String decodeValue(@NonNull String value) {
114 | return encryption.decrypt(value);
115 | }
116 |
117 | @Override
118 | public synchronized Map getAll() {
119 | Map newMap = new HashMap<>();
120 | for (Map.Entry entry : base.getAll().entrySet()) {
121 | String realKey = decodeKey(entry.getKey());
122 | if (entry.getValue() != null) {
123 | String encrypted = (String) entry.getValue();
124 | newMap.put(realKey, decodeValue(encrypted));
125 | } else {
126 | newMap.put(realKey, null);
127 | }
128 | }
129 | return newMap;
130 | }
131 |
132 | @Override
133 | @Nullable
134 | public synchronized String getString(@NonNull String key, @Nullable String defValue) {
135 | String realKey = encodeKey(key);
136 | String encoded = base.getString(realKey, null);
137 | return encoded != null ? decodeValue(encoded) : defValue;
138 | }
139 |
140 | @Override
141 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
142 | public synchronized Set getStringSet(@NonNull String key, Set defValues) {
143 | throw new UnsupportedOperationException();
144 | }
145 |
146 | @Override
147 | public synchronized int getInt(@NonNull String key, int defValue) {
148 | String value = getString(key, null);
149 | return value != null ? Integer.parseInt(value) : defValue;
150 | }
151 |
152 | @Override
153 | public synchronized long getLong(@NonNull String key, long defValue) {
154 | String value = getString(key, null);
155 | return value != null ? Long.parseLong(value) : defValue;
156 | }
157 |
158 | @Override
159 | public synchronized float getFloat(@NonNull String key, float defValue) {
160 | String value = getString(key, null);
161 | return value != null ? Float.parseFloat(value) : defValue;
162 | }
163 |
164 | @Override
165 | public synchronized boolean getBoolean(@NonNull String key, boolean defValue) {
166 | String value = getString(key, null);
167 | return value != null ? Boolean.parseBoolean(value) : defValue;
168 | }
169 |
170 | @Override
171 | public synchronized boolean contains(@NonNull String key) {
172 | String realKey = encodeKey(key);
173 | return base.contains(realKey);
174 | }
175 |
176 | @SuppressLint("CommitPrefEdits")
177 | @Override
178 | public Editor edit() {
179 | return new EncryptedEditor(base.edit());
180 | }
181 |
182 | @Override
183 | public void registerOnSharedPreferenceChangeListener(
184 | @NonNull final OnSharedPreferenceChangeListener listener) {
185 | OnSharedPreferenceChangeListener wrapper = new OnSharedPreferenceChangeListener() {
186 | @Override
187 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
188 | listener.onSharedPreferenceChanged(EncryptedSharedPreferences.this, decodeKey(key));
189 | }
190 | };
191 | listenerWrappers.put(listener, wrapper);
192 | base.registerOnSharedPreferenceChangeListener(wrapper);
193 | }
194 |
195 | @Override
196 | public void unregisterOnSharedPreferenceChangeListener(
197 | @NonNull OnSharedPreferenceChangeListener listener) {
198 | OnSharedPreferenceChangeListener wrapper = listenerWrappers.get(listener);
199 | if (wrapper != null) {
200 | listenerWrappers.remove(listener);
201 | base.unregisterOnSharedPreferenceChangeListener(wrapper);
202 | }
203 | }
204 |
205 | @Override
206 | protected void finalize() throws Throwable {
207 | for (OnSharedPreferenceChangeListener w : listenerWrappers.values()) {
208 | base.unregisterOnSharedPreferenceChangeListener(w);
209 | }
210 | super.finalize();
211 | }
212 |
213 | private class EncryptedEditor implements Editor {
214 |
215 | private final Editor editor;
216 |
217 | private EncryptedEditor(@NonNull Editor editor) {
218 | this.editor = editor;
219 | }
220 |
221 | @Override
222 | public synchronized Editor putString(@NonNull String key, @Nullable String value) {
223 | String realKey = encodeKey(key);
224 | editor.putString(realKey, value != null ? encodeValue(value) : null);
225 | return this;
226 | }
227 |
228 | @Override
229 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
230 | public synchronized Editor putStringSet(String key, Set values) {
231 | throw new UnsupportedOperationException();
232 | }
233 |
234 | @Override
235 | public synchronized Editor putInt(String key, int value) {
236 | return putString(key, String.valueOf(value));
237 | }
238 |
239 | @Override
240 | public synchronized Editor putLong(String key, long value) {
241 | return putString(key, String.valueOf(value));
242 | }
243 |
244 | @Override
245 | public synchronized Editor putFloat(String key, float value) {
246 | return putString(key, String.valueOf(value));
247 | }
248 |
249 | @Override
250 | public synchronized Editor putBoolean(String key, boolean value) {
251 | return putString(key, String.valueOf(value));
252 | }
253 |
254 | @Override
255 | public synchronized Editor remove(String key) {
256 | String realKey = encodeKey(key);
257 | editor.remove(realKey);
258 | return this;
259 | }
260 |
261 | @Override
262 | public synchronized Editor clear() {
263 | editor.clear();
264 | return this;
265 | }
266 |
267 | @Override
268 | public synchronized boolean commit() {
269 | return editor.commit();
270 | }
271 |
272 | @Override
273 | public synchronized void apply() {
274 | editor.apply();
275 | }
276 | }
277 | }
278 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2014 FUJI Goro .
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/lib/src/androidTest/java/com/github/gfx/util/encrypt/EncryptedSharedPreferencesTest.java:
--------------------------------------------------------------------------------
1 | package com.github.gfx.util.encrypt;
2 |
3 | import org.apache.commons.io.FileUtils;
4 |
5 | import android.annotation.SuppressLint;
6 | import android.content.Context;
7 | import android.content.SharedPreferences;
8 | import android.os.Build;
9 | import android.preference.PreferenceManager;
10 | import android.test.AndroidTestCase;
11 | import android.util.Log;
12 |
13 | import java.io.File;
14 | import java.io.IOException;
15 | import java.util.ArrayList;
16 | import java.util.List;
17 | import java.util.Map;
18 | import java.util.concurrent.CountDownLatch;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | @SuppressLint("Assert")
22 | public class EncryptedSharedPreferencesTest extends AndroidTestCase {
23 | private boolean defaultCipherNotAvailable() {
24 | return Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH;
25 | }
26 |
27 | private SharedPreferences prefs;
28 |
29 | @Override
30 | public void setUp() throws Exception {
31 | super.setUp();
32 |
33 | if (defaultCipherNotAvailable()) return;
34 |
35 | Context context = getContext();
36 | assert context != null;
37 | prefs = new EncryptedSharedPreferences(Encryption.getDefaultCipher(), context);
38 | //prefs = PreferenceManager.getDefaultSharedPreferences(context);
39 | }
40 |
41 | @Override
42 | public void tearDown() throws Exception {
43 | if (defaultCipherNotAvailable()) return;
44 |
45 | if (false) {
46 | // dump the file content
47 | String sharedPrefsContent = slurpSharedPrefsFile(
48 | EncryptedSharedPreferences.getDefaultPreferenceName(getContext()));
49 | Log.d("TEST", sharedPrefsContent);
50 | }
51 | prefs.edit()
52 | .clear()
53 | .apply();
54 | prefs = null;
55 |
56 | super.tearDown();
57 | System.gc();
58 | }
59 |
60 | private String slurpSharedPrefsFile(String name) throws IOException {
61 | Context context = getContext();
62 | assert context != null;
63 | File appDir = context.getFilesDir().getParentFile();
64 | File sharedPrefsDir = new File(appDir, "shared_prefs");
65 | File sharedPrefsFile = new File(sharedPrefsDir, name + ".xml");
66 | return FileUtils.readFileToString(sharedPrefsFile, "UTF-8");
67 | }
68 |
69 | public void testConstructorInterfaces() throws Exception {
70 | if (defaultCipherNotAvailable()) return;
71 |
72 | SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getContext());
73 | new EncryptedSharedPreferences(Encryption.getDefaultCipher(), getContext());
74 | new EncryptedSharedPreferences(Encryption.getDefaultCipher(), p, getContext());
75 | new EncryptedSharedPreferences(Encryption.getDefaultCipher(), p, "0123456789abcdef");
76 | new EncryptedSharedPreferences(p, new Encryption(Encryption.getDefaultCipher(), "0123456789abcdef"));
77 | }
78 |
79 | public void testString() throws Exception {
80 | if (defaultCipherNotAvailable()) return;
81 |
82 | prefs.edit().putString("foo", "bar").apply();
83 |
84 | assert prefs.getString("foo", "*").equals("bar");
85 | }
86 |
87 | public void testStringDefaultValue() throws Exception {
88 | if (defaultCipherNotAvailable()) return;
89 |
90 | assert prefs.getString("foo", "*").equals("*");
91 | }
92 |
93 | public void testInt() throws Exception {
94 | if (defaultCipherNotAvailable()) return;
95 |
96 | prefs.edit().putInt("foo", 42).apply();
97 |
98 | assert prefs.getInt("foo", 10) == 42;
99 | }
100 |
101 | public void testIntDefaultValue() throws Exception {
102 | if (defaultCipherNotAvailable()) return;
103 |
104 | assert prefs.getInt("foo", 10) == 10;
105 | }
106 |
107 | public void testLong() throws Exception {
108 | if (defaultCipherNotAvailable()) return;
109 |
110 | prefs.edit().putLong("foo", 42L).apply();
111 |
112 | assert prefs.getLong("foo", 10L) == 42L;
113 | }
114 |
115 | public void testLongDefaultValue() throws Exception {
116 | if (defaultCipherNotAvailable()) return;
117 |
118 | assert prefs.getLong("foo", 10L) == 10L;
119 | }
120 |
121 | public void testFloat() throws Exception {
122 | if (defaultCipherNotAvailable()) return;
123 |
124 | prefs.edit().putFloat("foo", 42.1f).apply();
125 |
126 | assert prefs.getFloat("foo", 10.1f) == 42.1f;
127 | }
128 |
129 | public void testFloatDefaultValue() throws Exception {
130 | if (defaultCipherNotAvailable()) return;
131 |
132 | assert prefs.getFloat("foo", 10.1f) == 10.1f;
133 | }
134 |
135 | public void testBoolean() throws Exception {
136 | if (defaultCipherNotAvailable()) return;
137 |
138 | prefs.edit().putBoolean("foo", true).apply();
139 |
140 | assert prefs.getBoolean("foo", false);
141 | }
142 |
143 | public void testBooleanDefaultValue() throws Exception {
144 | if (defaultCipherNotAvailable()) return;
145 |
146 | assert prefs.getBoolean("foo", true);
147 | }
148 |
149 | public void testContains() throws Exception {
150 | if (defaultCipherNotAvailable()) return;
151 |
152 | prefs.edit().putString("foo", "bar").apply();
153 |
154 | assert prefs.contains("foo");
155 | assert !prefs.contains("bar");
156 | }
157 |
158 | public void testAll() throws Exception {
159 | if (defaultCipherNotAvailable()) return;
160 |
161 | prefs.edit()
162 | .putString("foo", "aaa")
163 | .putString("bar", "bbb")
164 | .apply();
165 |
166 | Map map = prefs.getAll();
167 | assert map.size() == 2;
168 | assert map.get("foo").equals("aaa");
169 | assert map.get("bar").equals("bbb");
170 | // TODO: other vale types?
171 | }
172 |
173 | public void testCommit() throws Exception {
174 | if (defaultCipherNotAvailable()) return;
175 |
176 | SharedPreferences.Editor editor = prefs.edit();
177 |
178 | editor.putString("foo", "bar");
179 |
180 | assert prefs.getString("foo", "*").equals("*");
181 |
182 | assert editor.commit();
183 |
184 | assert prefs.getString("foo", "*").equals("bar");
185 | }
186 |
187 | public void testRemove() throws Exception {
188 | if (defaultCipherNotAvailable()) return;
189 |
190 | SharedPreferences.Editor editor = prefs.edit();
191 |
192 | editor.putString("foo", "aaa");
193 | editor.putString("bar", "bbb");
194 | assert editor.commit();
195 |
196 | assert prefs.edit()
197 | .remove("bar")
198 | .commit();
199 |
200 | assert prefs.getString("foo", "*").equals("aaa");
201 | assert prefs.getString("bar", "*").equals("*");
202 | }
203 |
204 | public void testClear() throws Exception {
205 | if (defaultCipherNotAvailable()) return;
206 |
207 | SharedPreferences.Editor editor = prefs.edit();
208 |
209 | editor.putString("foo", "aaa");
210 | editor.putString("bar", "bbb");
211 | assert editor.commit();
212 |
213 | assert prefs.edit()
214 | .clear()
215 | .commit();
216 |
217 | assert prefs.getString("foo", "*").equals("*");
218 | assert prefs.getString("bar", "*").equals("*");
219 | }
220 |
221 | public void testFileEncrypted() throws Exception {
222 | if (defaultCipherNotAvailable()) return;
223 |
224 | final CountDownLatch latch = new CountDownLatch(1);
225 | prefs.registerOnSharedPreferenceChangeListener(
226 | new SharedPreferences.OnSharedPreferenceChangeListener() {
227 | @Override
228 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
229 | String key) {
230 | latch.countDown();
231 | }
232 | }
233 | );
234 | prefs.edit()
235 | .putString("foo", "xyzzy")
236 | .apply();
237 | assert latch.await(10, TimeUnit.SECONDS);
238 |
239 | String sharedPrefsContent = slurpSharedPrefsFile(
240 | EncryptedSharedPreferences.getDefaultPreferenceName(getContext()));
241 |
242 | assert !sharedPrefsContent.contains("xyzzy");
243 | }
244 |
245 | public void testRegisterOnSharedPreferenceChangeListenerForPut() throws Exception {
246 | if (defaultCipherNotAvailable()) return;
247 |
248 | String key = "testRegisterOnSharedPreferenceChangeListenerForPut";
249 |
250 | final CountDownLatch latch = new CountDownLatch(1);
251 | final List events = new ArrayList<>();
252 |
253 | prefs.registerOnSharedPreferenceChangeListener(
254 | new SharedPreferences.OnSharedPreferenceChangeListener() {
255 | @Override
256 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
257 | String key) {
258 | // prefs might be null depending on timing
259 | // assert sharedPreferences == prefs;
260 | events.add(key);
261 | latch.countDown();
262 | }
263 | }
264 | );
265 |
266 | assert prefs.edit().putString(key, "bar").commit();
267 | assert latch.await(10, TimeUnit.SECONDS);
268 |
269 | assert events.size() == 1;
270 | assert events.contains(key);
271 | }
272 |
273 | public void testUnregisterOnSharedPreferenceChangeListener() throws Exception {
274 | if (defaultCipherNotAvailable()) return;
275 |
276 | final CountDownLatch latch = new CountDownLatch(1);
277 | SharedPreferences.OnSharedPreferenceChangeListener listener
278 | = new SharedPreferences.OnSharedPreferenceChangeListener() {
279 | @Override
280 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
281 | latch.countDown();
282 | }
283 | };
284 |
285 | prefs.registerOnSharedPreferenceChangeListener(listener);
286 | prefs.unregisterOnSharedPreferenceChangeListener(listener);
287 |
288 | assert prefs.edit()
289 | .putString("testUnregisterOnSharedPreferenceChangeListener", "bar")
290 | .commit();
291 | assert !latch.await(10, TimeUnit.SECONDS) : "successfully timed-out!";
292 | }
293 |
294 | public void testDifferentPrivateKeys() throws Exception {
295 | if (defaultCipherNotAvailable()) return;
296 |
297 | SharedPreferences base = getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
298 |
299 | SharedPreferences prefs1 = new EncryptedSharedPreferences(Encryption.getDefaultCipher(), base, "012345678912345a");
300 | SharedPreferences prefs2 = new EncryptedSharedPreferences(Encryption.getDefaultCipher(), base, "012345678912345b");
301 |
302 | final CountDownLatch latch = new CountDownLatch(2);
303 | SharedPreferences.OnSharedPreferenceChangeListener listener
304 | = new SharedPreferences.OnSharedPreferenceChangeListener() {
305 | @Override
306 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
307 | String key) {
308 | latch.countDown();
309 | }
310 | };
311 |
312 | base.registerOnSharedPreferenceChangeListener(listener);
313 |
314 | prefs1.edit()
315 | .putString("foo", "1")
316 | .apply();
317 | prefs2.edit()
318 | .putString("bar", "2")
319 | .apply();
320 |
321 | assert latch.await(10, TimeUnit.SECONDS);
322 |
323 | assert prefs1.getString("foo", "*").equals("1");
324 |
325 | try {
326 | assert !prefs1.getString("bar", "*").equals("*");
327 | assert !prefs1.getString("bar", "1").equals("2");
328 | } catch (Encryption.UnexpectedDecryptionStateException e) {
329 | // ignore
330 | }
331 |
332 | base.unregisterOnSharedPreferenceChangeListener(listener);
333 | base.edit().clear().apply();
334 | }
335 | }
336 |
--------------------------------------------------------------------------------