Java servlet mobile App Access Interface (i) Data encryption transmission verification _java

Source: Internet
Author: User
Tags md5 md5 encryption uuid stringbuffer

Several previous essays on the Servlet, which is combed the simple use of the servlet process, the next article will be mainly around the mobile phone app access interface to continue to write, MD5 encryption transmission---> SMS Verification---> mobile phone push---> Share---> Baidu Cloud----> Payment .... Third-party business ... Because I am a novice I also write while learning, inadequate local hope understanding.

Today this article mainly involves the encryption of Javaservlet transmission data, the combination of client request parameters, and will be accompanied by all the problems I encountered in the middle and the solution.

Because the phone access interface is published, so no matter what language to write the interface, we should do the corresponding security measures, otherwise people know your URL, intercept the client's request, and then modify the submission parameters, so the loss is big. The most common use of the servlet write interface should also be the transmission of data for a cryptographic, if it is webservice. NET WCF such technology to write, but also related to the certificate matching ....

One, the request data parameter encryption and realizes the idea.

Encryption here I use the MD5 32-bit encryption, 32-bit is an irreversible encryption, so even if the hackers intercepted, it is no way to encrypt our MD5 value, decrypted into our encryption when the combination of strings. Of course this is not absolute, as if a few years ago, computer experts have deciphered the MD5 encryption method, but I think that the technology may not be published at random, and then even if the announcement is not common people can understand, or you casually ask a programmer MD5 encryption you still use it, that must answer is no.

