Android SharePreferences 进行数据进行加密

                


package com.net.security.shareprefs.securitysp;

EncryptUtil

package com.net.security.shareprefs.securitysp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.net.security.shareprefs.BuildConfig;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**AES加密解密工具*/
public class EncryptUtil {
    BuildConfig s;
    private String key;
    private static EncryptUtil instance;
    private static final String TAG = EncryptUtil.class.getSimpleName();

    private EncryptUtil(Context context){
        String serialNo = getDeviceSerialNumber(context);
        //加密随机字符串生成AES key
        key = SHA(serialNo + "#$ERDTS$D%F^Gojikbh").substring(0, 16);
        Log.e(TAG,TAG+"___key = "+ key);
    }

    /**
     * 单例模式
     * @param context context
     * @return
     */
    public static EncryptUtil getInstance(Context context){
        if (instance == null){
            synchronized (EncryptUtil.class){
                if (instance == null){
                    instance = new EncryptUtil(context);
                }
            }
        }

        return instance;
    }

    /**
     * Gets the hardware serial number of this device.
     *
     * @return serial number or Settings.Secure.ANDROID_ID if not available.
     */
    @SuppressLint("HardwareIds")
    private String getDeviceSerialNumber(Context context) {
        // We're using the Reflection API because Build.SERIAL is only available
        // since API Level 9 (Gingerbread, Android 2.3).
        try {
            String deviceSerial = (String) Build.class.getField("SERIAL").get(null);
            if (TextUtils.isEmpty(deviceSerial)) {
                return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            } else {
                return deviceSerial;
            }
        } catch (Exception ignored) {
            // Fall back  to Android_ID
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
    }


    /**
     * SHA加密
     * @param strText 明文
     * @return
     */
    private String SHA( String strText){
        // 返回值
        String strResult = null;
        // 是否是有效字符串
        if (strText != null && strText.length() > 0){
            try{
                // SHA 加密开始
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes());
                byte byteBuffer[] = messageDigest.digest();
                StringBuffer strHexString = new StringBuffer();
                for (int i = 0; i < byteBuffer.length; i++){
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1){
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        return strResult;
    }

    /**
     * AES128加密
     * @param plainText 明文
     * @return
     */
    public String encrypt(String plainText) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keyspec);
            byte[] encrypted = cipher.doFinal(plainText.getBytes());
            return Base64.encodeToString(encrypted, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * AES128解密
     * @param cipherText 密文
     * @return
     */
    public String decrypt(String cipherText) {
        try {
            byte[] encrypted1 = Base64.decode(cipherText, Base64.NO_WRAP);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keyspec);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

SharedPreferences

package com.net.security.shareprefs.securitysp;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 自动加密SharedPreference
 */
public class SharedPreferences implements android.content.SharedPreferences {

    private android.content.SharedPreferences mSharedPreferences;
    private static final String TAG = SharedPreferences.class.getName();
    private Context mContext;

    public static SharedPreferences get(Context context, String name, int mode){
        return new SharedPreferences( context, name,  mode);
    }
    public static SharedPreferences get(Context context, String name){
        return  get(context,name,Context.MODE_PRIVATE);
    }
    public static SharedPreferences get(Context context){
        return  get(context,null,Context.MODE_PRIVATE);
    }

    /**
     * constructor
     * @param context should be ApplicationContext not activity
     * @param name file name
     * @param mode context mode
     */
    public SharedPreferences(Context context, String name, int mode){
        mContext = context;
        if (TextUtils.isEmpty(name)){
            mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        } else {
            mSharedPreferences =  context.getSharedPreferences(name, mode);
        }
    }

    @Override
    public Map<String, String> getAll() {
        final Map<String, ?> encryptMap = mSharedPreferences.getAll();
        final Map<String, String> decryptMap = new HashMap<>();
        for (Map.Entry<String, ?> entry : encryptMap.entrySet()){
            Object cipherText = entry.getValue();
            if (cipherText != null){
                decryptMap.put(entry.getKey(), entry.getValue().toString());
            }
        }
        return decryptMap;
    }

    /**
     * encrypt function
     * @return cipherText base64
     */
    private String encryptPreference(String plainText){
        return EncryptUtil.getInstance(mContext).encrypt(plainText);
    }

    /**
     * decrypt function
     * @return plainText
     */
    private String decryptPreference(String cipherText){
        return EncryptUtil.getInstance(mContext).decrypt(cipherText);
    }

    @Override
    public String getString(String key, String defValue) {
        final String encryptValue = mSharedPreferences.getString(encryptPreference(key), null);
        return encryptValue == null ? defValue : decryptPreference(encryptValue);
    }

    @Override
    public Set<String> getStringSet(String key, Set<String> defValues) {
        final Set<String> encryptSet = mSharedPreferences.getStringSet(encryptPreference(key), null);
        if (encryptSet == null){
            return defValues;
        }
        final Set<String> decryptSet = new HashSet<>();
        for (String encryptValue : encryptSet){
            decryptSet.add(decryptPreference(encryptValue));
        }
        return decryptSet;
    }

    @Override
    public int getInt(String key, int defValue) {
        final String encryptValue = mSharedPreferences.getString(encryptPreference(key), null);
        if (encryptValue == null) {
            return defValue;
        }
        return Integer.parseInt(decryptPreference(encryptValue));
    }

    @Override
    public long getLong(String key, long defValue) {
        final String encryptValue = mSharedPreferences.getString(encryptPreference(key), null);
        if (encryptValue == null) {
            return defValue;
        }
        return Long.parseLong(decryptPreference(encryptValue));
    }

    @Override
    public float getFloat(String key, float defValue) {
        final String encryptValue = mSharedPreferences.getString(encryptPreference(key), null);
        if (encryptValue == null) {
            return defValue;
        }
        return Float.parseFloat(decryptPreference(encryptValue));
    }

    @Override
    public boolean getBoolean(String key, boolean defValue) {
        final String encryptValue = mSharedPreferences.getString(encryptPreference(key), null);
        if (encryptValue == null) {
            return defValue;
        }
        return Boolean.parseBoolean(decryptPreference(encryptValue));
    }

    @Override
    public boolean contains(String key) {
        return mSharedPreferences.contains(encryptPreference(key));
    }

    @Override
    public Editor edit() {
        return new Editor();
    }

    @Override
    public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        mSharedPreferences.registerOnSharedPreferenceChangeListener(listener);
    }

    @Override
    public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener);
    }

    /**
     * 处理加密过渡
     */
    public void handleTransition(){
        Map<String, ?> oldMap = mSharedPreferences.getAll();
        Map<String, String> newMap = new HashMap<>();
        for (Map.Entry<String, ?> entry : oldMap.entrySet()){
            Log.i(TAG, "key:"+entry.getKey()+", value:"+ entry.getValue());
            newMap.put(encryptPreference(entry.getKey()), encryptPreference(entry.getValue().toString()));
        }
        android.content.SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.clear().commit();
        for (Map.Entry<String, String> entry : newMap.entrySet()){
            editor.putString(entry.getKey(), entry.getValue());
        }
        editor.commit();
    }

    /**
     * 自动加密Editor
     */
    public final class Editor implements android.content.SharedPreferences.Editor {

        private android.content.SharedPreferences.Editor mEditor;

        /**
         * constructor
         */
        private Editor(){
            mEditor = mSharedPreferences.edit();
        }

        @Override
        public android.content.SharedPreferences.Editor putString(String key, String value) {
            mEditor.putString(encryptPreference(key), encryptPreference(value));
            return this;
        }

        @Override
        public android.content.SharedPreferences.Editor putStringSet(String key, Set<String> values) {
            final Set<String> encryptSet = new HashSet<>();
            for (String value : values){
                encryptSet.add(encryptPreference(value));
            }
            mEditor.putStringSet(encryptPreference(key), encryptSet);
            return this;
        }

        @Override
        public android.content.SharedPreferences.Editor putInt(String key, int value) {
            mEditor.putString(encryptPreference(key), encryptPreference(Integer.toString(value)));
            return this;
        }

        @Override
        public android.content.SharedPreferences.Editor putLong(String key, long value) {
            mEditor.putString(encryptPreference(key), encryptPreference(Long.toString(value)));
            return this;
        }

        @Override
        public android.content.SharedPreferences.Editor putFloat(String key, float value) {
            mEditor.putString(encryptPreference(key), encryptPreference(Float.toString(value)));
            return this;
        }

        @Override
        public android.content.SharedPreferences.Editor putBoolean(String key, boolean value) {
            mEditor.putString(encryptPreference(key), encryptPreference(Boolean.toString(value)));
            return this;
        }

        @Override
        public android.content.SharedPreferences.Editor remove(String key) {
            mEditor.remove(encryptPreference(key));
            return this;
        }

        /**
         * Mark in the editor to remove all values from the preferences.
         * @return this
         */
        @Override
        public android.content.SharedPreferences.Editor clear() {
            mEditor.clear();
            return this;
        }

        /**
         * 提交数据到本地
         * @return Boolean 判断是否提交成功
         */
        @Override
        public boolean commit() {

            return mEditor.commit();
        }

        /**
         * Unlike commit(), which writes its preferences out to persistent storage synchronously,
         * apply() commits its changes to the in-memory SharedPreferences immediately but starts
         * an asynchronous commit to disk and you won't be notified of any failures.
         */
        @Override
        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        public void apply() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                mEditor.apply();
            } else {
                commit();
            }
        }
    }
}

