/*
* Copyright (C) 2014 Jason Fang ( ijasonfang@gmail.com )
*
* 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 fyc.framework.util; import java.util.HashSet;
import java.util.Map;
import java.util.Set; import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils; /**
* SharePreferences Tool
*
* @author Jason Fang
* @datetime 2014年12月5日 下午5:28:22
*/
public class PrefsUtils {
static final boolean DEBUG = true; private static final String SECURITY_KEY = "iJasonfang"; /**
* Put Value
*
* @param context
* @param key
* @param value
* @return
*/
public static boolean putValue(Context context, String key, Object value) {
return putValue(context, null, key, value);
} public static boolean putValue(Context context, String key, Object value, boolean[] keyValueEncrypt) {
return putValue(context, null, key, value, keyValueEncrypt);
} public static boolean putValue(Context context, String name, String key, Object value) {
return putValue(context, name, key, value, new boolean[]{true, true});
} public static boolean putValue(Context context, String name, String key, Object value, boolean[] keyValueEncrypt) {
return putValue(context, name, key, value, Context.MODE_PRIVATE, keyValueEncrypt);
} public static boolean putValue(Context context, String name, String key, Object value, int mode, boolean[] keyValueEncrypt) {
ArrayMap<String, Object> map = new ArrayMap<String, Object>();
map.put(key, value);
return putValue(context, name, map, keyValueEncrypt);
} public static boolean putValue(Context context, String name, Map<String, Object> map, boolean[] keyValueEncrypt) {
return putValue(context, name, map, Context.MODE_PRIVATE, keyValueEncrypt);
} @TargetApi(11)
@SuppressWarnings("unchecked")
public static boolean putValue(Context context, String name, Map<String, Object> map, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} Editor editor = preferences.edit();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = keyValueEncrypt[0] ? SecurityUtils.MD5(entry.getKey()) : entry.getKey();
Object value = entry.getValue(); if (keyValueEncrypt[1] && !(value instanceof Set)) {
editor.putString(key, SecurityUtils.DESencrypt(String.valueOf(value), SECURITY_KEY));
} else {
if (value instanceof Boolean) {
editor.putBoolean(key, Boolean.parseBoolean(String.valueOf(value)));
} else if (value instanceof Float) {
editor.putFloat(key, Float.parseFloat(String.valueOf(value)));
} else if (value instanceof Integer) {
editor.putInt(key, Integer.parseInt(String.valueOf(value)));
} else if (value instanceof Long) {
editor.putLong(key, Long.parseLong(String.valueOf(value)));
} else if (value instanceof String) {
editor.putString(key, String.valueOf(value));
} else if (value instanceof Set) {
if (keyValueEncrypt[1]) {
Set<String> sets = (Set<String>)value;
Set<String> tempSets = new HashSet<String>();
for (String s : sets) {
tempSets.add(SecurityUtils.DESencrypt(String.valueOf(s), SECURITY_KEY));
}
editor.putStringSet(key, tempSets);
} else {
editor.putStringSet(key, (Set<String>)value);
}
} else {
throw new IllegalArgumentException("Value type is not support!");
}
}
}
return editor.commit();
} /**
* Remove Key
* @param context
* @param key
*/
public static boolean removeKey(Context context, String key) {
return removeKey(context, null, key);
} public static boolean removeKey(Context context, String name, String key) {
return removeKey(context, name, key, false);
} public static boolean removeKey(Context context, String name, String key, boolean isKeyEncrypt) {
return removeKey(context, name, key, Context.MODE_PRIVATE, isKeyEncrypt);
} public static boolean removeKey(Context context, String name, String key, int mode, boolean isKeyEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} Editor editor = preferences.edit();
editor.remove(isKeyEncrypt ? SecurityUtils.DESencrypt(key, SECURITY_KEY) : key);
return editor.commit();
} /**
* Get String
*
* @param context
* @param key
* @param defValue
* @return
*/
public static String getString(Context context, String key, String defValue) {
return getString(context, null, key, defValue);
} public static String getString(Context context, String name, String key, String defValue) {
return getString(context, name, key, defValue, Context.MODE_PRIVATE, new boolean[]{true, true});
} public static String getString(Context context, String name, String key, String defValue, boolean[] keyValueEncrypt) {
return getString(context, name, key, defValue, Context.MODE_PRIVATE, keyValueEncrypt);
} public static String getString(Context context, String name, String key, String defValue, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} String value = preferences.getString(keyValueEncrypt[0] ? SecurityUtils.MD5(key) : key, defValue);
if (value.equals(defValue)) {
return value;
} else {
return keyValueEncrypt[1] ? SecurityUtils.DESdecrypt(value, SECURITY_KEY) : value;
}
} /**
* Get Int
*
* @param context
* @param key
* @param defValue
* @return
*/
public static int getInt(Context context, String key, int defValue) {
return getInt(context, null, key, defValue);
} public static int getInt(Context context, String name, String key, int defValue) {
return getInt(context, name, key, defValue, new boolean[]{true, true});
} public static int getInt(Context context, String name, String key, int defValue, boolean[] keyValueEncrypt) {
return getInt(context, name, key, defValue, Context.MODE_PRIVATE, keyValueEncrypt);
} public static int getInt(Context context, String name, String key, int defValue, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} if (keyValueEncrypt[1]) {
String value = getString(context, name, key, String.valueOf(defValue), mode, keyValueEncrypt);
try {
return Integer.valueOf(value);
} catch (Exception e) {
return defValue;
}
} else {
return preferences.getInt(keyValueEncrypt[0] ? SecurityUtils.MD5(key) : key, defValue);
}
} /**
* Get Long
*
* @param context
* @param key
* @param defValue
* @return
*/
public static long getLong(Context context, String key, long defValue) {
return getLong(context, null, key, defValue);
} public static long getLong(Context context, String name, String key, long defValue) {
return getLong(context, name, key, defValue, new boolean[]{true, true});
} public static long getLong(Context context, String name, String key, long defValue, boolean[] keyValueEncrypt) {
return getLong(context, name, key, defValue, Context.MODE_PRIVATE, keyValueEncrypt);
} public static long getLong(Context context, String name, String key, long defValue, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} if (keyValueEncrypt[1]) {
String value = getString(context, name, key, String.valueOf(defValue), mode, keyValueEncrypt); try {
return Long.valueOf(value);
} catch (Exception e) {
return defValue;
}
} else {
return preferences.getLong(keyValueEncrypt[0] ? SecurityUtils.MD5(key) : key, defValue);
}
} /**
* Get Float
*
* @param context
* @param key
* @param defValue
* @return
*/
public static float getFloat(Context context, String key, float defValue) {
return getFloat(context, null, key, defValue);
} public static float getFloat(Context context, String name, String key, float defValue) {
return getFloat(context, name, key, defValue, new boolean[]{true, true});
} public static float getFloat(Context context, String name, String key, float defValue, boolean[] keyValueEncrypt) {
return getFloat(context, name, key, defValue, Context.MODE_PRIVATE, keyValueEncrypt);
} public static float getFloat(Context context, String name, String key, float defValue, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} if (keyValueEncrypt[1]) {
String value = getString(context, name, key, String.valueOf(defValue), mode, keyValueEncrypt);
try {
return Float.valueOf(value);
} catch (Exception e) {
return defValue;
}
} else {
return preferences.getFloat(keyValueEncrypt[0] ? SecurityUtils.MD5(key) : key, defValue);
} } /**
* boolean
*
* @param context
* @param key
* @param defValue
* @return
*/
public static boolean getBoolean(Context context, String key, boolean defValue) {
return getBoolean(context, null, key, defValue);
} public static boolean getBoolean(Context context, String name, String key, boolean defValue) {
return getBoolean(context, name, key, defValue, new boolean[]{true, true});
} public static boolean getBoolean(Context context, String name, String key, boolean defValue, boolean[] keyValueEncrypt) {
return getBoolean(context, name, key, defValue, Context.MODE_PRIVATE, keyValueEncrypt);
} public static boolean getBoolean(Context context, String name, String key, boolean defValue, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
} if (keyValueEncrypt[1]) {
String valueString = getString(context, name, key, String.valueOf(defValue), mode, keyValueEncrypt);
try {
return Boolean.valueOf(valueString);
} catch (Exception e) {
return defValue;
}
} else {
return preferences.getBoolean(keyValueEncrypt[0] ? SecurityUtils.MD5(key) : key, defValue);
}
} /**
* StringSet
*
* @param context
* @param key
* @param defValues
* @return
*/
public static Set<String> getStringSet(Context context, String key, Set<String> defValues) {
return getStringSet(context, null, key, defValues);
} public static Set<String> getStringSet(Context context, String name, String key, Set<String> defValues) {
return getStringSet(context, name, key, defValues, new boolean[]{true, true});
} public static Set<String> getStringSet(Context context, String name, String key, Set<String> defValues, boolean[] keyValueEncrypt) {
return getStringSet(context, name, key, defValues, Context.MODE_PRIVATE, keyValueEncrypt);
} /**
* @param context
* @param name
* @param key
* @param defValues
* @param mode
* @return
*/
@TargetApi(11)
public static Set<String> getStringSet(Context context, String name, String key, Set<String> defValues, int mode, boolean[] keyValueEncrypt) {
SharedPreferences preferences = null;
if (TextUtils.isEmpty(name)) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
} else {
preferences = context.getSharedPreferences(name, mode);
}
Set<String> valueSet = preferences.getStringSet(keyValueEncrypt[0] ? SecurityUtils.MD5(key) : key, defValues);
Set<String> tempValueSet = new HashSet<String>();
for (String s : valueSet) {
tempValueSet.add(SecurityUtils.DESdecrypt(s, SECURITY_KEY));
}
return tempValueSet;
} private PrefsUtils(){/*Do not new me*/};
}

