文件加密处理类

来源:互联网 发布:js 导出excel插件 编辑:程序博客网 时间:2024/06/14 02:11
package com.bonc.dp.tools;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.ObjectInputStream.GetField;
import java.util.Random;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

/**
* 文件加密处理类
*
*/
public class Encryption {

private Context m;

public Encryption(Context m) {
this.m = m;
}

/**
* 获得需要加密的文件
* @param path 文件路径
* @return RandomAccessFile
*/
public RandomAccessFile getFile(String path){
try {
RandomAccessFile file = new RandomAccessFile(path, "rw");
return file;
} catch (Exception e) {
new Exception(e.toString());
}
return null;
}

/**
* 加密文件<br>
* 加密思路:<br>
* 在文件字节流默认位置插入随机字段,并把原文件中的字节流通过sharedPreference保存起来.<br>
* sharedPreference结构:
* 文件名:encryption<br>
* position: long类型 表示加密时从哪个位置开始加密<br>
* key: String类型 原文件中的字节流
*
* @param file
* @param position 加密位置
* @param key 加密字段
*/
public void encryption(RandomAccessFile file){
try {

Random r = new Random();

//生成随机字节流
int length = r.nextInt(1024) + 1;
byte[] pass = new byte[length];
for(int i=0; i<length; i++){
pass[i] = new Byte(r.nextInt(128) + "");
}

//生成随机位置
//long position = (long)(file.length() * Math.random());
long position = 0;

//将文件流中指定位置,长度与随机字节流相等的原文件中的字节提取
file.seek(position);
byte[] buffer = new byte[length];
int off = file.read(buffer);

//保存原文件中的字节流
StringBuffer sb = new StringBuffer();
sb.setLength(0);
for(int i=0; i<off; i++){
sb.append(buffer[i]).append(",");
}
sb.deleteCharAt(sb.length() - 1);
String key = sb.toString();
SharedPreferences sp = m.getSharedPreferences("encryption", Context.MODE_PRIVATE);
Editor e = sp.edit();
e.putLong("position", position);
e.putString("key", key);
e.commit();

//使用随机字段覆盖到指定字节流
file.seek(position);
file.write(pass, 0, off);

} catch (Exception e) {
new Exception(e.toString());
}

}

/**
* 解密文件
* @param file
* @param position操作位置
*/
public void decrypt(RandomAccessFile file) throws Exception{
//读取原文件加密信息
SharedPreferences sp = m.getSharedPreferences("encryption", Context.MODE_PRIVATE);
long position = sp.getLong("position", -1);
String key = sp.getString("key", "");

//如果有加密信息
if(position == -1){

}else{
file.seek(position);
String[] strs = key.split(",");
byte[] buffer = new byte[strs.length];

int off = file.read(buffer);
file.seek(position);
byte[] b = new byte[off];
for(int i=0;i<off; i++){
b[i] = new Byte(strs[i]);
}

//还原字节流
file.write(b, 0, off);

//将加密信息清空
sp.edit().clear().commit();
}
}

}


原创粉丝点击