Android之登录时密码的保护

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

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

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

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

  1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2     xmlns:tools="http://schemas.android.com/tools"
  3     android:layout_width="match_parent"
  4     android:layout_height="match_parent"
  5     android:background="#E6E6E6"
  6      android:orientation="vertical">
  7      <ImageView 
  8          android:id="@+id/iv_head"
  9          android:layout_width="150dp"
 10          android:layout_height="150dp"
 11          android:layout_centerHorizontal="true"
 12          android:layout_marginTop="40dp"
 13          android:src="@drawable/ic_launcher"/>
 14      <LinearLayout 
 15          android:id="@+id/layout"
 16          android:layout_width="match_parent"
 17          android:layout_height="wrap_content"
 18          android:layout_below="@+id/iv_head"
 19          android:layout_margin="10dp"
 20          android:background="#FFFFFF"
 21          android:orientation="vertical">
 22          <RelativeLayout 
 23              android:id="@+id/rl_username"
 24              android:layout_width="match_parent"
 25              android:layout_height="wrap_content"
 26              android:layout_margin="10dp">
 27              <TextView 
 28                  android:id="@+id/tv_name"
 29                  android:layout_width="wrap_content"
 30                  android:layout_height="wrap_content"
 31                  android:layout_centerVertical="true"
 32                  android:text="账号"/>
 33              <EditText 
 34                  android:id="@+id/et_number"
 35                  android:layout_width="match_parent"
 36                  android:layout_height="wrap_content"
 37                  android:layout_marginLeft="5dp"
 38                  android:layout_toRightOf="@+id/tv_name"
 39                  android:background="@null"/>
 40          </RelativeLayout>
 41          <View 
 42              android:layout_width="match_parent"
 43              android:layout_height="2dp"
 44              android:background="#E6E6E6"/>
 45           <RelativeLayout 
 46              android:id="@+id/rl_userpsd"
 47              android:layout_width="match_parent"
 48              android:layout_height="wrap_content"
 49              android:layout_margin="10dp">
 50              <TextView 
 51                  android:id="@+id/tv_psw"
 52                  android:layout_width="wrap_content"
 53                  android:layout_height="wrap_content"
 54                  android:layout_centerVertical="true"
 55                  android:text="密码"/>
 56              <EditText 
 57                  android:id="@+id/et_password"
 58                  android:layout_width="match_parent"
 59                  android:layout_height="wrap_content"
 60                  android:layout_marginLeft="5dp"
 61                  android:layout_toRightOf="@+id/tv_psw"
 62                  android:inputType="textPassword"
 63                  android:background="@null"/>
 64          </RelativeLayout>
 65          
 66      </LinearLayout>
 67      <Button 
 68          android:id="@+id/login"
 69          android:onClick="login"
 70          android:layout_width="match_parent"
 71          android:layout_height="40dp"
 72          android:layout_below="@+id/layout"
 73          android:layout_centerHorizontal="true"
 74          android:layout_marginLeft="10dp"
 75          android:layout_marginRight="10dp"
 76          android:layout_marginTop="20dp"
 77          android:background="#3C8DC4"
 78          android:text="登录"
 79          android:textColor="#FFFFFF"/>
 80      <Button 
 81          android:id="@+id/signUp"
 82          android:layout_width="wrap_content"
 83          android:layout_height="wrap_content"
 84          android:text="注册"
 85          android:background="#E6E6E6"
 86          android:textColor="#000000"
 87          android:layout_marginTop="21dp"
 88          android:layout_centerHorizontal="true"
 89          android:layout_marginRight="10dp"
 90          android:layout_below="@+id/login"
 91          android:layout_alignParentRight="true"/>
 92 
 93      <CheckBox
 94          android:id="@+id/save"
 95          android:layout_width="wrap_content"
 96          android:layout_height="wrap_content"
 97          android:layout_alignBaseline="@+id/signUp"
 98          android:layout_alignBottom="@+id/signUp"
 99          android:layout_alignLeft="@+id/login"
