一:儲存型別
- 資料庫儲存 :基於 OrmLite 架構,提供了資料庫底層加密能力。
- 鍵值對儲存 :基於 Android 原生的 SharedPreferences,同時進行了一定的包裝,提升了易用性。
- 檔案儲存 :基於 Android 原生 File,提供了檔案加密能力。
二:儲存方案
1. 資料庫儲存方案
(1) 架構
基於 OrmLite 架構,參考:【Android - 框架】之ORMLite的使用
(2) 安全性
在資料庫建立或者開啟的時候,傳入password SQLite加密方式
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
this.mPassword = null;
...
}
public SQLiteDatabase getWritableDatabase() {
synchronized(this) {
return this.getDatabaseLocked(true);
}
}
public SQLiteDatabase getReadableDatabase() {
synchronized(this) {
return this.getDatabaseLocked(false);
}
}
private SQLiteDatabase getDatabaseLocked(boolean writable) {
...
db = SQLiteDatabase.openOrCreateDatabase(dbFile.getAbsolutePath(), this.mFactory, this.mErrorHandler, this.mEnableWriteAheadLogging, this.mPassword);
} catch (SQLiteException var14) {
if(writable) {
throw var14;
}
...
}
複製程式碼
最終調SQLiteConnection.java
private void open() {
this.mConnectionPtr = nativeOpen(this.mConfiguration.path, this.mConfiguration.openFlags, this.mConfiguration.label, false, false);
this.setEncryptKey();
this.setForeignKeyModeFromConfiguration();
this.setWalModeFromConfiguration();
this.setJournalSizeLimit();
this.setAutoCheckpointInterval();
this.setLocaleFromConfiguration();
int functionCount = this.mConfiguration.customFunctions.size();
for(int i = 0; i < functionCount; ++i) {
SQLiteCustomFunction function = (SQLiteCustomFunction)this.mConfiguration.customFunctions.get(i);
nativeRegisterCustomFunction(this.mConnectionPtr, function);
}
}
private void setEncryptKey() {
if(!this.mConfiguration.isInMemoryDb() && !this.mIsReadOnlyConnection) {
String password = this.mConfiguration.password;
if(password != null) {
File encryptFile = new File(this.mConfiguration.path + "-encrypt");
if(encryptFile.exists()) {
this.execute("PRAGMA key='" + password + "';", (Object[])null, (Object)null);
} else {
this.execute("PRAGMA rekey='" + password + "';", (Object[])null, (Object)null);
try {
encryptFile.createNewFile();
} catch (IOException var4) {
Log.e("SQLiteConnection", "Can't touch " + encryptFile.getName() + ", can't rekey the database");
}
}
}
}
}
複製程式碼
(3) 使用便捷性
- 不用寫sql語句,建立資料庫繼承OrmLiteSqliteOpenHelper,建表通過JavaBean和註解的方式。增刪改查使用Dao的方式。
- 資料庫加密,在建立時傳入password即可。
2. 鍵值對儲存方案
(1) 架構
封裝類APSharedPreferences.java
private Context sContext = null;
private String mGroup = "alipay_default_sp"; // 組id,與檔名類似
private SharedPreferences mSP;
private int mMode = 0;
private Editor edit = null;
public boolean getBoolean(String key, boolean defValue) {
return this.getBoolean(this.getGroup(), key, defValue);
}
public String getString(String key, String defValue) {
return this.getString(this.getGroup(), key, defValue);
}
...
複製程式碼
管理類SharedPreferencesManager.java
private static LruCache<String, APSharedPreferences> spList = new LruCache(30); // 定義了一個最大長度為30的快取列表,使用lru演算法
public SharedPreferencesManager() {
}
public static APSharedPreferences getInstance(Context context, String groupId) {
return getInstance(context, groupId, 0);
}
public static APSharedPreferences getInstance(Context context, String groupId, int mode) {
if(context != null && !TextUtils.isEmpty(groupId)) {
APSharedPreferences sp = (APSharedPreferences)spList.get(groupId);
if(sp == null) {
Class var4 = SharedPreferencesManager.class;
synchronized(SharedPreferencesManager.class) {
sp = (APSharedPreferences)spList.get(groupId);
if(sp == null) {
sp = new APSharedPreferences(context, groupId, mode);
spList.put(groupId, sp);
}
}
}
return sp;
} else {
return null;
}
}
複製程式碼
(2) 加密
無
(3) 使用便捷性
- 對SharedPreferences api做了封裝,更方便使用
- 對檔案分組,便於管理,增加了增刪改操作。
- 使用LruCache,加快讀寫速度。
3. 檔案儲存方案
(1) 架構
- ZFile:該檔案型別儲存在 data/data/package_name/files 下。
- ZExternalFile:該檔案型別儲存在 sdcard/Android/data/package_name/files 下。
- ZFileInputStream/ZFileOutputStream:檔案儲存輸入輸出流,使用該流則不進行加解密。
- ZSecurityFileInputStream/ZSecurityFileOutputStream:檔案儲存安全輸入輸出流,使用該流則會
ZFile.java
public class ZFile extends BaseFile {
private static final long serialVersionUID = -1952946196402763362L;
// groupId為目錄,name為檔名,subPath為相對子路徑
public ZFile(Context context, String groupId, String name, String subPath) {
super(buildPath(context, groupId, name, subPath));
}
public ZFile(Context context, String groupId, String name) {
super(buildPath(context, groupId, name, (String)null));
}
private static String buildPath(Context context, String groupId, String name, String subPath) {
...
String path = "";
// 拼檔案路徑
String dir = context.getFilesDir() + File.separator + groupId + formatPath(subPath);
File fileDir = new File(dir);
if(!fileDir.exists()) {
fileDir.mkdirs();
}
path = dir + name;
return path;
...
}
}
複製程式碼
ZExternalFile.java
public class ZExternalFile extends BaseFile {
private static final String Tag = "ZExternalFile";
protected static final String ExtDataTunnel = "ExtDataTunnel";
private static final long serialVersionUID = -3489082633723468737L;
public ZExternalFile(Context context, String groupId, String name, String subPath) {
super(buildPath(context, groupId, name, subPath));
}
public ZExternalFile(Context context, String groupId, String name) {
super(buildPath(context, groupId, name, (String)null));
}
private static String buildPath(Context context, String groupId, String name, String subPath) {
...
File externalFilesDir = null;
try {
externalFilesDir = context.getExternalFilesDir(groupId);
} catch (Throwable var8) {
Log.w("ZExternalFile", "context.getExternalFilesDir(" + groupId + ") failed!", var8);
}
String path;
String dir;
if(externalFilesDir == null) {
Log.w("ZExternalFile", "externalFilesDir is null");
path = FileUtils.getSDPath();
if(TextUtils.isEmpty(path)) {
return "";
}
dir = path + File.separator + "ExtDataTunnel" + File.separator + "files" + File.separator + groupId;
externalFilesDir = new File(dir);
}
path = "";
dir = externalFilesDir.getAbsolutePath() + formatPath(subPath);
File fileDir = new File(dir);
if(!fileDir.isDirectory() || !fileDir.exists()) {
fileDir.mkdirs();
}
path = dir + name;
return path;
...
}
}
複製程式碼
ZSecurityFileOutputStream.java
public class ZSecurityFileOutputStream extends ZFileOutputStream {
public void write(byte[] buffer) throws IOException {
this.byteList.add(buffer);
this.byteSize += buffer.length;
}
public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException {
int size = byteCount;
if(byteCount > buffer.length) {
size = buffer.length;
}
byte[] sBuffer = new byte[size];
System.arraycopy(buffer, byteOffset, sBuffer, 0, size);
this.byteList.add(sBuffer);
this.byteSize += size;
}
// 在close的時候,才將資料加密並且寫入檔案
public void close() throws IOException {
byte[] finalByte = new byte[this.byteSize];
int pos = 0;
if(this.byteList != null && !this.byteList.isEmpty()) {
for(int i = 0; i < this.byteList.size(); ++i) {
byte[] item = (byte[])this.byteList.get(i);
if(this.byteSize >= pos + item.length) {
System.arraycopy(item, 0, finalByte, pos, item.length);
}
pos += item.length;
}
this.byteList.clear();
Object var6 = null;
byte[] enByte;
try {
// 加密
enByte = TaobaoSecurityEncryptor.encrypt(this.mContext, finalByte);
} catch (Exception var5) {
throw new IOException(var5);
}
super.write(enByte, 0, enByte.length);
super.close();
}
}
}
複製程式碼
ZSecurityFileInputStream.java
private void initBuffer() throws IOException {
int size = super.available();
byte[] enBuffer = new byte[size];
super.read(enBuffer, 0, enBuffer.length);
super.close();
try {
// 解密
this.mBuffer = TaobaoSecurityEncryptor.decrypt(this.mContext, enBuffer);
} catch (Exception var4) {
LoggerFactory.getTraceLogger().warn("ZSecurityFileInputStream", var4);
throw new IOException();
}
}
複製程式碼
(2) 安全性
ZSecurityFileInputStream和ZSecurityFileOutputStream具有加解密功能
(3) 使用便捷性
- ZFile和ZExternalFile使用相對路徑,檔案目錄名和檔名,省去了檔案路徑的拼接。
- ZSecurityFileInputStream和ZSecurityFileOutputStream封裝了加解密的方法