Package CN. vicky. utils; import Java. security. messagedigest; public class MD5 {// Private Final Static string [] hexdigits = {"0", "1", "2", "3", "4 ", "5", // "6", "7", "8", "9", "A", "B", "C", "D ", "E", "F "}; //// ** // * convert the byte array to a hexadecimal string // * @ Param B // * byte array // * @ return hexadecimal string // * // public static string bytearraytohexstring (byte [] B) {// stringbuffer resultsb = new stringbuffer (); // For (INT I = 0; I <B. length; I ++) {// resultsb. append (bytetohexstring (B [I]); //} // return resultsb. tostring (); //} // Private Static string bytetohexstring (byte B) {// int n = B; // If (n <0) N = 256 + N; // int d1 = N/16; // int D2 = n % 16; // return hexdigits [D1] + hexdigits [D2]; ///}/*** convert 16-bit byte [] to 32-Bit String ** @ Param buffer * @ return */Private Static string tohex (byte buffer []) {stringbuilder sb = new stringbuilder (buffer. length * 2); For (INT I = 0; I <buffer. length; I ++) {sb. append (character. fordigit (buffer [I] & 240)> 4, 16); sb. append (character. fordigit (buffer [I] & 15, 16);} return sb. tostring ();} public static string md5encode (string origin) {string resultstring = NULL; try {resultstring = new string (origin); messagedigest MD = messagedigest. getinstance ("MD5"); // MD5 Sha sha1 SHA-1resultString = tohex (MD. digest (resultstring. getbytes (); // or // resultstring = bytearraytohexstring (MD. digest (resultstring //. getbytes ();} catch (exception ex) {} return resultstring;} public static string shaencode (string origin) {string resultstring = NULL; try {resultstring = new string (origin); messagedigest MD = messagedigest. getinstance ("Sha"); resultstring = tohex (MD. digest (resultstring. getbytes (); // or // resultstring = bytearraytohexstring (MD. digest (resultstring //. getbytes ();} catch (exception ex) {} return resultstring ;}}
For more information, see:
Http://blog.csdn.net/eclipser1987/article/details/5158784