加密工具类!

/*
* Copyright (C) 2014 Jason Fang ( ijasonfang@gmail.com )
*
* 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 fyc.framework.util; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec; import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Base64; /**
* 加密工具类
* @description
* @author Jason Fang
* @created 2013年10月31日
*/
public class SecurityUtils {
static final boolean DEBUG = true; /**
* MD5
* @param srcString
* @return
*/
public static String MD5(String srcString) {
if (TextUtils.isEmpty(srcString)) {
throw new IllegalArgumentException("srcString cannot be null!");
} try {
return MD5(srcString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
return "";
}
} public static String MD5(byte[] srcBytes) {
if (srcBytes == null) {
throw new IllegalArgumentException("bytes cannot be null!");
} try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(srcBytes);
byte[] bytes = md.digest();
int i = 0;
StringBuffer buffer = new StringBuffer("");
for (int offset = 0; offset < bytes.length; offset++) {
i = bytes[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buffer.append("0");
}
buffer.append(Integer.toHexString(i));
}
return buffer.toString();
} catch (Exception e) {
if (DEBUG) Flog.e(e);
}
return "";
}
/**
* @param dataSource
* @param password
* @return
*/
public static String DESencrypt(String dataSource, String password) {
return ConvertUtils.parseBytesToHexString(DESencrypt(dataSource.getBytes(), password));
} /**
* @param data
* @param password
* @return
*/
public static String DESdecrypt(String data, String password) {
byte[] bytes = DESdecrypt(ConvertUtils.parseHexStringToBytes(data), password);
if (bytes == null) {
return "";
}
return new String(bytes);
}
private SecurityUtils() {/*Do not new me*/};
}

