Monday, October 3, 2011

How to Create MD5 Hashed Code in Android

Dear Blog Viewer,

What is the MD5 hash?
The MD5 hash also known as checksum for a file is a 128-bit value, something like a fingerprint of the file. There is a very small possibility of getting two identical hashes of two different files. This feature can be useful both for comparing the files and their integrity control.
Let us imagine a situation that will help to understand how the MD5 hash works.
Alice and Bob have two similar huge files. How do we know that they are different without sending them to each other? We simply have to calculate the MD5 hashes of these files and compare them.
MD5 Hash Properties
The MD5 hash consists of a small amount of binary data, typically no more than 128 bits. All hash values share the following properties:
Hash length
The length of the hash value is determined by the type of the used algorithm, and its length does not depend on the size of the file. The most common hash value lengths are either 128 or 160 bits.
Every pair of nonidentical files will translate into a completely different hash value, even if the two files differ only by a single bit. Using today's technology, it is not possible to discover a pair of files that translate to the same hash value.
Each time a particular file is hashed using the same algorithm, the exact same hash value will be produced.
All hashing algorithms are one-way. Given a checksum value, it is infeasible to discover the password. In fact, none of the properties of the original message can be determined given the checksum value alone.
The algorithm was invented by:
Professor Ronald L. Rivest (born 1947, Schenectady, New York) is a cryptographer, and is the Viterbi Professor of Computer Science at MIT's Department of Electrical Engineering and Computer Science. He is most celebrated for his work on public-key encryption with Len Adleman and Adi Shamir, specifically the RSA algorithm, for which they won the 2002 ACM Turing Award.
Simple Code for Android:

public static final String md5Digest(final String text)
           // Create MD5 Hash
           MessageDigest digest ="MD5");
           byte messageDigest[] = digest.digest();

           // Create Hex String
           StringBuffer hexString = new StringBuffer();
           int messageDigestLenght = messageDigest.length;
           for (int i = 0; i < messageDigestLenght; i++)
                String hashedData = Integer.toHexString(0xFF & messageDigest[i]);
                while (hashedData.length() < 2)
                     hashedData = "0" + hashedData;
           return hexString.toString();

     } catch (NoSuchAlgorithmException e)
     return ""; // if text is null then return nothing

No comments: