AES加密SharePreference数据

介绍

封装了SharePreference插入AES加密后的数据的功能,减少了明文存储造成用户信息泄露的风险

使用方式

  • Applicaton初始化
 public class MyApplication extends Application {
    private static Context appContext;

    @Override
    public void onCreate() {
        super.onCreate();
        setAppContext(getApplicationContext());
        //初始化AES工具类,并设置AES密码
        AESUtils.init("ASDFSDokju98kSsdfDF");
        //默认SharePreference使用USERINFO标签数据 切换到其他文件通过 setTag()方法
        SharePreferencesUtils.init("USERINFO");
    }

    public static Context getAppContext() {
        if (appContext == null)
            appContext = getAppContext();
        return appContext;
    }

    public static void setAppContext(Context appContext) {
        MyApplication.appContext = appContext;
    }
}
  • 写入加密数据到SharePreference
SharePreferencesUtils.setTag("USERINFO");
        SharePreferencesUtils.putString("username", "迪丽热巴");
        SharePreferencesUtils.putString("password", "abc123");
        SharePreferencesUtils.putString("phone", "18567345345");
  • 读取SharePreference的加密数据
 SharePreferencesUtils.getString("username");
 SharePreferencesUtils.getString("password");
 SharePreferencesUtils.getString("phone");

两个工具类如下

AESUtils类

package com.hujing.kabao.utils;

import android.support.annotation.NonNull;

import java.io.UnsupportedEncodingException;

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


public class AESUtils {

    private static String aes_key;

    private AESUtils() {
    }

    /**
     * 静态内部类实现单例模式
     */
    private static class AESUtilsHelp {
        private static final AESUtils instance = new AESUtils();
    }

    public static AESUtils init(@NonNull String key) {
        aes_key = key;
        return AESUtilsHelp.instance;
    }

    //    private static final String CipherMode = "AES/ECB/PKCS5Padding";使用ECB加密,不需要设置IV,但是不安全
    private static final String CipherMode = "AES/CFB/NoPadding";//使用CFB加密,需要设置IV

    // /** 创建密钥 **/
    private static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuilder sb = new StringBuilder(32);
        sb.append(password);
        while (sb.length() < 32) {
            sb.append("0");
        }
        if (sb.length() > 32) {
            sb.setLength(32);
        }

        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    // /** 加密字节数据 **/
    private static byte[] encrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            System.out.println(key);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // /** 加密(结果为16进制字符串) **/
    public static String encrypt(String content) {
        String password = aes_key;
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        String result = byte2hex(data);
        return result;
    }

    // /** 解密字节数组 **/
    private static byte[] decrypt(byte[] content, String password) {

        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(
                    new byte[cipher.getBlockSize()]));

            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // /** 解密16进制的字符串为字符串 **/
    public static String decrypt(String content) {
        String password = aes_key;
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null)
            return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    // /** 字节数组转成16进制字符串 **/
    private static String byte2hex(byte[] b) { // 一个字节的数,
        StringBuilder sb = new StringBuilder(b.length * 2);
        String tmp = "";
        for (byte aB : b) {
            // 整数转成十六进制表示
            tmp = (Integer.toHexString(aB & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    // /** 将hex字符串转换成字节数组 **/
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

SharePreferencesUtils类
(只写了String的插入于读取,其他数据类型自行添加)

package com.hujing.kabao.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.util.Log;

import com.hujing.kabao.MyApplication;

public class SharePreferencesUtils {
    private static Context context;
    private static SharedPreferences preferences;
    private static SharedPreferences.Editor editor;

    private SharePreferencesUtils() {
    }

    private static class SharePerferencesUtilsHelp {
        private static final SharePreferencesUtils instance = new SharePreferencesUtils();
    }

    @SuppressLint("CommitPrefEdits")
    public static SharePreferencesUtils init(@NonNull String preferenceName) {
        context = MyApplication.getAppContext();
        preferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
        editor = preferences.edit();
        return SharePerferencesUtilsHelp.instance;
    }

    @SuppressLint("CommitPrefEdits")
    public static void setTag(String tag) {
        preferences = context.getSharedPreferences(tag, Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public static void putString(String key, String value) {
        String aesValue = AESUtils.encrypt(value);
        Log.i("test", "插入的AES数据:" + aesValue);
        editor.putString(key, aesValue);
        editor.commit();
    }

    public static String getString(String key) {
        String aesValue = preferences.getString(key, null);
        if (aesValue == null)
            return null;
        return AESUtils.decrypt(aesValue);
    }
}

水平有限,不足之处,望指正,方能进步。

posted @ 2018-07-16 14:42  木头同学  阅读(171)  评论(0编辑  收藏  举报