Java use MessageDigest to get a string or file MD5 detailed

Source: Internet
Author: User
Tags md5 sha1


MD5 is a commonly used encryption algorithm, and is often used to verify information integrity, such as file integrity. In terms of terminology, MD5 is a message digest algorithm (Messages Digest algorithm). In addition, there is a common message digest algorithm SHA1. If you want to know these words, you can go to Baidu Encyclopedia: MD5, SHA1, Message digest algorithm.






Java has implemented the MD5, SHA1 algorithm. Use the java.security.MessageDigest class to get the MD5 and SHA1 results of strings and files.






1. MD5 of strings (with detailed comments in the following code)


public static String stringMD5(String input) {
Try {
//Get an MD5 converter (if you want to change SHA1 parameter to "SHA1")
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
//The input string is converted to a byte array
byte[] inputByteArray = input.getBytes();
//Inputbytearray is an array of bytes converted from an input string
messageDigest.update(inputByteArray);
//Convert and return the result, which is also a byte array, containing 16 elements
byte[] resultByteArray = messageDigest.digest();
//Character array conversion to string return
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
Return null;
}
}








The following function is used to replace a byte array with a 16-binary string


public static String byteArrayToHex(byte[] byteArray) {
//First, initialize a character array to store each hexadecimal character
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
//New an array of characters, which is used to form the result string (explain: a byte is an eight bit binary, that is, two hexadecimal characters (the 8th power of 2 is equal to the 2nd power of 16))
char[] resultCharArray =new char[byteArray.length * 2];
//Traverse byte array, convert to character and put it into character array through bit operation (high efficiency of bit operation)
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b& 0xf];
}
//Character array combined into string return
return new String(resultCharArray);
}











As you can see from the code above, the step to MD5 the string using MessageDigest is to convert the string into a byte array, to MD5 the algorithm, and finally to return a byte array, and we'll turn ourselves into a 32-bit string.






2. Document MD5






MD5 The file can also be the same as the string MD5, first to convert the file into a byte array, followed by the string MD5 exactly the same.



But if it is a particularly large file, all of a sudden the array of a file read into memory, then the estimated memory can not be too much.



For large files, you can use Digestinputstream.


public static String fileMD5(String inputFile) throws IOException {
//Buffer size (this can extract a parameter)
int bufferSize = 256 * 1024;
FileInputStream fileInputStream = null;
DigestInputStream digestInputStream = null;
Try {
//Get an MD5 converter (again, you can change to SHA1 here)
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
//Using digestinputstream
fileInputStream = new FileInputStream(inputFile);
digestInputStream = new DigestInputStream(fileInputStream,messageDigest);
//MD5 is processed during read until the file is read
byte[] buffer =new byte[bufferSize];
while (digestInputStream.read(buffer) > 0);
//Get the final messagedigest
messageDigest= digestInputStream.getMessageDigest();
//The result is also a byte array with 16 elements
byte[] resultByteArray = messageDigest.digest();
//Similarly, convert a byte array to a string
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
Return null;
} finally {
Try {
digestInputStream.close();
} catch (Exception e) {
}
Try {
fileInputStream.close();
} catch (Exception e) {
}
}
}


 






The above method I have tested the size of about 4G of files, the resulting MD5 value and online Download a MD5 small tool to get the MD5 value, which shows that the way there is no problem. However, the MD5 of large files is very slow, 4G files run for a minute (I5 processor 6G Memory 64-bit XP system laptop).






Appendix 1: I also see a way to MD5 files on the Internet





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 Bytearraytohex (Messagedigest.digest ());
}





I've tried this, too, but if the file is larger than 2G, then there's an exception. So it's not recommended.






Appendix 2: Main method to test file MD5





public static void Main (string[] args) {

  long starttime = System.currenttimemillis ();

  try {
    System.out.println (fileMD5 ("e:/software/vs2008proedition90daytrialchsx1435983.iso"));
  } catch ( IOException e) {
    e.printstacktrace ();
  }

  Long endtime = System.currenttimemillis ();

  System.out.println ((endtime-starttime)/1000);
}









Author: Fork Brother reproduced Please specify the source: http://blog.csdn.net/xiao__gui/article/details/8148203











Related Article

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.