SharedPrefsUtils

package com.net.security.shareprefs.securitysp;

import android.content.Context;

import java.util.Set;

/**
 * 作者:dongixang
 * 时间:2017/10/31 10:59
 * 功能:加密存贮功能;
 * 使用:
 */
public class SharedPrefsUtils {
    private static SharedPrefsUtils instances;
    private SharedPreferences ssp;
    public static SharedPrefsUtils get(Context context, String spName, int mode){
        instances=new SharedPrefsUtils(context, spName,mode);
        return instances;
    }
    public static SharedPrefsUtils get(Context context, String spName) {
        instances=get(context, spName,Context.MODE_PRIVATE);
        return instances;
    }
    public static SharedPrefsUtils get(Context context) {
        instances=get(context, null,Context.MODE_PRIVATE);
        return instances;
    }
    public SharedPrefsUtils(Context context, String spName, int mode) {
        this.ssp = SharedPreferences.get(context, spName,mode);
    }
//========================= String
    public boolean putString(String key, String value) {
        if (value == null) {
            value = "";
        }
        SharedPreferences.Editor editor = ssp.edit();
        editor.putString(key, value);
        return editor.commit();
    }
    public String getString(String key, String defaultValue) {
        return ssp.getString(key, defaultValue);
    }

//========================= long
    public boolean putLong(String key, long value) {
        SharedPreferences.Editor editor = ssp.edit();
        editor.putLong(key, value);
        return editor.commit();
    }
    public long getLong(String key,long defaultvalue) {
        return ssp.getLong(key, defaultvalue);
    }
//========================= int
    public boolean putInt(String key, int value) {
    SharedPreferences.Editor editor = ssp.edit();
    editor.putInt(key, value);
    return editor.commit();
}
    public long getInt(String key,int defaultvalue) {
        return ssp.getInt(key, defaultvalue);
    }
//========================= boolean
    public boolean putBoolean(String key, boolean value) {
    SharedPreferences.Editor editor = ssp.edit();
    editor.putBoolean(key, value);
    return editor.commit();
}
    public boolean getBoolean(String key, boolean defaultvalue) {
        return ssp.getBoolean(key, defaultvalue);
    }
//========================= Float
    public boolean putFloat(String key, float value) {
    SharedPreferences.Editor editor = ssp.edit();
    editor.putFloat(key, value);
    return editor.commit();
}
    public float getFloat(String key, float defaultvalue) {
        return ssp.getFloat(key, defaultvalue);
    }
//========================= StringSet
    public boolean putStringSet(String key, Set<String> value) {
    SharedPreferences.Editor editor = ssp.edit();
    editor.putStringSet(key, value);
    return editor.commit();
}
    public Set<String> getStringSet(String key, Set<String> defaultvalue) {
        return ssp.getStringSet(key, defaultvalue);
    }

}    

