欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android登录时密码保护功能

程序员文章站 2024-02-12 14:47:34
在很多的android项目中都需要用户登录、注册。这样的话在开发中做好保护用户密码的工作就显得尤为重要。这里我把自己的密码保护方法记录下来。 这是我建了一个保存密码的文件...

在很多的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登录时密码保护功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。