MD5 hashing in Java, written by dimport

Source: Internet
Author: User

A wrapper for Java's MD5 class that makes life a little easier.

This class lets you produce an MD5 hashcode for some binary data. it is useful for storing passwords in databases or file systems, or for checking the validity of downloaded files. it also provides an example of the singleton design pattern.

 

Import java. Security .*;

Public class MD5
{

Private messagedigest MD = NULL;
Static private MD5 MD5 = NULL;
Private Static final char [] hexchars = {'0', '1', '2', '3', '4', '5', '6 ', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F '};

/**
* Constructor is private so you must use the getinstance Method
*/
Private MD5 () throws nosuchalgorithmexception
{
MD = messagedigest. getinstance ("MD5 ");
}


/**
* This returns the singleton instance
*/
Public static MD5 getinstance () throws nosuchalgorithmexception
{

If (MD5 = NULL)
{
MD5 = new MD5 ();

}

Return (MD5 );
}

Public String hashdata (byte [] datatohash)

{

Return hexstringfrombytes (calculatehash (datatohash )));
}



Private byte [] calculatehash (byte [] datatohash)

{
Md. Update (datatohash, 0, datatohash. Length );

Return (Md. Digest ());
}



Public String hexstringfrombytes (byte [] B)

{

String hex = "";

Int MSB;

Int LSB = 0;
Int I;

// MSB maps to idx 0

For (I = 0; I <B. length; I ++)

{

MSB = (INT) B [I] & 0x000000ff)/16;

LSB = (INT) B [I] & 0x000000ff) % 16;
Hex = hex + hexchars [MSB] + hexchars [LSB];
}
Return (HEX );
}


Public static void main (string [] ARGs)
{
Try
{

MD5 MD = md5.getinstance ();
System. Out. println (Md. hashdata ("hello". getbytes ()));
}
Catch (nosuchalgorithmexception E)
{
E. printstacktrace (system. Out );
}
}
}

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.