Android-Construct Secure Android client requests to avoid illegal requests
Today, we use examples to describe how to construct secure Android client requests to avoid illegal requests:
Server code:
Code 1-tool class:
Package com. ghj. packageoftool; import java. security. messageDigest; import java. security. noSuchAlgorithmException; import java. text. simpleDateFormat; import java. util. date;/*** String SHA-1 conversion ** @ author Gao huanjie */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 ("10:19:30" + "miyue"); System. out. println (timeStamp + "signature:" + str. equals ("927CFBFC8D0F049CEDB83FB10FBEC9AC784A9460 "));}}
Code 2-filter class:
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 j Avax. servlet. http. httpServletResponse; import com. ghj. packageoftool. sha1Util;/*** this Filter is used to verify whether the request is legal ** @ author Gao huanjie */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; Stri Ng secretKey = "AndroidClient"; String timeStamp = request. getParameter ("timeStamp"); String signature = request. getParameter ("signature"); String dateDifference = getDateDifference (timeStamp); if (dateDifference = null) {// The difference between system time and timeStamp is null, this indicates that the time in the request has been modified and the time format is incorrect. SendErrorState (response, 0);} if (! Sha1Util. SHA (timeStamp + secretKey). equals (signature) {// If the timeStamp is artificially modified, the request signature is inconsistent. SendErrorState (response, 1);} else if (Integer. parseInt (dateDifference)> 1000*60*5) {// if the time from request creation to server arrival is more than 5 minutes, the request is deemed to have timed out-do not give the time 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 (io1_tio N e) {e. printStackTrace ();} finally {out. close ();} return;}/*** @ see: obtains the difference between the timestamp and the current system time (in milliseconds) ** @ 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 (); // obtain the system time (milliseconds)-timestamp time (milliseconds)} catch (Exception e) {e. printStackTrace ();} return null;} public void destroy () {} public void init (FilterConfig filterConfig) throws ServletException {}}
Code 3-Servlet class:
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 (HttpServletReq Uest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/plain; charsets = UTF-8"); request. setCharacterEncoding ("UTF-8"); System. err. println (request. getParameter ("clientData"); PrintWriter printWriter = respo Neuron. getWriter (); printWriter. print ("Hello Android client! "); PrintWriter. flush (); printWriter. close ();}}
Code 4-configuration file:
checkRequestFilter
com.ghj.packageoffilter.CheckRequestFilter
checkRequestFilter
*.do
ServerServlet
com.ghj.packageofservlet.ServerServlet
ServerServlet
/ServerServlet.do
Client code:
Code 1-tool class:
The same as the server tool class!
Code 1-Activity class:
Package com. ghj. packageofacti.pdf; 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. sh A1Util; 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. sendInfo Button); 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", "Hello, server! "); 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, "the request is invalid! ", 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, "no response is obtained from the Android server! ", Toast. LENGTH_LONG). show ();}});}});}}
Summary:
1. Because the Demo client depends on many files and some jar packages, we recommend that you download the complete Demo project directly --【Download Demo at 0]
2. Implementing this function is actually very simple: in a single sentence, do everything possible to invalidate the requests sent by people with ulterior motives !!!