You are here:

Java/code explanation

Advertisement


Question
Hi Artemus,

I have found a piece of code which converts plaintext to md5 hash. 32 bit yet im unsure how it works 'line by line'(just the conversion part). I was hoping if you could help me regarding what each line of code is doing.

I have attempted to make sense of what each line of code is doing by adding comments above it. please correct me if i'm wrong

Thanks

ps. full code for this can be found here at paste bin:http://pastebin.com/rjg8Vc7w


Here's the code i need to interpret:

   public static String encryptMD5(String input) {
       try {
//create a new messageDigest instance
         MessageDigest md = MessageDigest.getInstance("MD5");
//encode the input into sequence of bytes
         byte[] messageDigest = md.digest(input.getBytes());
//store it as a big interger since immutable
         BigInteger number = new BigInteger(1, messageDigest);
//create a hashtext to convert the biginteger to a 16bit string conversion
         String hashtext = number.toString(16);
//zero pad to actually get 32 bits
         while (hashtext.length() < 32) {
         hashtext = "0" + hashtext;
         }
         return hashtext;
       } catch (NoSuchAlgorithmException e) {
         throw new RuntimeException(e);
       }
   }

Answer
First, note that this get an MD5 encode as 16 bytes (32 nibbles, or 128 bits), not 32 bits.
This is correct:
//create a new messageDigest instance
        MessageDigest md = MessageDigest.getInstance("MD5");
//encode the input into sequence of bytes
        byte[] messageDigest = md.digest(input.getBytes());

This line creates a positive BigInteger. This is done since BigInteger has a constructor that takes a byte[], and can store numbers than a long which is only 64 bits:
BigInteger number = new BigInteger(1, messageDigest);

This line converts the number to a hexadecimal String (base 16). This has nothing to do with unicode.
String hashtext = number.toString(16);

Your mostly correct on this next line, except that it pads the nibbles (half the size of a byte), not the bits.
while (hashtext.length() < 32) {
        hashtext = "0" + hashtext;
        }

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.