Use Java to implement the MD5 Algorithm

Source: Internet
Author: User

Found on a foreigner's website! Modified it!

 

Import java. Security. messagedigest;
Public class MD5
...{
Private messagedigest MD5;
Private Static MD5 instance;

/***//**
* Constructs the MD5 object and sets the string whose MD5 is to be computed.
*
* @ Param instr the <code> string </code> whose MD5 is to be computed
*/
Public synchronized static MD5 getmd5instance ()
...{
If (instance = NULL)
Instance = new MD5 ();
Return instance;
}
Private MD5 ()
...{
Try ...{

This. MD5 = messagedigest. getinstance ("MD5 ");
}
Catch (exception E)
...{
System. Out. println (E. tostring ());
E. printstacktrace ();
}
}

/***//**
* Computes the MD5 fingerprint of a string.
*
* @ Return the MD5 Digest of the input <code> string </code>
*/
Public String compute (string instr)
...{
// Convert input string to a char []
// Convert that char [] to byte []
// Get the MD5 Digest as byte []
// Bit-wise and that byte [] with 0xff
// Prepend "0" to the output stringbuffer to make sure that we don't end up
// Something like "e21ff" instead of "e201ff"

Char [] chararray = instr. tochararray ();
Byte [] bytearray = new byte [chararray. Length];

For (INT I = 0; I <chararray. length; I ++)
Bytearray [I] = (byte) chararray [I];

Byte [] md5bytes = This. md5.digest (bytearray );

Stringbuffer hexvalue = new stringbuffer ();

For (INT I = 0; I <md5bytes. length; I ++)
...{
Int val = (INT) md5bytes [I]) & 0xff;
If (Val <16) hexvalue. append ("0 ");
Hexvalue. append (integer. tohexstring (VAL ));
}

Return hexvalue. tostring ();
}
Public static void main (string [] ARGs)
...{
System. Out. println (md5.getmd5instance (). Compute (""). touppercase ());
}
}

 

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.