100          android:layout_marginLeft="14dp"
101          android:text="记住密码" />
102     
103 </RelativeLayout>
  1 package com.itcast.test03;
  2 import java.io.BufferedReader;
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.io.InputStreamReader;
  6 import java.io.UnsupportedEncodingException;
  7 import java.security.MessageDigest;
  8 import java.security.NoSuchAlgorithmException;
  9 import java.util.ArrayList;
 10 import java.util.List;
 11 import org.apache.http.HttpEntity;
 12 import org.apache.http.HttpResponse;
 13 import org.apache.http.NameValuePair;
 14 import org.apache.http.ParseException;
 15 import org.apache.http.client.ClientProtocolException;
 16 import org.apache.http.client.HttpClient;
 17 import org.apache.http.client.entity.UrlEncodedFormEntity;
 18 import org.apache.http.client.methods.HttpPost;
 19 import org.apache.http.impl.client.DefaultHttpClient;
 20 import org.apache.http.message.BasicNameValuePair;
 21 import org.apache.http.util.EntityUtils;
 22 import org.json.JSONArray;
 23 import org.json.JSONObject;
 24 import android.os.Build;
 25 import android.os.Bundle;
 26 import android.os.StrictMode;
 27 import android.annotation.SuppressLint;
 28 import android.annotation.TargetApi;
 29 import android.app.Activity;
 30 import android.content.Intent;
 31 import android.content.SharedPreferences;
 32 import android.text.TextUtils;
 33 import android.util.Log;
 34 import android.view.Menu;
 35 import android.view.View;
 36 import android.view.View.OnClickListener;
 37 import android.view.View.OnFocusChangeListener;
 38 import android.widget.Button;
 39 import android.widget.CheckBox;
 40 import android.widget.EditText;
 41 import android.widget.Toast;
 42 
 43 
 44 public class MainActivity extends Activity implements OnClickListener {
 45     private EditText et_username;
 46     private EditText et_userPsd;
 47     private Button login;
 48     private Button signUp;
 49     private CheckBox save;
 50     private String user,pass;
 51     @Override
 52     protected void onCreate(Bundle savedInstanceState) {
 53         super.onCreate(savedInstanceState);       
 54         setContentView(R.layout.activity_main);
 55         et_username = (EditText)findViewById(R.id.et_number);
 56         et_userPsd = (EditText)findViewById(R.id.et_password);
 57         login=(Button)findViewById(R.id.login);
 58         signUp=(Button)findViewById(R.id.signUp);
 59         save = (CheckBox)findViewById(R.id.save);
 60         save.setOnClickListener(new CheckBox.OnClickListener(){
 61             public void onClick(View v) {
 62                 SharedPreferences pre = getSharedPreferences("loginvalue",
 63                                                     MODE_WORLD_WRITEABLE);
 64                 pass = MD5( et_userPsd.getText().toString());
 65                 user = et_username.getText().toString();
 66                 if (!pass.equals("") && !user.equals("")) {
 67                             pre.edit().putString("username",
 68                                     et_username.getText().toString())
 69                                     .putString("password", encryptmd5(pass)).commit();
 70                 Toast.makeText(getApplicationContext(),"保存成功!",
 71                 Toast.LENGTH_SHORT).show();
 72                 } else{
 73                 Toast.makeText(getApplicationContext(),"密码不能为空!",
 74                 Toast.LENGTH_LONG).show();
 75         }
 76                 }
 77         });
 78         login.setOnClickListener(new Button.OnClickListener() {
 79              
 80             @Override
 81             public void onClick(View v) {
 82                 
 83             SharedPreferences sp = getSharedPreferences("loginvalue",MODE_WORLD_READABLE);
 84             String loginuser = sp.getString("username",null);
 85             String loginpass = sp.getString("password",null);
 86              
 87             user = et_username.getText().toString();
 88             pass = et_userPsd.getText().toString();
 89              
 90             String passmd5 = MD5(pass);
 91             String encryptmd5 = encryptmd5(passmd5);
 92              
 93             System.out.println("username="+ loginuser
 94             + "-------------password="+ loginpass);
 95             System.out.println("user=="+ user
 96             + "-------------encryptmd5=="+ encryptmd5);
 97             if (!user.equals("") && !pass.equals("")) {
 98             if (user.equals(loginuser) && encryptmd5.equals(loginpass)) {
 99             Intent intent = new Intent();
100             intent.setClass(MainActivity.this, StudentMainActivity.class);
101             MainActivity.this.startActivity(intent);
102             finish();
103             } else{
104             Toast.makeText(getApplicationContext(),"密码是错误的!",
105             Toast.LENGTH_LONG).show();
106             }
107             } else{
108             Toast.makeText(getApplicationContext(),"密码不能为空!",
109             Toast.LENGTH_LONG).show();
110             }
111              
112             }
113              
114             });
115         initWidget();//
116         }
117     private void initWidget()
118     {
119         
120         login.setOnClickListener(this);
121         signUp.setOnClickListener(this);
122         et_username.setOnFocusChangeListener(new OnFocusChangeListener()
123         {
124 
125             @Override
126             public void onFocusChange(View v, boolean hasFocus) {
127                 // TODO Auto-generated method stub
128                 if(!hasFocus){
129                     String username=et_username.getText().toString().trim();
130                     if(username.length()<4){
131                         Toast.makeText(MainActivity.this, "用户名不能小于4个字符", Toast.LENGTH_SHORT);
132                     }
133                 }
134             }
135             
136         });
137         et_userPsd.setOnFocusChangeListener(new OnFocusChangeListener()
138         {
139 
140             @Override
141             public void onFocusChange(View v, boolean hasFocus) {
142                 // TODO Auto-generated method stub
143                 if(!hasFocus){
144                     String password=et_userPsd.getText().toString().trim();
145                     if(password.length()<4){
146                         Toast.makeText(MainActivity.this, "密码不能小于4个字符", Toast.LENGTH_SHORT);
147                     }
148                 }
149             }
150             
151         });
152     }
153     
154 
155     public void onClick(View v) {
156         // TODO Auto-generated method stub
157         switch(v.getId())
158         {
159         case R.id.login:
160             if(checkEdit())
161             {
162                 login();
163             }            
164             break;
165         case R.id.signUp:
166             Intent intent2=new Intent(MainActivity.this,SignUp.class);
167             startActivity(intent2);
168             break;
169         }
170     }
171     
172     private boolean checkEdit(){
173         if(et_username.getText().toString().trim().equals("")){
174             Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
175             Intent intent=new Intent(MainActivity.this,StudentMainActivity.class);
176             startActivity(intent);
177         }else if(et_userPsd.getText().toString().trim().equals("")){
178             Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
179         }else{
180             return true;
181         }
182         return false;
183     }
184     
185     private void login(){
186         //这个网址需要改动
187         String httpUrl="http://192.168.1.102:8080/web-test/login.jsp";
188         HttpPost httpRequest=new HttpPost(httpUrl);
189         List<NameValuePair> params=new ArrayList<NameValuePair>();
190         params.add(new BasicNameValuePair("username",et_username.getText().toString().trim()));
191         params.add(new BasicNameValuePair("password",et_userPsd.getText().toString().trim()));
192         HttpEntity httpentity = null;
193         try {
194             httpentity = new UrlEncodedFormEntity(params,"utf8");
195         } catch (UnsupportedEncodingException e) {
196             // TODO Auto-generated catch block
197             e.printStackTrace();
198         }
199         httpRequest.setEntity(httpentity);
200         HttpClient httpclient=new DefaultHttpClient();
201         HttpResponse httpResponse = null;
202         try {
203             httpResponse = httpclient.execute(httpRequest);
204         } catch (ClientProtocolException e) {
205             // TODO Auto-generated catch block
206             e.printStackTrace();
207         } catch (IOException e) {
208             // TODO Auto-generated catch block
209             e.printStackTrace();
210         }
211         if(httpResponse.getStatusLine().getStatusCode()==200)
212         {
213             String strResult = null;
214             try {
215                 strResult = EntityUtils.toString(httpResponse.getEntity());
216             } catch (ParseException e) {
217                 // TODO Auto-generated catch block
218                 e.printStackTrace();
219             } catch (IOException e) {
220                 // TODO Auto-generated catch block
221                 e.printStackTrace();
222             }
223             Toast.makeText(MainActivity.this, strResult, Toast.LENGTH_SHORT).show();
224             Intent intent=new Intent(MainActivity.this,StudentMainActivity.class);
225             startActivity(intent);
226         }
227         else
228             
229         {
230             Toast.makeText(MainActivity.this, "登录失败!", Toast.LENGTH_SHORT).show();
231         }
232         
233     }
234  public static String MD5(String str){    
235         MessageDigest md5 = null;    
236     try {
237         md5 = MessageDigest.getInstance("MD5");
238     } catch (NoSuchAlgorithmException e) {
239         // TODO Auto-generated catch block
240         e.printStackTrace();
241         return "";
242     }
243      char[] charArray = str.toCharArray();
244      byte[] byteArray = new byte[charArray.length];
245      for (int i = 0; i < charArray.length; i++) {
246         byteArray[i] = (byte)charArray[i];
247     }
248      byte[] md5Bytes = md5.digest(byteArray);
249      StringBuffer hexValue = new StringBuffer();
250      for (int i = 0; i < md5Bytes.length; i++) {
251         int val = ((int)md5Bytes[i])&0xff;
252         if(val<16){
253             hexValue.append("0");
254         }
255         hexValue.append(Integer.toHexString(val));
256     }
257      return hexValue.toString();     
258  }
259  public static String encryptmd5(String str){
260      char[] a = str.toCharArray();
261      for (int i = 0; i < a.length; i++) {
262         a[i] = (char)(a[i]^'1');
263     }
264      String s = new String(a);
265      return s;
266  }
267  }

添加权限:

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

原文地址:https://www.cnblogs.com/kangyaping/p/5440329.html