JAVA MessageDigest MD5 SHA

Source: Internet
Author: User
Tags printable characters

MD5 is a common encryption algorithm and is often used to verify information integrity, such as file integrity. In terminology, MD5 is a Message Digest Algorithm (Message Digest Algorithm ). There is also a common message digest algorithm SHA1. If you want to know this, you can go to Baidu Encyclopedia: MD5, SHA1, message digest algorithm. Java has implemented the MD5 and SHA1 algorithms. The java. security. MessageDigest class can be used to obtain the MD5 and SHA1 results of strings and files. 1. MD5 of the String (the code below is annotated in detail) [java] public static String stringMD5 (String input) {try {// get an MD5 converter (if you want to change the SHA1 parameter to "SHA1") MessageDigest messageDigest = MessageDigest. getInstance ("MD5"); // The input string is converted into a byte array byte [] inputByteArray = input. getBytes (); // inputByteArray is the byte array messageDigest obtained from input string conversion. update (inputByteArray); // convert and return the result. It is also a byte array, which contains 16 elements: byte [] resultByteArray = messageDigest. digest (); // returns r if the character array is converted to a string. Eturn byteArrayToHex (resultByteArray);} catch (NoSuchAlgorithmException e) {return null ;}} the following function is used to convert a byte array to a hexadecimal String [java] public static String byteArrayToHex (byte [] byteArray) {// first initialize a character array, it is used to store each hexadecimal character char [] hexDigits = {'0', '1', '2', '3', '4', '5 ', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E ', 'F'}; // a new character array, which is used to form the result string (explanation: A byte is an eight-bit binary, that is, two hexadecimal characters (the power of 2 is equal to the power of 16) char [] resultCharArray = new Char [byteArray. length * 2]; // traverses the byte array. bitwise operations are performed (bit operation efficiency is high) to convert it into characters and place them in the character array. int index = 0; for (byte B: byteArray) {resultCharArray [index ++] = hexDigits [B >>> 4 & 0xf]; resultCharArray [index ++] = hexDigits [B & 0xf];} // returns return new String (resultCharArray) by combining character arrays into strings. From the code above, we can see that the MD5 Algorithm for strings using MessageDigest is to convert strings into byte arrays first, the MD5 Algorithm returns a byte array. We need to convert it into a 32-Bit String. 2. MD5 of a file can also be the same as MD5 of a string. First, convert the file to a byte array, which is exactly the same as MD5 of a string. However, if it is a very large file and all the arrays of a file are read into the memory, it is estimated that the memory will not be enough. For large files, you can use DigestInputStream. [Java] public static String fileMD5 (String inputFile) throws IOException {// buffer size (this can be extracted as a parameter) int bufferSize = 256*1024; FileInputStream fileInputStream = null; digestInputStream digestInputStream = null; try {// get an MD5 converter (likewise, you can change it to SHA1) MessageDigest messageDigest = MessageDigest. getInstance ("MD5"); // use DigestInputStream fileInputStream = new FileInputStream (inputFile); digestInputStream = New DigestInputStream (fileInputStream, messageDigest); // MD5 processing is performed during the read process until the file byte [] buffer = new byte [bufferSize] is read; while (digestInputStream. read (buffer)> 0); // obtain the final MessageDigest messageDigest = digestInputStream. getMessageDigest (); // get the result, which is also a byte array containing 16 elements, byte [] resultByteArray = messageDigest. digest (); // Similarly, convert the byte array to the string return byteArrayToHex (resultByteArray);} catch (NoSuchAlgorithmException E) {return null;} finally {try {digestInputStream. close () ;}catch (Exception e) {}try {fileInputStream. close () ;}catch (Exception e) {}} main method of MD5 test file [java] 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 end Time = System. currentTimeMillis (); System. out. println (endTime-startTime)/1000);} The most common user, the user name and password MD5 we know, programming data transmission, save, in order to consider security issues, data needs to be encrypted. let's take the database as an example. if the database of a user registration system does not save the user information, for example, when I register the database on the page, enter "Vicky", "123456 ". registration. if the web server does not encrypt the data and directly writes it to the database, the user information in the database is a directly available data! Once the server is hacked ~ Then the user's information will be unretained in front of hackers... to solve this problem, most of the information is now encrypted using MD5. for example, after "Vicky" and "123456" are encrypted, a 16-bit or 32-Bit String is generated. hackers cannot even use the data... [java] @ Test public void testMD () {try {String username = "Vicky"; MessageDigest messageDigest = MessageDigest. getInstance ("MD5"); messageDigest. update (username. getBytes (); String usernameMD5 = messageDigest. digest (). toString (); System. out. println (usernameMD5);} catch (Exception e) {e. prin TStackTrace () ;}} prints [B @ 107077e, because the output is byte [] (messageDigest. digest () is a binary byte array. Some bytes may be non-printable characters .)... We can use Base64 to process byte []. MessageDigest not only provides "MD5" encryption for us, but also provides four different encryption methods, such as "SHA-1. The method is only MessageDigest messageDigest = MessageDigest. getInstance ("SHA-1"); the difference between MD5 and SHA-1 is: MD5 is 16 bits, SHA is 20 bits (this is the algorithm of the two message digest algorithms) [java] public static void main (String [] args) throws Exception {String Str = "H the city of Taizhou, Zhejiang Province"; getFeatureSHAbyte (Str );} public static byte [] getFeatureSHAbyte (String key) throws Exception {// hashType = "SHA1"; // hashType = "SHA-256"; // hashType = "SHA-384 "; // hashType = "SHA-512"; MessageDigest messageDigest = MessageDigest. getInstance ("SHA-512"); messageDigest. update (key. getBytes (); byte [] B = key. getBytes (); System. out. print ("original binary:"); for (int I: B) {System. out. print (I + ",");} System. out. println (Base64.encode (messageDigest. digest (); return B;} Of course, we can write a function to process binary to hex strings. [java]/*** converts a 16-bit byte [] to a 32-Bit String ** @ param buffer * @ return */private String toHex (byte buffer []) {StringBuffer sb = new StringBuffer (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 ();}

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.