Android—構建安全的Android用戶端請求,避免非法請求,android用戶端

來源:互聯網
上載者:User

Android—構建安全的Android用戶端請求,避免非法請求,android用戶端

        今天通過執行個體來介紹一下如何構建安全的Android用戶端請求,避免非法請求:

        伺服器端代碼:

        代碼1—工具類:

package com.ghj.packageoftool;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.text.SimpleDateFormat;import java.util.Date;/** * 字串SHA-1轉換 *  * @author 高煥傑 */public class Sha1Util {public static String SHA(String paramString) {MessageDigest localMessageDigest;try {localMessageDigest = MessageDigest.getInstance("SHA-1");localMessageDigest.update(paramString.getBytes());return toHexString(localMessageDigest.digest()).toUpperCase();} catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {localNoSuchAlgorithmException.printStackTrace();return "";}}private static String toHexString(byte[] digestArray) {if (digestArray == null || digestArray.length <= 0) {return "";}StringBuilder stringBuilder = new StringBuilder();for (int i = 0; i < digestArray.length; i++) {String hexString = Integer.toHexString(digestArray[i] & 0xFF);if (hexString.length() < 2) {stringBuilder.append(0);}stringBuilder.append(hexString);}return stringBuilder.toString();}public static void main(String[] paramArrayOfString) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String timeStamp = dateFormat.format(new Date());String str = SHA("2014-12-16 10:19:30" + "miyue");System.out.println(timeStamp + "signature:"+str.equals("927CFBFC8D0F049CEDB83FB10FBEC9AC784A9460"));}}

        代碼2—過濾器類:

package com.ghj.packageoffilter;import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.ghj.packageoftool.Sha1Util;/** * 本過濾器用來校正請求是否合法 *  * @author 高煥傑 */public class CheckRequestFilter implements Filter {public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;String secretKey = "AndroidClient";String timeStamp = request.getParameter("timeStamp");String signature = request.getParameter("signature");String dateDifference = getDateDifference(timeStamp);if(dateDifference == null){//系統時間和時間戳記的差值為null,這說明該請求中的時間被認為的進行了修改且時間格式不正確。sendErrorState(response, 0);}if(!Sha1Util.SHA(timeStamp + secretKey).equals(signature)){//如果時間戳記被人為地進行了修改造成請求籤名不一致。sendErrorState(response, 1);}else if(Integer.parseInt(dateDifference) > 1000*60*5){//如果請求從建立到到達伺服器端的時間大於5分鐘,則認為請求逾時——不給別有用心的人思考的時間sendErrorState(response, 2);}else{chain.doFilter(request, response);}}private void sendErrorState(HttpServletResponse response, int errorState) {PrintWriter out = null;try {out = response.getWriter();out.println("errorState:" + errorState);out.flush();} catch (IOException e) {e.printStackTrace();}finally{out.close();}return;}/** * @see: 擷取時間戳記與當前系統時間的差值(以毫秒為單位) *  * @author GaoHuanjie */private String getDateDifference(String timeStamp){try{ if(timeStamp != null){return String.valueOf(new Date().getTime()- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStamp).getTime());//擷取系統時間(毫秒)-時間戳記時間(毫秒)}}catch(Exception e){e.printStackTrace();}return null;}public void destroy() {}public void init(FilterConfig filterConfig) throws ServletException {}}

        代碼3—Servlet類:

package com.ghj.packageofservlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServerServlet extends HttpServlet {private static final long serialVersionUID = -1052048925901833921L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/plain; charset=UTF-8");request.setCharacterEncoding("UTF-8");System.err.println(request.getParameter("clientData"));PrintWriter printWriter = response.getWriter();printWriter.print("您好Android用戶端!");printWriter.flush();printWriter.close();}}

        代碼4—設定檔:

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><filter><filter-name>checkRequestFilter</filter-name><filter-class>com.ghj.packageoffilter.CheckRequestFilter</filter-class></filter><filter-mapping><filter-name>checkRequestFilter</filter-name><url-pattern>*.do</url-pattern></filter-mapping><servlet><servlet-name>ServerServlet</servlet-name><servlet-class>com.ghj.packageofservlet.ServerServlet</servlet-class></servlet><servlet-mapping><servlet-name>ServerServlet</servlet-name><url-pattern>/ServerServlet.do</url-pattern></servlet-mapping></web-app>

        用戶端代碼:

        代碼1—工具類:

         與伺服器端工具類完全一樣!

        代碼1—Activity類:

package com.ghj.packageofactivity;import java.text.SimpleDateFormat;import java.util.Date;import org.apache.http.Header;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;import com.example.androidclient.R;import com.ghj.packageoftool.Sha1Util;import com.loopj.android.http.AsyncHttpClient;import com.loopj.android.http.AsyncHttpResponseHandler;import com.loopj.android.http.RequestParams;public class AndroidClientActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.android_client);Button sendInfoButton = (Button) findViewById(R.id.sendInfoButton);sendInfoButton.setOnClickListener(new OnClickListener(){@Override@SuppressLint("SimpleDateFormat")public void onClick(View v) {String secretKey = "AndroidClient";String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());RequestParams requestParams = new RequestParams();requestParams.add("clientData", "您好伺服器端!");requestParams.add("timeStamp", timeStamp);requestParams.add("signature", Sha1Util.SHA(timeStamp + secretKey));new AsyncHttpClient().post("http://172.16.99.207:8080/CheckRequest/ServerServlet.do", requestParams, new AsyncHttpResponseHandler() {@Overridepublic void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {if(statusCode == 200){String responseData = new String(responseBody);if(responseData.contains("errorState")){Toast.makeText(AndroidClientActivity.this, "請求非法!", Toast.LENGTH_LONG).show();}else{Toast.makeText(AndroidClientActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();}}}@Overridepublic void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {Toast.makeText(AndroidClientActivity.this, "沒有擷取到Android伺服器端的響應!", Toast.LENGTH_LONG).show();}});}});}}

        總結:

        1、由於該Demo用戶端需要依賴很多檔案和一些jar包,所以建議直接下載完整Demo工程——【0分下載Demo

           2、實現這個功能其實很簡單:一句話,想盡一切方法讓別有用心的人發出的請求失效!!!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.