【Android安全】自带加密光环的SharedPreference

Android入门第52天-在SharedPreference中使用加密 在上一篇中,我们讲了SharedPreference的使用。但是那不是一个生产场景。特别是我们举了一个例子,存放登录信息的例子。这个例子里用户的密码没有加密,比如说在真实的实际生产环境里用户的一些敏感信息或者说是像:用户四要素按照等保3规范以及“个信”法,都是需要加密和脱敏的。所以当碰到这样的“敏感”信息脱敏需求时,我们不可以直接把一个明文存入SharedPreference。因此我们今天会使用MD5来对SharedPreference中存放的信息进行脱敏处理。 阅读详情

项目地址:https://github.com/afinal/SecuritySharedPreference

前言

安全问题长久以来就是Android系统的一大弊病,很多人也因此舍弃Android选择了苹果,作为一个Android Developer,我们需要对用户的隐私负责,需要对用户的数据安全倾尽全力,想到这里,我就热血沸腾,仿佛自己化身正义的天使(我编不下去了。。。)。

概述

现在,我们回归正题,SharedPreference是我们比较常用的保存数据到本地的方式,我们习惯在SharedPreference中保存用户信息,用户偏好设置,以及记住用户名密码等等。但是,SharedPreference存在一些安全隐患,我们都知道,SharedPreference是以“键值对”的形式把数据保存在data/data/packageName/shared_prefs文件夹中的xml文件中。
在正常的情况下,我们没办法访问data/data目录,我们也没办法拿到xml中的文件。但是,我们root手机之后,通过命令行可以获得读写data/data目录的权限,我们SharedPreference中保存的数据也就很容易泄漏,造成不可挽回的损失。那么我们今天就从SharedPreference开刀,为APP的安全尽一份绵薄之力。

代码

SecuritySharedPreference.java

我们实现了SharedPreference接口和SharedPreference.Editor接口,重写了保存数据和取出数据的方法,我们在保存数据和取出数据的时候加了加解密层,这样可以保证我们在操作自定义的SharedPreference时候像调用原生的一样简单。

package com.domain.securitysharedpreference;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
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
 * Created by Max on 2016/11/23.
 */

public class SecuritySharedPreference implements SharedPreferences {
   
   

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

