├── .idea
├── .name
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── vcs.xml
├── modules.xml
├── runConfigurations.xml
├── gradle.xml
├── compiler.xml
└── misc.xml
├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── itzs
│ │ │ └── testcipher
│ │ │ ├── CipherUtil.java
│ │ │ ├── MainActivity.java
│ │ │ └── CustomFileCipherUtil.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── itzs
│ │ │ └── testcipher
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── itzs
│ │ └── testcipher
│ │ └── ApplicationTest.java
├── build.gradle
└── proguard-rules.pro
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── Screenshot_2016-07-08-14-24-43.jpeg
├── .gitignore
├── README.md
├── gradle.properties
├── gradlew.bat
└── gradlew
/.idea/.name:
--------------------------------------------------------------------------------
1 | TestCipher
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | TestCipher
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Screenshot_2016-07-08-14-24-43.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/Screenshot_2016-07-08-14-24-43.jpeg
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhangSir/TestCipher/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Oct 21 11:34:03 PDT 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.8-all.zip
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/test/java/com/itzs/testcipher/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.itzs.testcipher;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/itzs/testcipher/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.itzs.testcipher;
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 | }
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.itzs.testcipher"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.3.0'
26 | }
27 |
--------------------------------------------------------------------------------
/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 D:\Android\Android-Studio\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 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TestCipher
2 | 简单的文件加密解密程序,主要用于解释文件加解密的原理流程;
3 |
4 | ##文件加解密的流程及原理
5 | 1、加密方法:存储文件时,从输入流中截取文件的字节数组,对字节数组进行加密,至于加密的方式和算法就可以视需求而定了,然后把加密后的字节数组写入到文件中,最后生成加密后的文件;
6 |
7 | 2、解密方法:同加密方法一样,只不过是对字节数据进行解密,最后生成明文文件;
8 |
9 | 3、加密算法:android系统本身引入了javax包的Cipher类,这个类里提供了各种各样的通用的加密方式,如AES对称加密等;该程序中有个CipherUtil工具类,里面有一些简单的使用Cipher进行AES加解密的方法;当然最好还是好好学习一下Cipher类的使用;
10 |
11 | 4、注意事项:
12 |
13 | a、如何判断一个文件是加密后的文件,最简单的方法就是对加密后的文件统一增加一个后缀名,
14 | 然后在解密之后将这个后缀名去除,还原回原有文件格式;
15 |
16 | 如:密文文件的统一后缀名为“.cipher”,明文文件名为"测试.txt",加密后的密文文件应该为“测试.txt.cipher”;
17 |
18 | b、加密文件时还有一个重要的注意事项,就是加密后的密文和明文的长度是否相同,
19 | 如果文件时一次读取出所有字节数组进行加密的话不用担心这个问题,
20 | 但是当对文件分次读取加密或分段加密的话,就不得不考虑这个问题了,最方便的方法就是保证明文和加密后的密文长度相同;
21 | 如果长度不同,由于是分段加密的,密文是由一段一段子密文拼接成的,
22 | 解密时会找不到每段子密文,因为不知道每段子密文的长度是多少;
23 |
24 | ##截图
25 | 
26 |
--------------------------------------------------------------------------------
/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/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
18 |
19 |
24 |
25 |
30 |
31 |
36 |
37 |
42 |
43 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itzs/testcipher/CipherUtil.java:
--------------------------------------------------------------------------------
1 | package com.itzs.testcipher;
2 |
3 | import java.security.NoSuchAlgorithmException;
4 | import java.security.SecureRandom;
5 |
6 | import javax.crypto.Cipher;
7 | import javax.crypto.KeyGenerator;
8 | import javax.crypto.SecretKey;
9 | import javax.crypto.spec.SecretKeySpec;
10 |
11 | /**
12 | * 使用系统Javax包中Cipher类进行加密解密的工具(这里使用AES对称加密方式)
13 | * Created by zhangshuo on 2016/6/28.
14 | */
15 | public class CipherUtil {
16 |
17 | private static byte[] getRawKey(byte[] seed) throws NoSuchAlgorithmException {
18 | SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); // 获得一个随机数,传入的参数为默认方式。
19 | sr.setSeed(seed); // 设置一个种子,这个种子一般是用户设定的密码。也可以是其它某个固定的字符串
20 | KeyGenerator keyGen = KeyGenerator.getInstance("AES"); // 获得一个key生成器(AES加密模式)
21 | keyGen.init(128, sr); // 设置密匙长度128位
22 | SecretKey key = keyGen.generateKey(); // 获得密匙
23 | byte[] raw = key.getEncoded(); // 返回密匙的byte数组供加解密使用
24 | return raw;
25 | }
26 |
27 | private static byte[] encry(byte[] raw, byte[] input) throws Exception { // 加密
28 | SecretKeySpec keySpec = new SecretKeySpec(raw, "AES"); // 根据上一步生成的密匙指定一个密匙(密匙二次加密?)
29 | Cipher cipher = Cipher.getInstance("AES"); // 获得Cypher实例对象
30 | cipher.init(Cipher.ENCRYPT_MODE, keySpec); // 初始化模式为加密模式,并指定密匙
31 | byte[] encode = cipher.doFinal(input); // 执行加密操作。 input为需要加密的byte数组
32 | return encode; // 返回加密后的密文(byte数组)
33 | }
34 |
35 | private static byte[] decry(byte[] raw, byte[] encode) throws Exception{ // 解密
36 | SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
37 | Cipher cipher = Cipher.getInstance("AES");
38 | cipher.init(Cipher.DECRYPT_MODE, keySpec); // 解密的的方法差不多,只是这里的模式不一样
39 | byte[] decode = cipher.doFinal(encode); // 加解密都通过doFinal方法来执行最终的实际操作
40 | return decode;
41 | }
42 |
43 | public static String decryptString(String seed, byte[] encode) throws Exception{
44 | byte[] raw = getRawKey(seed.getBytes());
45 | byte[] decode = decry(raw, encode);
46 | return new String(decode);
47 | }
48 |
49 | public static byte[] encryptString(String seed, String input) throws Exception{
50 | byte[] raw = getRawKey(seed.getBytes());
51 | byte[] encode = encry(raw, input.getBytes());
52 | // return new String(encode); // 加密后的byte数组转换成字符串时将出现问题。
53 | return encode;
54 | }
55 |
56 | private static String bytesToHexString(byte[] src){
57 | StringBuilder stringBuilder = new StringBuilder("");
58 | if (src == null || src.length <= 0) {
59 | return null;
60 | }
61 | for (int i = 0; i < src.length; i++) {
62 | int v = src[i] & 0xFF;
63 | String hv = Integer.toHexString(v);
64 | if (hv.length() < 2) {
65 | stringBuilder.append(0);
66 | }
67 | stringBuilder.append(hv);
68 | }
69 | return stringBuilder.toString();
70 | }
71 |
72 |
73 | private static byte[] hexStringToBytes(String hexString) {
74 | if (hexString == null || hexString.equals("")) {
75 | return null;
76 | }
77 | hexString = hexString.toUpperCase();
78 | int length = hexString.length() / 2;
79 | char[] hexChars = hexString.toCharArray();
80 | byte[] d = new byte[length];
81 | for (int i = 0; i < length; i++) {
82 | int pos = i * 2;
83 | d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
84 | }
85 | return d;
86 | }
87 |
88 | private static byte charToByte(char c) {
89 | return (byte) "0123456789ABCDEF".indexOf(c);
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itzs/testcipher/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.itzs.testcipher;
2 |
3 | import android.os.Handler;
4 | import android.os.Message;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.os.Bundle;
7 | import android.view.View;
8 | import android.widget.Button;
9 | import android.widget.EditText;
10 | import android.widget.TextView;
11 |
12 | public class MainActivity extends AppCompatActivity {
13 |
14 | private EditText etEncrypt, etDecrypt;
15 | private Button btnEncrypt, btnDecrypt;
16 | private TextView tvStatus;
17 |
18 | private Handler uiHandler = new Handler(){
19 | @Override
20 | public void handleMessage(Message msg) {
21 | super.handleMessage(msg);
22 | tvStatus.setText((String)msg.obj);
23 | }
24 | };
25 |
26 | @Override
27 | protected void onCreate(Bundle savedInstanceState) {
28 | super.onCreate(savedInstanceState);
29 | setContentView(R.layout.activity_main);
30 |
31 | this.initView();
32 | this.initListener();
33 | }
34 |
35 | private void initView(){
36 | etEncrypt = (EditText) findViewById(R.id.et_encrypt);
37 | etDecrypt = (EditText) findViewById(R.id.et_decrypt);
38 | btnEncrypt = (Button) findViewById(R.id.btn_encrypt);
39 | btnDecrypt = (Button) findViewById(R.id.btn_decrypt);
40 | tvStatus = (TextView) findViewById(R.id.tv_status);
41 | }
42 |
43 | private void initListener(){
44 |
45 | btnEncrypt.setOnClickListener(new View.OnClickListener() {
46 | @Override
47 | public void onClick(View v) {
48 | new Thread(new Runnable() {
49 | @Override
50 | public void run() {
51 | boolean isSuccess = CustomFileCipherUtil.encrypt(etEncrypt.getText().toString(), new CustomFileCipherUtil.CipherListener() {
52 | @Override
53 | public void onProgress(long current, long total) {
54 | Message msg = uiHandler.obtainMessage();
55 | msg.obj = "加密:" + current + "/" + total + "(" + current * 100 / total + "%)";
56 | uiHandler.sendMessage(msg);
57 | }
58 | });
59 | Message msg = uiHandler.obtainMessage();
60 | if(isSuccess){
61 | msg.obj = "加密成功";
62 | }else{
63 | msg.obj = "加密失败";
64 | }
65 | uiHandler.sendMessage(msg);
66 | }
67 | }).start();
68 | }
69 | });
70 | btnDecrypt.setOnClickListener(new View.OnClickListener() {
71 | @Override
72 | public void onClick(View v) {
73 | new Thread(new Runnable() {
74 | @Override
75 | public void run() {
76 | boolean isSuccess = CustomFileCipherUtil.decrypt(etDecrypt.getText().toString(), new CustomFileCipherUtil.CipherListener() {
77 | @Override
78 | public void onProgress(long current, long total) {
79 | Message msg = uiHandler.obtainMessage();
80 | msg.obj = "解密:" + current + "/" + total + "(" + current * 100 / total + "%)";
81 | uiHandler.sendMessage(msg);
82 | }
83 | });
84 | Message msg = uiHandler.obtainMessage();
85 | if(isSuccess){
86 | msg.obj = "解密成功";
87 | }else{
88 | msg.obj = "解密失败";
89 | }
90 | uiHandler.sendMessage(msg);
91 | }
92 | }).start();
93 | }
94 | });
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/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 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itzs/testcipher/CustomFileCipherUtil.java:
--------------------------------------------------------------------------------
1 | package com.itzs.testcipher;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.File;
6 | import java.io.RandomAccessFile;
7 | import java.nio.MappedByteBuffer;
8 | import java.nio.channels.FileChannel;
9 |
10 | /**自定义实现简单的文件加密解密工具
11 | * Created by zhangshuo on 2016/6/28.
12 | */
13 | public class CustomFileCipherUtil {
14 |
15 | /**
16 | * 加密后的文件的后缀
17 | */
18 | public static final String CIPHER_TEXT_SUFFIX = ".cipher";
19 |
20 | /**
21 | * 加解密时以32K个字节为单位进行加解密计算
22 | */
23 | private static final int CIPHER_BUFFER_LENGHT = 32 * 1024;
24 |
25 | /**
26 | * 加密,这里主要是演示加密的原理,没有用什么实际的加密算法
27 | *
28 | * @param filePath 明文文件绝对路径
29 | * @return
30 | */
31 | public static boolean encrypt(String filePath, CipherListener listener) {
32 | try {
33 | long startTime = System.currentTimeMillis();
34 | File f = new File(filePath);
35 | RandomAccessFile raf = new RandomAccessFile(f, "rw");
36 | long totalLenght = raf.length();
37 | FileChannel channel = raf.getChannel();
38 |
39 | long multiples = totalLenght / CIPHER_BUFFER_LENGHT;
40 | long remainder = totalLenght % CIPHER_BUFFER_LENGHT;
41 |
42 | MappedByteBuffer buffer = null;
43 | byte tmp;
44 | byte rawByte;
45 |
46 | //先对整除部分加密
47 | for(int i = 0; i < multiples; i++){
48 | buffer = channel.map(
49 | FileChannel.MapMode.READ_WRITE, i * CIPHER_BUFFER_LENGHT, (i + 1) * CIPHER_BUFFER_LENGHT);
50 |
51 | //此处的加密方法很简单,只是简单的异或计算
52 | for (int j = 0; j < CIPHER_BUFFER_LENGHT; ++j) {
53 | rawByte = buffer.get(j);
54 | tmp = (byte) (rawByte ^ j);
55 | buffer.put(j, tmp);
56 |
57 | if(null != listener){
58 | listener.onProgress(i * CIPHER_BUFFER_LENGHT + j, totalLenght);
59 | }
60 | }
61 | buffer.force();
62 | buffer.clear();
63 | }
64 |
65 | //对余数部分加密
66 | buffer = channel.map(
67 | FileChannel.MapMode.READ_WRITE, multiples * CIPHER_BUFFER_LENGHT, multiples * CIPHER_BUFFER_LENGHT + remainder);
68 |
69 | for (int j = 0; j < remainder; ++j) {
70 | rawByte = buffer.get(j);
71 | tmp = (byte) (rawByte ^ j);
72 | buffer.put(j, tmp);
73 |
74 | if(null != listener){
75 | listener.onProgress(multiples * CIPHER_BUFFER_LENGHT + j, totalLenght);
76 | }
77 | }
78 | buffer.force();
79 | buffer.clear();
80 |
81 | channel.close();
82 | raf.close();
83 |
84 | //对加密后的文件重命名,增加.cipher后缀
85 | // f.renameTo(new File(f.getPath() + CIPHER_TEXT_SUFFIX));
86 | Log.d("加密用时:", (System.currentTimeMillis() - startTime) /1000 + "s");
87 | return true;
88 | } catch (Exception e) {
89 | e.printStackTrace();
90 | return false;
91 | }
92 | }
93 |
94 |
95 | /**
96 | * 解密,这里主要是演示加密的原理,没有用什么实际的加密算法
97 | *
98 | * @param filePath 密文文件绝对路径,文件需要以.cipher结尾才会认为其实可解密密文
99 | * @return
100 | */
101 | public static boolean decrypt(String filePath, CipherListener listener) {
102 | try {
103 | long startTime = System.currentTimeMillis();
104 | File f = new File(filePath);
105 | // if(!f.getPath().toLowerCase().endsWith(CIPHER_TEXT_SUFFIX)){
106 | // //后缀不同,认为是不可解密的密文
107 | // return false;
108 | // }
109 |
110 | RandomAccessFile raf = new RandomAccessFile(f, "rw");
111 | long totalLenght = raf.length();
112 | FileChannel channel = raf.getChannel();
113 |
114 | long multiples = totalLenght / CIPHER_BUFFER_LENGHT;
115 | long remainder = totalLenght % CIPHER_BUFFER_LENGHT;
116 |
117 | MappedByteBuffer buffer = null;
118 | byte tmp;
119 | byte rawByte;
120 |
121 | //先对整除部分解密
122 | for(int i = 0; i < multiples; i++){
123 | buffer = channel.map(
124 | FileChannel.MapMode.READ_WRITE, i * CIPHER_BUFFER_LENGHT, (i + 1) * CIPHER_BUFFER_LENGHT);
125 |
126 | //此处的解密方法很简单,只是简单的异或计算
127 | for (int j = 0; j < CIPHER_BUFFER_LENGHT; ++j) {
128 | rawByte = buffer.get(j);
129 | tmp = (byte) (rawByte ^ j);
130 | buffer.put(j, tmp);
131 |
132 | if(null != listener){
133 | listener.onProgress(i * CIPHER_BUFFER_LENGHT + j, totalLenght);
134 | }
135 | }
136 | buffer.force();
137 | buffer.clear();
138 | }
139 |
140 | //对余数部分解密
141 | buffer = channel.map(
142 | FileChannel.MapMode.READ_WRITE, multiples * CIPHER_BUFFER_LENGHT, multiples * CIPHER_BUFFER_LENGHT + remainder);
143 |
144 | for (int j = 0; j < remainder; ++j) {
145 | rawByte = buffer.get(j);
146 | tmp = (byte) (rawByte ^ j);
147 | buffer.put(j, tmp);
148 |
149 | if(null != listener){
150 | listener.onProgress(multiples * CIPHER_BUFFER_LENGHT + j, totalLenght);
151 | }
152 | }
153 | buffer.force();
154 | buffer.clear();
155 |
156 | channel.close();
157 | raf.close();
158 |
159 | //对加密后的文件重命名,增加.cipher后缀
160 | // f.renameTo(new File(f.getPath().substring(f.getPath().toLowerCase().indexOf(CIPHER_TEXT_SUFFIX))));
161 |
162 | Log.d("解密用时:", (System.currentTimeMillis() - startTime) / 1000 + "s");
163 | return true;
164 | } catch (Exception e) {
165 | e.printStackTrace();
166 | return false;
167 | }
168 | }
169 |
170 | /**
171 | * 用于加解密进度的监听器
172 | */
173 | public interface CipherListener{
174 | void onProgress(long current, long total);
175 | }
176 | }
177 |
--------------------------------------------------------------------------------