ConvertUtils

/*
* Copyright (C) 2014 Jason Fang ( ijasonfang@gmail.com )
*
* 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 fyc.framework.util; import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Map;
import java.util.Set; import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.TypedValue; /**
* 转换工具集
* @author Jason Fang
* @datetime 2014年11月23日 上午11:22:25
*/
public class ConvertUtils {
static final boolean DEBUG = false;
/**
* byte[] to String
* @param bytes
* @return
*/
public static String parseBytesToHexString(byte[] bytes) {
if (bytes == null) return "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String x16 = Integer.toHexString(bytes[i]);
if (x16.length() < 2) {
sb.append("0" + x16);
} else if (x16.length() > 2) {
sb.append(x16.substring(x16.length() - 2));
} else {
sb.append(x16);
}
}
return sb.toString();
} /**
* String to byte[]
* @param intString
* @return
*/
public static byte[] parseHexStringToBytes(String intString) {
if (TextUtils.isEmpty(intString)) return null; if (intString.length() % 2 == 1) {
intString = "0" + intString;
}
byte[] bytes = new byte[intString.length() / 2]; try {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte)Integer.parseInt(intString.substring(i * 2, i * 2 + 2), 16);
} if (DEBUG) Flog.i("===parseStringToBytes===" + bytes.toString()); return bytes;
} catch (Exception e) {
Flog.e(e);
return null;
}
}
}