package com.net.security.shareprefs.normalsp;

SharePrefsUtils

package com.net.security.shareprefs.normalsp;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import java.util.Set;

/**
 * 作者:dongixang
 * 时间:2017/10/31 13:51
 * 功能:不加密的Sharepreferences 进行数据保存
 * 使用:
 */

public class SharePrefsUtils {
    private static SharePrefsUtils instances;
    private SharedPreferences sp;
    public static SharePrefsUtils get(Context context, String spName, int mode){
        instances=new SharePrefsUtils(context, spName,mode);
        return instances;
    }
    public static SharePrefsUtils get(Context context, String spName) {
        instances=get(context, spName,Context.MODE_PRIVATE);
        return instances;
    }
    public static SharePrefsUtils get(Context context) {
        instances=get(context, null,Context.MODE_PRIVATE);
        return instances;
    }
    public SharePrefsUtils(Context context, String spName, int mode) {
        if (TextUtils.isEmpty(spName)){
            this.sp= PreferenceManager.getDefaultSharedPreferences(context);
        }else {
            this.sp=context.getSharedPreferences(spName,mode);
        }
    }
    //========================= String
    public boolean putString(String key, String value) {
        if (value == null) {
            value = "";
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        return editor.commit();
    }
    public String getString(String key, String defaultValue) {
        return sp.getString(key, defaultValue);
    }

    //========================= long
    public boolean putLong(String key, long value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(key, value);
        return editor.commit();
    }
    public long getLong(String key,long defaultvalue) {
        return sp.getLong(key, defaultvalue);
    }
    //========================= int
    public boolean putInt(String key, int value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(key, value);
        return editor.commit();
    }
    public long getInt(String key,int defaultvalue) {
        return sp.getInt(key, defaultvalue);
    }
    //========================= boolean
    public boolean putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }
    public boolean getBoolean(String key, boolean defaultvalue) {
        return sp.getBoolean(key, defaultvalue);
    }
    //========================= Float
    public boolean putFloat(String key, float value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat(key, value);
        return editor.commit();
    }
    public float getFloat(String key, float defaultvalue) {
        return sp.getFloat(key, defaultvalue);
    }
    //========================= StringSet
    public boolean putStringSet(String key, Set<String> value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putStringSet(key, value);
        return editor.commit();
    }
    public Set<String> getStringSet(String key, Set<String> defaultvalue) {
        return sp.getStringSet(key, defaultvalue);
    }
}



下载  数据包下载




相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页