Android之登录时密码的保护

时间:2023-01-07 23:31:22

在很多的Android项目中都需要用户登录、注册。这样的话在开发中做好保护用户密码的工作就显得尤为重要。这里我把自己的密码保护方法记录下来。

这是我建了一个保存密码的文件,以便于检查自己保存密码或者上传到服务器的时候密码是否已经被保护了。这就是当我输入用户名和密码之后点击记住密码之后

保存在SD卡上的文件,打开之后可以明显的看到密码已经被保护了。

Android之登录时密码的保护

下面是我的布局文件以及主程序的代码:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E6E6E6"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_head"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:src="@drawable/ic_launcher"/>
<LinearLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/iv_head"
android:layout_margin="10dp"
android:background="#FFFFFF"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/rl_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="账号"/>
<EditText
android:id="@+id/et_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/tv_name"
android:background="@null"/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#E6E6E6"/>
<RelativeLayout
android:id="@+id/rl_userpsd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:id="@+id/tv_psw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="密码"/>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/tv_psw"
android:inputType="textPassword"
android:background="@null"/>
</RelativeLayout> </LinearLayout>
<Button
android:id="@+id/login"
android:onClick="login"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="@+id/layout"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:background="#3C8DC4"
android:text="登录"
android:textColor="#FFFFFF"/>
<Button
android:id="@+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册"
android:background="#E6E6E6"
android:textColor="#000000"
android:layout_marginTop="21dp"
android:layout_centerHorizontal="true"
android:layout_marginRight="10dp"
android:layout_below="@+id/login"
android:layout_alignParentRight="true"/> <CheckBox
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/signUp"
android:layout_alignBottom="@+id/signUp"
android:layout_alignLeft="@+id/login"
android:layout_marginLeft="14dp"
android:text="记住密码" /> </RelativeLayout>
 package com.itcast.test03;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener {
private EditText et_username;
private EditText et_userPsd;
private Button login;
private Button signUp;
private CheckBox save;
private String user,pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText)findViewById(R.id.et_number);
et_userPsd = (EditText)findViewById(R.id.et_password);
login=(Button)findViewById(R.id.login);
signUp=(Button)findViewById(R.id.signUp);
save = (CheckBox)findViewById(R.id.save);
save.setOnClickListener(new CheckBox.OnClickListener(){
public void onClick(View v) {
SharedPreferences pre = getSharedPreferences("loginvalue",
MODE_WORLD_WRITEABLE);
pass = MD5( et_userPsd.getText().toString());
user = et_username.getText().toString();
if (!pass.equals("") && !user.equals("")) {
pre.edit().putString("username",
et_username.getText().toString())
.putString("password", encryptmd5(pass)).commit();
Toast.makeText(getApplicationContext(),"保存成功!",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(),"密码不能为空!",
Toast.LENGTH_LONG).show();
}
}
});
login.setOnClickListener(new Button.OnClickListener() { @Override
public void onClick(View v) { SharedPreferences sp = getSharedPreferences("loginvalue",MODE_WORLD_READABLE);
String loginuser = sp.getString("username",null);
String loginpass = sp.getString("password",null); user = et_username.getText().toString();
pass = et_userPsd.getText().toString(); String passmd5 = MD5(pass);
String encryptmd5 = encryptmd5(passmd5); System.out.println("username="+ loginuser
+ "-------------password="+ loginpass);
System.out.println("user=="+ user
+ "-------------encryptmd5=="+ encryptmd5);
if (!user.equals("") && !pass.equals("")) {
if (user.equals(loginuser) && encryptmd5.equals(loginpass)) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, StudentMainActivity.class);
MainActivity.this.startActivity(intent);
finish();
} else{
Toast.makeText(getApplicationContext(),"密码是错误的!",
Toast.LENGTH_LONG).show();
}
} else{
Toast.makeText(getApplicationContext(),"密码不能为空!",
Toast.LENGTH_LONG).show();
} } });
initWidget();//
}
private void initWidget()
{ login.setOnClickListener(this);
signUp.setOnClickListener(this);
et_username.setOnFocusChangeListener(new OnFocusChangeListener()
{ @Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String username=et_username.getText().toString().trim();
if(username.length()<4){
Toast.makeText(MainActivity.this, "用户名不能小于4个字符", Toast.LENGTH_SHORT);
}
}
} });
et_userPsd.setOnFocusChangeListener(new OnFocusChangeListener()
{ @Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String password=et_userPsd.getText().toString().trim();
if(password.length()<4){
Toast.makeText(MainActivity.this, "密码不能小于4个字符", Toast.LENGTH_SHORT);
}
}
} });
} public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.login:
if(checkEdit())
{
login();
}
break;
case R.id.signUp:
Intent intent2=new Intent(MainActivity.this,SignUp.class);
startActivity(intent2);
break;
}
} private boolean checkEdit(){
if(et_username.getText().toString().trim().equals("")){
Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,StudentMainActivity.class);
startActivity(intent);
}else if(et_userPsd.getText().toString().trim().equals("")){
Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
}else{
return true;
}
return false;
} private void login(){
//这个网址需要改动
String httpUrl="http://192.168.1.102:8080/web-test/login.jsp";
HttpPost httpRequest=new HttpPost(httpUrl);
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",et_username.getText().toString().trim()));
params.add(new BasicNameValuePair("password",et_userPsd.getText().toString().trim()));
HttpEntity httpentity = null;
try {
httpentity = new UrlEncodedFormEntity(params,"utf8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpRequest.setEntity(httpentity);
HttpClient httpclient=new DefaultHttpClient();
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(httpResponse.getStatusLine().getStatusCode()==200)
{
String strResult = null;
try {
strResult = EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(MainActivity.this, strResult, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,StudentMainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this, "登录失败!", Toast.LENGTH_SHORT).show();
} }
public static String MD5(String str){
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
char[] charArray = str.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte)charArray[i];
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int)md5Bytes[i])&0xff;
if(val<16){
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static String encryptmd5(String str){
char[] a = str.toCharArray();
for (int i = 0; i < a.length; i++) {
a[i] = (char)(a[i]^'1');
}
String s = new String(a);
return s;
}
}

添加权限:

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

Android之登录时密码的保护Android之登录时密码的保护

Android之登录时密码的保护的更多相关文章

  1. Android SharedPreferences登录记住密码

    SharedPreferences是Android中存储简单数据的一个工具类.可以想象它是一个小小的Cookie,它通过用键值对的方式把简单 数据类型(boolean.int.float.long和S ...

  2. android手机登录时遇到&OpenCurlyDoubleQuote;QQ安全登录发现病毒”解决

    android手机作为开源系统非常容易感染病毒,有时候我们会经常遇到手机QQ登录时检测到app被感染,一般情况是由手机感染病毒所引起的,安装腾讯管家后只能检测病毒和卸载感染病毒的软件,不能清除病毒.解 ...

  3. Spring-Security &lpar;学习记录五&rpar;--配置登录时&comma;密码采用md5加密,以及获取登录信息属性监听同步自己想要的登录信息

    目录 1. PasswordEncoder 采用密码加密 2. 获取当前的用户信息 1. PasswordEncoder 采用密码加密 使用前面的例子.可以看出我们数据库密码是采用明文的,我们在登录的 ...

  4. spring mvc自定义注解--登录时密码加密注解

    1,定义注解名称接口 /** * 使用该注解不用再MD5转换了 * * @author adonis * */ @Target(ElementType.PARAMETER) @Retention(Re ...

  5. sqlplus登录时密码有特殊符号解决方法

    偶然百度得到解决方法,在查看了公司有的脚本使用了这种解决方式,特记录下来,有需要的可以点击文末的链接查看原文. 本文转载https://www.cnblogs.com/lhrbest/p/656090 ...

  6. 【随笔】ssh登录时如何直接在参数中加入登录密码

    如同apt-get安装程序时会有-y参数来避免交互输入一样,我也希望在ssh登录时能够直接附加登录密码以避免交互式输入密码这一步,网上找了找,方法很多. 比如直接通过密钥免密码登录,不过需要改动很多, ...

  7. 轻松实现ajax登录时让浏览器保存密码

    将登录页面由form提交改为ajax提交,发现一个副作用——登录时浏览器不会提示是否保存密码,这样每次登录都要输入用户名/密码. html代码如下: <script> $(function ...

  8. c&num;登录时保存账号密码到cookie

    登陆界面有用户名.密码输入框,一个’记住账号密码‘的复选框. 1.登录时,勾选‘记住账号密码‘复选框,则会把用户名密码保存在客户端cookie里,保存时间为最大值(直到用户清除浏览器缓存或者取消勾选’ ...

  9. ASP&period;NET中登录时记住用户名和密码(附源码下载)--ASP&period;NET

    必需了解的:实例需要做的是Cookie对象的创建和对Cookie对象数据的读取,通过Response对象的Cookies属性创建Cookie,通过Request对象的Cookies可以读取Cookie ...

随机推荐

  1. VB模拟键盘输入的N种方法

    VB模拟键盘输入的N种方法http://bbs.csdn.net/topics/90509805hd378发表于: 2006-12-24 14:35:39用VB模拟键盘事件的N种方法 键盘是我们使用计 ...

  2. SSH框架配置释义

      创建一个bean, 依赖注入支持的不同注入方式及具体配置方法 属性注入 通过setter()方法注入bean的属性或者依赖对象.属性注入要求bean需要提供一个默认构造函数和对应的setter方法 ...

  3. 【论文阅读记录】Real-Time Correlative Scan Matching

    这篇文章是谷歌的Cartograph中实现real_time_correlative_scan_matcher的论文 Real-Time Correlative Scan MatchingEdwin ...

  4. iOS教你轻松打造瀑布流Layout

    前言 : 在写这篇文章之前, 先祝贺自己, 属于我的GitHub终于来了. 这也是我的GitHub的第一份代码, 以下文章的代码均可以在Demo clone或下载. 欢迎大家给予意见. 觉得写得不错的 ...

  5. Java基础知识强化之IO流笔记18:FileOutputStream写入数据

    1. 创建字节输出流对象,做了几件事情: (1)调用系统功能去创建文件(2)创建fos对象(3)把fos对象指向这个文件 2. 代码示例: package com.himi.fileoutputstr ...

  6. HDU 2064 汉诺塔III

    汉诺塔III Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...

  7. java-并发之高性能对象

    Hadoop之RPC          Hadoop的RPC主要是通过Java的动态代理(Dynamic Proxy)与反射(Reflect)实现,代理类是由java.lang.reflect.Pro ...

  8. MySQL 出现 The table is full 的解决方法【转】

    [MySQL FAQ]系列 — 你所不知的table is full那些事 时间 2014-08-21 12:18:56  MySQL中文网 原文  http://imysql.com/2014/08 ...

  9. error LNK2001&colon; unresolved external symbol &lowbar;&lowbar;beginthreadex

    解决方法: project->settings->C++>category->code generation->Use runtime library选Debug Mul ...

  10. arcgis api 3&period;x for js 之 echarts 开源 js 库实现地图统计图分析(附源码下载)

    前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...