Package com.kaige123.util; Import Java.io.File; Import Java.io.FileInputStream; Import java.io.IOException; Import Java.nio.MappedByteBuffer; Import Java.nio.channels.FileChannel; Import Java.security.MessageDigest; /** * MD5 text and file encryption <br> * http://www.kaige123.com * @author Edith */ public class Md5util { //16 in-process protected static char hex[] = { ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '}; protected static MessageDigest messagedigest = null; static { try { // Get MD5 Example MessageDigest = Messagedigest.getinstance ("MD5"); } catch (Exception e) { } } // Get the file MD5 Key public static String getfilemd5string (file file) throws IOException { FileInputStream in = new FileInputStream (file); FileChannel ch = in.getchannel (); Mappedbytebuffer Bytebuffer = Ch.map (FileChannel.MapMode.READ_ONLY, 0, File.length ()); Messagedigest.update (Bytebuffer); Return Buffertohex (Messagedigest.digest ()); } // Get MD5 string Key public static string getmd5string (string s) { Return getmd5string (S.getbytes ()); } public static String getmd5string (byte[] bytes) { Messagedigest.update (bytes); Return Buffertohex (Messagedigest.digest ()); } private static String Buffertohex (byte bytes[]) { Return Buffertohex (bytes, 0, bytes.length); } private static String Buffertohex (byte bytes[], int m, int n) { StringBuffer StringBuffer = new StringBuffer (2 * n); int k = m + N; for (int l = m; l < K; l++) { Appendhexpair (Bytes[l], stringbuffer); } return stringbuffer.tostring (); } private static void Appendhexpair (Byte bt, StringBuffer StringBuffer) { char C0 = hex[(BT & 0XF0) >> 4]; Char C1 = HEX[BT & 0xf]; Stringbuffer.append (C0); Stringbuffer.append (C1); } } |