Cryptographic tool Classes
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 &NBSP;JAVA.SECURITY.MESSAGEDIGEST;/**&NBSP;*MD5 text and file encryption <br> *http://www.kaige123.com * @author Edith */public class MD5Util { &NBSP;//16 binary protectedstatic char hex[] = { ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '}; protectedstatic messagedigest messagedigest = null; static{ try{ // Get MD5 Instances messagedigest= Messagedigest.getinstance ("MD5"); }catch (exception e) { } } //get file MD5 key publicStatic string getfilemd5string (File file) throws IOException { Fileinputstreamin = new fileinputstream (file); filechannelch = in.getchannel (); MappedByteBufferbyteBuffer = ch.map (filechannel.mapmode.read_only,0, &Nbsp; file.length ()); messagedigest.update (ByteBuffer); returnbuffertohex (Messagedigest.digest ()); } //get MD5 string key publicstatic string getmd5string (string s) { returngetmd5string (S.getBytes ()) ; } Publicstatic string getmd5string (byte[] bytes) { messagedigest.update (bytes); returnbuffertohex ( Messagedigest.digest ()); } privatestatic string buffertohex (byte bytes[]) { Returnbuffertohex (bytes, 0, bytes.length); } privatestatic string buffertohex (byte Bytes[], int m, int n) { StringBufferstringbuffer = new StringBuffer (2 * n); intk = m + n; for (int l = m; l < k; l++) { appendhexpair (Bytes[l],stringbuffer); } Returnstringbuffer.tostring (); } privatestatic void appendhexpair (byte bt, stringbuffer StringBuffer) { charc0 = hex[(bt & 0xf0) >> 4]; charc1 = hex[bt & 0xf]; stringbuffer.append (C0); stringbuffer.append (C1); }}
test class
package com.kaige123.util;import java.io.file;import java.io.ioexception;/** * Test class * @author Edith */public class Test { publicstatic void main (String[] args) throws IOException { // Get string md5 stringmd5str=md5util.getmd5string ("Edith is a Fat Man"); system.out.println (MD5STR); //Get the file md5 &nBsp; stringfilemd5str=md5util.getfilemd5string (New file ("C:/kaige/a.txt")); System.out.println (FILEMD5STR); }}
Encrypting files and strings using Java MD5