Java MD5 concurrency

Source: Internet
Author: User
Tags md5 digest

Message Digest algorithm MD5 (Chinese named message Digest Algorithm version fifth) is a hash function widely used in the field of computer security to provide integrity protection for messages. The algorithm's file number is RFC 1321 (R.rivest,mit Laboratory for computer science and RSA Data Security Inc. April 1992).

View MessageDigest Source code

public void Update (byte[] input) {        engineupdate (input, 0, input.length);        state = in_progress;}

You can see here that the Engineupdate method is called, and this method makes an update operation.

The State property is then changed to indicate that the current calculation is in process.

State Default Property

Private int state = INITIAL;

Then you need to call the Messagedigest.digest () method to calculate the hash value

 

Public byte[] Digest () {/        * Resetting is the responsibility of implementors. */        byte[] result = Enginedigest (); 
   state = INITIAL;        return result;}

The calculation of the MD5 value has been completed here, the State property reverts to its initial status, and if you want to reuse the MessageDigest object, you also need to call the Messagedigest.reset () method to reset it so that this calculation will affect the next calculation. resulting in incorrect calculation results.

And the problem I encountered is, in MessageDigest in the multi-threaded environment, THREAD-1 calculation has not been completed, Thread-2 began to use the MessageDigest object for the next calculation, Thread-2 modifies the state of the messagedigest, Thread-1 is calculated using the modified messagedigest, which results in incorrect calculations.

The solution has two:

1, lock to share the same messagedigest;

public class MD5 {private static final byte[] Tohex_ ={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F ' };p rivate MessageDigest md5_ = null;static private MessageDigest md5_;static{try {md5_ = messagedigest.getinstance ("MD5" );} MD5 is Supportedcatch (NoSuchAlgorithmException e) {}; Safe to swallow};p ublic MD5 () {try {md5_ = messagedigest.getinstance ("MD5"),}//MD5 is Supportedcatch (nosuchalgorith Mexception e) {}; Safe to swallow}/*** */public static synchronized String Digest (byte[] datatohash) {md5_.update (Datatohash, 0, Datatoha Sh.length); return Hexstringfrombytes (Md5_.digest ());} /*** Non-threadsafe MD5 Digest (hashing) Function*/public String Digest (byte[] datatohash) {md5_.update (Datatohash, 0, Datatohash.length); return Hexstringfrombytes (Md5_.digest ());}  private static String hexstringfrombytes (byte[] b) {byte [] hex_bytes = new byte[b.length * 2];int i,j=0;for (i=0; i < B.length; i++) {Hex_bytes[j] = tohex_[(B[i] & 0xF0) >> 4]; hex_BYTES[J+1] = tohex_[b[i] & 0xF];j+=2;} return new String (hex_bytes);}}

  

2, each time to create a new messagedigest;

Class  Md5_test {     public   final   static  string MD5 (string s) {      char  hexdigits[] = {  ' 0 ' ,  ' 1 ',  ' 2 ',  ' 3 ',  ' 4 ',  ' 5 ',  ' 6 ',  ' 7 ',  ' 8 ',  ' 9 ',        ' a ',  ' B ', c19/> ' C ',  ' d ',  ' e ',  ' F '  };      Try  {     byte [] strtemp = S.getbytes ();     MessageDigest mdtemp = messagedigest.getinstance ("MD5");     Mdtemp.update (strtemp);     byte [] md = Mdtemp.digest ();     int  j = md.length;     Char  str[] =  new   Char [J *  2];     int  k =  0;     for  (int  i =  0; i < J; i++) {      byte  byte0 = Md[i];      str[k++] = hexdigits[byte0 >>> 4  &  0xf];      str[k++] = hexdigits[byte0 & 0xf];     }     Return   new  String (str);    } catch  (Exception e) {     return   null;    }   }     Public   static   void  main (string[] args) {    //md5_test AA = new Md5_test ();    System.out.print (md5_test. MD5 ("a"));  System.out.print (md5_test. MD5 ("%7b%7dahrcu"));   }  

  

Both of these scenarios address concurrency issues.

 

Java MD5 concurrency

Related Article

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.