Blog Archive

Android generate md5 hash example

The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. Specified in RFC 1321, MD5 has been employed in a wide variety of security applications, and is also commonly used to check data integrity. However, it has been shown that MD5 is not collision resistant; as such, MD5 is not suitable for applications like SSL certificates or digital signatures that rely on this property. An MD5 hash is typically expressed as a 32-digit hexadecimal number.
package com.as400samplecode;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Hash {

    public static void main(String[] args) {
       
        String s = "SecretKey20111013000";
        String  res = md5(s);
        System.out.println(res);

    }

    private static String md5(String s) { try { 
       
        // Create MD5 Hash 
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); 
        digest.update(s.getBytes()); 
        byte messageDigest[] = digest.digest();

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

     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
     }
     return "";

    }
   
   
}

8 comments :

  1. Not giving exact answer.

    String = 123
    in mysql = 202cb962ac59075b964b07152d234b70
    in function = 202cb962ac5975b964b7152d234b70

    ReplyDelete
  2. I spent over a night to find out the mistake

    ReplyDelete
  3. Thanks for your code, it helps me a lot :)
    I solved the bug (in 5-10 min), like this:

    str = String.format("%02X", (0xFF & messageDigest[ i ]));
    sb.append( str );

    You can also add an enumeration of algorithms like "SHA256", "SHA1", "MD5", it works :)

    Rem: I also adapted the SHA1 examples of Wikipedia which were wrong lol ^^

    ReplyDelete
    Replies
    1. hey can u help me in my android project?
      I wanna insert the encrypted text in the image. Now i dont know how to encrypt the text and embed it in image. Help me

      Delete
  4. Quien me ayuda he tratado de hacerle hacerlo el md5 de imei invertido para lograr conseguir el código pero no tengo éxito.

    ReplyDelete
  5. Quien me ayuda he tratado de hacerle hacerlo el md5 de imei invertido para lograr conseguir el código pero no tengo éxito.

    ReplyDelete
  6. thanks.. nice post

    ReplyDelete