1, first of all, I said I request the combination of parameters, because it involves MD5 encryption, so we have to use the app login account, feedback to the user two token, the first token is the unique value of the user identity, this token needs to be added to the request interface parameters ( This parameter is involved in the encryption, you do not affect, I am here to participate in, because the servlet needs to query the user's encryption required token, the second token is used to encrypt the MD5 value, this token can not be added to the request interface parameters, And these two token we all must save to the database, because after the user requests the interface, the Serlvet needs to obtain the user in the parameter token and then goes to the database to query MD5 encryption need token, The servlet then adds the encrypted token of the query to the string that the user passes in, carries out a MD5 encryption again, encrypts the value after the MD5 that the user passes after encrypting, whether it is the same as the value of the servlet after the encryption, if it is different, then there may be two reasons, The servlet here encrypts the string combination error, and the user transmits the data in the middle of a truncated modification. These two token are generated by the Java UUID that I use, and a unique value should be generated for the UUID. The build method is simple. Here is the code

 public static String Getuuid () 
 {return 
 uuid.randomuuid (). toString (); 
  
  

The following is a Java MD5 32-bit encryption method

 public static String Md5encrypt (String groupparamertstr) throws 
   unsupportedencodingexception {MessageDigest messagedigest = null; 
    try {messagedigest = messagedigest.getinstance ("MD5"); 
    Messagedigest.reset (); 
   Messagedigest.update (Groupparamertstr.getbytes ("UTF-8")); 
    catch (NoSuchAlgorithmException e) {System.out.println ("nosuchalgorithmexception caught!"); 
   System.exit (-1); 
   catch (Unsupportedencodingexception e) {e.printstacktrace (); 
   } byte[] ByteArray = Messagedigest.digest (); 
   StringBuffer Md5strbuff = new StringBuffer (); 
     for (int i = 0; i < bytearray.length i++) {if (Integer.tohexstring (0xFF & Bytearray[i)). Length () = 1) 
    Md5strbuff.append ("0"). Append (integer.tohexstring (0xFF & Bytearray[i)); 
   Else Md5strbuff.append (integer.tohexstring (0xFF & Bytearray[i])); 
  
  
 return md5strbuff.tostring (); }

The following is the servlet this side gets the parameter to encrypt, using the encryption result to compare with the encryption result that the user requests passes. If the request is the same, the request parameter value may have been modified

The following method three parameters first is the user token the second is the required parameters for encryption, and so on after we query the user Token encryption token, we need to splice it to the Servlet encryption required JSON string, the third is from the client came Encrypt result string Here the method returns 0 to indicate that the user has no problem with the encrypted result, otherwise there is an error public static int posttokenverify (String token, jsonobject requestjsonobject, STR
  ing encryptstrvalue) {int returnvalue=0;
  String[] Mysqlparameter=new String[]{token}; The following is the user token query user's encryption token ResultSet returndata=mysqlhepler.executequery ("select * from InfoSheet where idtoken=?", M
  Ysqlparameter);
  Jsonobject Returnobject=null;
  try {returnobject = Resulttojsontool.resultsettojsonobject (returndata);
  catch (SQLException E1) {//TODO auto-generated catch block E1.printstacktrace ();
  catch (Jsonexception E1) {//TODO auto-generated catch block E1.printstacktrace ();
   } String byencryptstrvalue= "";
    
    try {if (returnobject.getstring ("Encrypttoken"). Length () >2) {//Description of the user's Idtoken presence,//return returnvaluestring; {"Idtoken": "123456", "id": "The", "pwd": "The", "Encrypttoken": "23456"", "Account": "Hang"}/* The following code is in the matching JAVAMD5 encrypted string, because the user encryption, added encryption token to the encrypted string, but the request can not pass the encryption token, so we need to use the servlet encryption User token to query the user's encryption toke, query out, we need to splice to, request parameter JSON, so that the servlet encrypted string is the same as the user's encrypted string. The following is the query out the encryption token after stitching to the request parameters after the method, * * byencryptstrvalue=requestjsonobject.tostring (). substring (0, Requestjsonobject.tos
    
     Tring (). Length ()-1);
     Jsonobject encrypttokenjsonobject=new jsonobject ();
     
    Encrypttokenjsonobject.put ("Encrypttoken", Returnobject.getstring ("Encrypttoken"));
    
    String value1=encrypttokenjsonobject.tostring (). substring (1, encrypttokenjsonobject.tostring (). Length ());
    
    
    
    Byencryptstrvalue=byencryptstrvalue+ "," +value1;  else {Returnvalue=1;//idtoken error} catch (Jsonexception E1) {//TODO auto-generated
  Catch block E1.printstacktrace (); The try {//The following method is called using a concatenation of the correct string to encrypt on the servlet, returning a result that compares the encrypted results of the user pass string javamd5result=encryptsafa.md5encr
   
   Ypt (Byencryptstrvalue); If (Javamd5result.equals (Encryptstrvalue))
   {//cryptographic string is correct} else {returnvalue= 2;//cryptographic result is wrong} catch (Unsupportedencodingexception e) {
  TODO auto-generated Catch block E.printstacktrace ();
 Return returnvalue;
 }

All of the above are encapsulated methods that are called by the servlet, and here are all the code that the servlet page calls

1, the requested URL

Here I am passing is a dictionary converts a JSON-formatted parameter to a key-value pair form that requests only one parameter. The Idtoken in the parameter is the user token, the value I was randomly added to the database by a 123456

Not using UUID, of course, it certainly does not.

http://localhost:8080/javaservlettest/2.jsp?parameter={"parameter": "{idtoken\": \ "123456\", \ "pwd\": \ "Chinese characters \", \ " Account\ ": \" hang\ "}", "Md5str": "672f4a8c6fb92103c01d4275e46df790"}

The following is the code for Servlet page processing, which is to verify that the user request has been modified on the way to delivery.

 Yesterday encountered a problem here, that is, when I request the parameters in Chinese, the servlet after the acquisition is garbled, and then use the following this way good.
   
   String Requestjsonstr=new string (request.getparameter ("parameter"). GetBytes ("Iso8859-1"), "UTF-8");
  Submit Parameters Jsonobject Objectparameter=null;
  Idtoken Jsonobject Requestparmeter=null;
  Idtoken String idtoken= "";
   The client encrypts string md5str= "";
    try {//Get the total JSON string, which is actually a parameter objectparameter=new jsonobject (REQUESTJSONSTR) that we pass from the URL only paramter; Submit parameters, a key value of JSON, request parameters inside the paramter, in fact, this parameter is placed in the business of the required parameters, such as your login account password This type of Requestparmeter=new jsonobject (
     Objectparameter.getstring ("parameter")); 
     Idtoken This is the user token, he is the user's only identification, we are required through him to query the database in the corresponding encryption token idtoken=requestparmeter.getstring ("Idtoken");
  The client encrypts the string md5str=objectparameter.getstring ("Md5str");
  catch (Jsonexception E1) {//TODO auto-generated catch block E1.printstacktrace (); //MD5 encrypted string//Next step is to verify token is correct int tokenverifyresult=encryptsafa.posttokenverify (Idtoken, R EquestparmetEr, md5str);
     
      if (tokenverifyresult==0) {out.println ("token encryption is correct");
       else {out.println ("Encrypt token or encryption method error");
       
     Return
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.