Android登錄時(shí)密碼保護(hù)功能
在很多的Android項(xiàng)目中都需要用戶登錄、注冊(cè)。這樣的話在開發(fā)中做好保護(hù)用戶密碼的工作就顯得尤為重要。這里我把自己的密碼保護(hù)方法記錄下來。
這是我建了一個(gè)保存密碼的文件,以便于檢查自己保存密碼或者上傳到服務(wù)器的時(shí)候密碼是否已經(jīng)被保護(hù)了。這就是當(dāng)我輸入用戶名和密碼之后點(diǎn)擊記住密碼之后
保存在SD卡上的文件,打開之后可以明顯的看到密碼已經(jīng)被保護(hù)了。

下面是我的布局文件以及主程序的代碼:
<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="賬號(hào)"/>
<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="注冊(cè)"
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(),"密碼是錯(cuò)誤的!",
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個(gè)字符", 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個(gè)字符", 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(){
//這個(gè)網(wǎng)址需要改動(dòng)
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;
}
}
添加權(quán)限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" />


以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android 開發(fā)仿簡書登錄框可刪除內(nèi)容或顯示密碼框的內(nèi)容
- Android設(shè)計(jì)登錄界面、找回密碼、注冊(cè)功能
- 在Nginx用htpasswd對(duì)網(wǎng)站進(jìn)行密碼保護(hù)的設(shè)置方法
- 頁面使用密碼保護(hù)代碼
- 設(shè)置密碼保護(hù)的SqlServer數(shù)據(jù)庫備份文件與恢復(fù)文件的方法
- Android開發(fā)之登錄驗(yàn)證實(shí)例教程
- Android集成新浪微博第三方登錄的方法
- Android開發(fā)之注冊(cè)登錄方法示例
- Android實(shí)現(xiàn)登錄功能demo示例
- Android調(diào)用第三方QQ登錄代碼分享
相關(guān)文章
實(shí)例講解Android應(yīng)用開發(fā)中Fragment生命周期的控制
這篇文章主要介紹了Android應(yīng)用開發(fā)中Fragment生命周期的控制,Fragment依賴于Activity,所以生命周期方面也受Activity的影響,需要的朋友可以參考下2016-02-02
Android pdf viewer在android studio應(yīng)用問題說明詳解
這篇文章主要介紹了Android pdf viewer在android studio應(yīng)用問題說明的相關(guān)資料,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09
Android動(dòng)態(tài)加載Activity原理詳解
這篇文章主要介紹了Android動(dòng)態(tài)加載Activity原理詳解的相關(guān)資料,需要的朋友可以參考下2016-04-04
詳解Android6.0運(yùn)行時(shí)權(quán)限管理
自從Android6.0發(fā)布以來,在權(quán)限上做出了很大的變動(dòng),不再是之前的只要在manifest設(shè)置就可以任意獲取權(quán)限,而是更加的注重用戶的隱私和體驗(yàn)。本文詳細(xì)介紹了Android6.0運(yùn)行時(shí)權(quán)限管理。需要的朋友一起來看下吧2016-12-12
Android懸浮按鈕點(diǎn)擊返回頂部FloatingActionButton
這篇文章主要為大家詳細(xì)介紹了Android懸浮按鈕FloatingActionButton點(diǎn)擊回到頂部的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02
Android 快速使用正則表達(dá)式,校驗(yàn)身份證號(hào)的實(shí)例
下面小編就為大家分享一篇Android 快速使用正則表達(dá)式,校驗(yàn)身份證號(hào)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Flutter StaggeredGridView實(shí)現(xiàn)瀑布流效果
這篇文章主要為大家詳細(xì)介紹了Flutter StaggeredGridView實(shí)現(xiàn)瀑布流效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Android App中實(shí)現(xiàn)簡單的刮刮卡抽獎(jiǎng)效果的實(shí)例詳解
這篇文章主要介紹了Android App中實(shí)現(xiàn)簡單的刮刮卡抽獎(jiǎng)效果的實(shí)例詳解,文中主要借助Bitmap的canvas.drawPath的api來實(shí)現(xiàn),需要的朋友可以參考下2016-03-03

