提交 7dc33932 编写于 作者: guolin's avatar guolin

Add encryption for saving data.

上级 3a270ae2
......@@ -27,6 +27,7 @@ import org.litepal.parser.LitePalConfig;
import org.litepal.parser.LitePalParser;
import org.litepal.tablemanager.Connector;
import org.litepal.util.BaseUtility;
import org.litepal.util.CipherUtil;
import org.litepal.util.Const;
import org.litepal.util.SharedUtil;
......@@ -133,9 +134,14 @@ public class LitePal {
return false;
}
public static void aesKey(String key) {
CipherUtil.aesKey = key;
}
/**
* Remove the database version in SharedPreferences file.
* @param dbName
* Name of database to delete.
*/
private static void removeVersionInSharedPreferences(String dbName) {
if (isDefaultDatabase(dbName)) {
......
/*
* Copyright (C) Tony Green, LitePal Framework Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.litepal.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used for adding constraints to a column. Note that this annotation won't affect id column.
*
* @author Tony Green
* @since 1.6
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Encrypt {
String MD5 = "MD5";
String AES = "AES";
/**
* Set the algorithm for encryption.
*/
String algorithm();
}
......@@ -22,11 +22,14 @@ import android.database.sqlite.SQLiteDatabase;
import android.util.SparseArray;
import org.litepal.LitePalBase;
import org.litepal.annotation.Column;
import org.litepal.annotation.Encrypt;
import org.litepal.crud.model.AssociationsInfo;
import org.litepal.exceptions.DataSupportException;
import org.litepal.exceptions.DatabaseGenerateException;
import org.litepal.tablemanager.model.GenericModel;
import org.litepal.util.BaseUtility;
import org.litepal.util.CipherUtil;
import org.litepal.util.Const;
import org.litepal.util.DBUtility;
......@@ -266,6 +269,15 @@ abstract class DataHandler extends LitePalBase {
Date date = (Date) fieldValue;
fieldValue = date.getTime();
}
Encrypt annotation = field.getAnnotation(Encrypt.class);
if (annotation != null && "java.lang.String".equals(field.getType().getName())) {
String algorithm = annotation.algorithm();
if (Encrypt.AES.equalsIgnoreCase(algorithm)) {
fieldValue = CipherUtil.aesEncrypt((String) fieldValue);
} else if (Encrypt.MD5.equalsIgnoreCase(algorithm)) {
}
}
Object[] parameters = new Object[] { changeCase(DBUtility.convertToValidColumnName(field.getName())), fieldValue };
Class<?>[] parameterTypes = getParameterTypes(field, fieldValue, parameters);
DynamicExecutor.send(values, "put", parameters, values.getClass(), parameterTypes);
......
package org.litepal.util;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* @author Tony Green
* @since 1.6
*/
public class CipherUtil {
private static final String AES = "AES";
public static String aesKey = "LitePal";
public static String aesEncrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(AES);
kgen.init(128, new SecureRandom(aesKey.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
Cipher cipher = Cipher.getInstance(AES);
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String aesDecrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(AES);
kgen.init(128, new SecureRandom(aesKey.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(parseHexStr2Byte(content));
return new String(result, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (byte b : buf) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册