The previous article introduced the MD5 encryption algorithm, the previously written code is somewhat redundant, and the readability is poor. Today, encrypt the text data and get the MD5 value of the file as a wrapper class. The code is as follows:
Package Com.itydl.utils;import Java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException; Import Java.io.ioexception;import Java.security.messagedigest;import java.security.NoSuchAlgorithmException; The path of the public class Md5utils {/** * @param path * file * @return * file MD5 value */public static string getFileMD5 (string path) { StringBuilder mess = new StringBuilder (); try {fileinputstream fis = new FileInputStream (new File (path));// Get the MD5 dongle messagedigest MD = messagedigest.getinstance ("MD5"); byte[] buffer = new Byte[10240];int len = fis.read (buffer); while (len! =-1) {md.update (buffer, 0, Len);//Continue reading Len = fis.read (buffer);} After reading the file, get the MD5 value of the file and finish getting the MD5 value. The obtained value is stored in the returned array byte[] Digest = Md.digest (); for (byte b:digest) {//to convert each byte to 16 binary int d = b & 0xff;//0x000000ffstring He xstring = integer.tohexstring (d); if (hexstring.length () = = 1) {//bytes high 4 bits is 0hexString = "0" + hexstring;} hexstring = Hexstring.touppercase (); Mess.append (hexstring);//the 2-bit hexadecimal number corresponding to each byte as string concatenation}} catch (NosuchalgoritHmexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (FileNotFoundException e) {//Todo Auto-gene Rated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return mess + "";} public static string MD5 (String str) {StringBuilder mess = new StringBuilder (); try {//Get MD5 dongle messagedigest MD = Messagedig Est.getinstance ("MD5"); byte[] bytes = Str.getbytes (); byte[] Digest = md.digest (bytes); for (byte b:digest) {// Turn each byte into a 16 decimal number int d = b & 0xff;//0x000000ffstring hexstring = integer.tohexstring (d); if (hexstring.length () = = 1) {// The high 4 bits of the byte are 0hexString = "0" + hexstring;} Mess.append (hexstring);//the 2-bit hexadecimal number corresponding to each byte is stitched together as a string}} catch (NoSuchAlgorithmException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return mess + "";}}
The first season of Java MD5 Encryption tool class for files and strings