Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Help understanding this code

  1. #1
    Junior Member
    Join Date
    Apr 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help understanding this code

    public static String MD5(Object obj) throws java.security.NoSuchAlgorithmException {
    		String buffer = obj.toString();
    		java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
    		digest.update(buffer.getBytes());
    		byte[] b = digest.digest();		
    		buffer = "";
     
    		for (int i=0; i < b.length; i++) {
    			buffer += Integer.toString((b[i] & 0xff ) + 0x100, 16).substring(1);
    		}
     
    		return buffer;
    	}

    Hi,

    I found this piece of code on the net while i was curious about md5 encryption. I tried to figure some things out but since I'm new, I'm not too sure why.

    1. Why must I do digest.update? I tried looking in the documentation, but I couldn't get it.

    update

    public void update(byte[] input,
    int offset,
    int len)

    Updates the digest using the specified array of bytes, starting at the specified offset.

    Parameters:
    input - the array of bytes.
    offset - the offset to start from in the array of bytes.
    len - the number of bytes to use, starting at offset.
    2. What does the offset do?


    for (int i=0; i < b.length; i++) {
    			buffer += Integer.toString((b[i] & 0xff ) + 0x100, 16).substring(1);
    		}
    3. I do not get it why must this line be done.



    I found out that I could actually do the below md5 hashing, but it truncates the 0 infront.

    import java.security.*;
    import java.math.*;
     
    public class MD5 {
    	public static void main(String args[]) throws Exception{
    	    String s="This is a test";
                MessageDigest m=MessageDigest.getInstance("MD5");
                m.update(s.getBytes(),0,s.length());
                System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
            }
     }


    For both type of md5 hashing, I used the string, "f78spx"

    Regards,
    Zepx


  2. #2
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Help understanding this code

    This is my current version of a HashUtility class.

    import java.io.UnsupportedEncodingException;
    import java.math.BigInteger;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
     
    /**
     * HashUtility.
     *
     * @author Daniel
     * @since 17 Sep 2009
     */
    public class HashUtility {
     
        private static final Logger LOGGER = LoggerFactory.getLogger(HashUtility.class);
     
        protected HashUtility() {
            throw new UnsupportedOperationException();
        }
     
        public static String sha1(final String input) {
            return hash("SHA1", input);
        }
     
        public static String sha512(final String input) {
            return hash("SHA-512", input);
        }
     
        public static String md5(final String input) {
            String result = hash("MD5", input);
     
            if (result.length() == 31) {
                result = "0".concat(result);
            }
     
            return result;
        }
     
        /**
         * Hashes the input string as MD5. If exception is thrown this will return the input string.
         *
         * @param input the input string to be hashed
         * @return the md5 hashed input string
         */
        public static String hash(final String algorithm, final String input) {
            try {
                final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
                messageDigest.update(input.getBytes("UTF-8"), 0, input.length());
     
                return new BigInteger(1, messageDigest.digest()).toString(16);
            } catch (NoSuchAlgorithmException algorithmException) {
                LOGGER.error("NoSuchAlgorithmException caught while trying to create message digest");
            } catch (UnsupportedEncodingException e) {
                LOGGER.error("UnsupportedEncodingException caugth while trying to get input string as byte array in [UTF-8] format");
            }
     
            return input;
        }
    }

    Just replace all the LOGGER calls with sysout or whatever you're using. For more information regarding the MessageDigest have a look at MessageDigest (Java Platform SE 6)

    // Json

  3. #3
    Junior Member
    Join Date
    Apr 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help understanding this code

    Hi,

    Thanks for the reply. I understand that the other method is to manually add back the 0's from your HashUtility class. However, I'm more keen to understand why the above code, that is, by using hex. I would prefer to understand why.

    I kindly hope that someone else could explain to me the few questions that I've asked.

    Regards,
    Zepx