    /**
     * constructor
     * @param context should be ApplicationContext not activity
     * @param name file name
     * @param mode context mode
     */
    public SecuritySharedPreference(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);
    }

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

    @Nullable
    @Override
    public Set<String> getStringSet(String key, Set<String> defValues) {
        final Set<String> encryptSet = m
Android入门第51天-使用Android的SharedPreference存取信息 上一篇我们介绍了在android里如何读写本地文件。我们有一种场景,类似网页的cookie,要把用户的一些储如上一次登录、使用的痕迹等信息保存下来以便于每次不需要做重复“填表单”的操作,当在这种场景下我们如果也使用本地文件读写的话显然是“太重”了。因此android提供了一种轻量级存储叫SharedPreference专门用来存储这种场景下的数据。 阅读详情

相关推荐

Android-一个比较安全的SharedPreference加密方案

一个比较安全的SharedPreference加密方案

CryptSharedPreference:在SharedPreference util中加密的保存类

CryptSharedPreference 1、介绍 SharedPreferences中封装了一系列使用sp保存数据的方法,特点在于可以直接保存数据类与储存时加密数据。 2、如何依赖 step 1: 在项目根目录下的build.gradle添加 allprojects { repositories { ... maven { url 'https://jitpack.io' } } } step 2: 添加项目依赖 dependencies { implementation 'com.github.YeGuli:CryptSharedPreference:v1.0.0' } 3、如何使用 创建继承自BaseSet的数据类: public class AccountSet extends BaseSet { private String u

EncryptedSharedPreferences:为Android SharedPreferences提供加密

EncyptedSharedPreferences 使用Android Studio 0.8.0的Android库 为SharedPreferences集成系统提供加密。 它使用AES 128位加密技术来保护数据安全,并且与UTF-8兼容元素兼容。 ====================== Gradle集成: 添加存储库依赖项: repositories { jcenter() maven { url "https://github.com/omadahealth/omada-nexus/raw/master/release" } } 将依赖项添加到“ dependencies”中: dependencies { compile 'com.og.encryptedsharedpreferences:encryptedsha

排队论在食堂窗口规划中的应用:M/M/S模型优化案例

本文通过食堂窗口规划的真实案例,详细阐述了如何运用排队论中的M/M/S模型量化服务效率。文章从问题拆解、数据采集、模型计算到成本效益分析,提供了完整的数学建模实战指南,帮助读者掌握利用最优化方法解决资源配置问题的核心流程与工具。

docker7nomad的博客 1084

阿里平头哥与华为芯片的比较

阿里平头哥与华为芯片代表了中国AI芯片领域的两种典型发展路径:平头哥通过兼容CUDA生态快速切入市场,以较低成本提供接近国际水平的AI算力;华为则坚持全栈自研路线,构建从芯片到框架的完整技术体系,更注重供应链安全和自主可控。从短期来看,平头哥PPU在单卡性能参数上全面超越昇腾910B,接近英伟达H20水平,且成本优势明显,有望在云服务和互联网应用领域取得更大市场份额。而华为昇腾则凭借全栈自研和端边云协同优势,在政企市场和科研领域更具竞争力。

shao.bing的专栏 4012

用AI生成React/Vue页面?实测Locofy等5款工具,教你选最适合的

本文深度评测了2024年五大AI生成前端页面工具,包括Locofy、Builder.io等,从代码质量、可视化编辑器成本到企业级落地方案进行全面分析。通过实测数据和实战案例,揭示如何利用AI生成技术高效创建React/Vue页面,提升开发效率并优化性能。

m5n6o7的博客 606

【SABRE 3D, SABRE 3DxT,LAM设备】2025年9月10日

前文:SABRE 3D系列机台简介本章节详细阐述了在维护期间锁定电气、机械、热力学及重力组件以及化学管线输入的锁定操作流程,旨在降低人员受伤风险。p42~p55。

weixin_46735260的博客 1615

Windows Server+SqlServer Always On实战:5步搞定高可用集群搭建

本文详细介绍了在Windows Server环境中,通过5个关键步骤搭建SQL Server Always On高可用集群的实战指南。内容涵盖从底层故障转移集群配置、SQL Server实例启用Always On功能,到创建可用性组和侦听器的完整流程,并提供了核心运维与故障排查思路,帮助企业构建稳定可靠的数据库高可用架构。

milk5的博客 859

从 OA 门户到 SAP 的单点登录全景解析

OA(Office Automation)门户往往已与企业身份证明源(Microsoft Entra ID、LDAP 等)集成。管理员希望:员工在 OA 登陆后访问 SAP Fiori Launchpad、OData API 或 RFC 接口时无需再次输入账号密码,而 SAP 仍能识别用户身份并执行基于角色的授权。此时 OA 可以直接充当 IdP,也可以把企业 IdP 发放的令牌转发给 SAP 充当 SP(service provider)。SAP Help Portal 将这类跨系统认证称为 single

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 999

QT6实现USB摄像头接入显示与抓拍功能实现

QT实现USB摄像头接入显示 一、UVC协议简介 UVC全称是USB Video Class(USB视频类),是一种标准化的USB视频设备通信协议,它定义了摄像头与主机之间的数据传输协议和格式。 UVC协议的出现,解决了摄像头厂商之间互不兼容,以及摄像头应用开发与平台之间的散乱问题。 UVC标准是由USB-IF主导制定的,目前最新的版本是UVC 1.5,UVC的缺省设置类容易实现,不需要额外的驱动程序。

热土程序园,利他愉己~ 3417

uni-app - 解决 H5 微信公众号授权登录后,无法回退到 “上一页“ 的问题(微信登录后如何返回到触发它的那一页?无法通过 uni.navigateBack() 返回到前一页的问题?)详细教程

uniappH5微信登录重定向后无法返回到原来进入前的页面了,uni-appH5微信浏览器中授权微信登录后,无法正常回退问题,uniappH5微信登录后怎么返回上一页,uniapp公众号登陆后使用uni.navigateBack()回不去上一页,uniapp微信登录成功后返回页面后一直自动刷新页面,uniapph5授权成功后如何返回上一页,uniappH5微信登录后怎么返回到触发它的那一页去,公众号h5在授权后如何跳转回到刚进入时的页面,微信公众号H5网页返回上一页疑问,解决微信H5静默授

🏆 前端领域优质创作者 7715

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: OkHttp报错javax.net.ssl.SSLHandshakeException: Handshake failed
下一篇: Android原生项目集成React Native
随便想个名字
博客等级 码龄14年 28粉丝 21原创
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值