写了个SharedPreferences的工具类(带加密)的更多相关文章

  1. Android 分享一个SharedPreferences的工具类,方便保存数据

    我们平常保存一些数据,都会用到SharedPreferences,他是保存在手机里面的,具体路径是data/data/你的包名/shared_prefs/保存的文件名.xml, SharedPrefe ...

  2. SharedPreferences的工具类,使用起来方便、快捷

    SharedPreferences的工具类,使用起来方便.快捷:上代码:import android.content.Context;import android.content.SharedPref ...

  3. SharedPreferences的工具类

    import android.content.Context; import android.content.SharedPreferences; import android.content.Sha ...

  4. 自己写的java excel导出工具类

    最近项目要用到excel导出功能,之前也写过类似的代码.因为这次项目中多次用到excel导出.这次长了记性整理了一下 分享给大伙 欢迎一起讨论 生成excel的主工具类: public class E ...

  5. 自己用反射写的一个request.getParameter工具类

    适用范围:当我们在jsp页面需要接收很多值的时候,如果用request.getParameter(属性名)一个一个写的话那就太麻烦了,于是我想是 否能用反射写个工具类来简化这样的代码,经过1个小时的代 ...

  6. java 写一个JSON解析的工具类

    上面是一个标准的json的响应内容截图,第一个红圈”per_page”是一个json对象,我们可以根据”per_page”来找到对应值是3,而第二个红圈“data”是一个JSON数组,而不是对象,不能 ...

  7. 调用jdbc已经写成的方法----jdbc工具类抽取方式三

    package jdbc_demo3; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.R ...

  8. 调用jdbc已经写成的方法----jdbc工具类抽取方式二

    先创建db.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/web08?useUnicode=true& ...

  9. 调用jdbc已经写成的方法----jdbc工具类抽取方式一

    package web09; /*获取连接和释放资源的方法 */ import java.sql.Connection; import java.sql.DriverManager; import j ...

随机推荐

  1. IOS SQLITE 数据库操作

    NSArray * array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); N ...

  2. 10款jquery图片广告特效的预览及源码下载 改自[帅的相对论]

    原文格式有问题,我来排版了一下,分享给大家. 1.jQuery仿海尔官网全屏焦点图特效代码 Query仿海尔官网全屏焦点图特效代码,带有左右箭头的jQuery焦点图切换特效.当焦点图切换时,下方的三块 ...

  3. cxf 动态创建客户端,局域网能正常调用服务端,外网不能访问

  4. POJ-1002 解题报告

      1.题目描述 http://poj.org/problem?id=1002 2.解题过程 按部就班来解题的话,这个题目很容易写出来,这是我的第一个版本的代码,思路是读入一行电话字符串,均转化为整型 ...

  5. Ubuntu 12.04 中安装ubuntu-tweak出错

    错误信息: ubuntu-tweakE: Sub-process /usr/bin/dpkg returned an error code (1) 解决办法: 第一步:删除 /usr/share/py ...

  6. AHOI2013 Round2 Day1 简要题解

    第一题,好吧这是个dp.(搜素也能在BZOJ上卡过). 第二题,BFS搜索碰到的立方体面数,智硬没有想到... 第三题,其实一看就有思路,但关键是求x坐标不交的矩形对数+y坐标不交的矩形对数 - x, ...

  7. 优秀java开源项目与解决方案推荐与概论

    http://www.oschina.net/project/lang/19/java http://www.open-open.com/ http://java-source.net/ https: ...

  8. JEE , EJB概念深入概括

    说起EJB,不得不提JEE,java EE 英文全称为:java Enterprise Edition企业级应用的软件架构,是一种思想,也是一种规范,方便从事这方面的开发者以及开发厂商进行规范性的开发 ...

  9. homework-07

    终于等到了一次难度相对比较小的问题,只要读完提问题就好,但又不得不说自己真的很菜,且不说C++掌握的不好,连英文也比较差,导致读的非常吃力,不过我还是坚持读完了四篇英文文章,大致意思是可以了解的,但是 ...

  10. homework09-虐心的现程设终于要告一段落了

    V3.0版本今天凌晨出炉 添加了随机生成 添加了文件打开 完全按照老师的要求搞定了 V2.0版本更新 添加了中间数组变量显示 这次作业写了整整一天,把以前能用的代码都改了一个遍 最后变成了网页版的小程 ...