How to hash a string in Android? How to hash a string in Android? java java

How to hash a string in Android?


This snippet calculate md5 for any given string

public 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 "";}

Source: http://www.androidsnippets.com/snippets/52/index.html

Hope this is useful for you


That function above from (http://www.androidsnippets.org/snippets/52/index.html) is flawed. If one of the digits in the messageDigest is not a two character hex value (i.e. 0x09), it doesn't work properly because it doesn't pad with a 0. If you search around you'll find that function and complaints about it not working. Here a better one found in the comment section of this page, which I slightly modified:

public static String md5(String s) {    MessageDigest digest;    try    {        digest = MessageDigest.getInstance("MD5");        digest.update(s.getBytes(Charset.forName("US-ASCII")),0,s.length());        byte[] magnitude = digest.digest();        BigInteger bi = new BigInteger(1, magnitude);        String hash = String.format("%0" + (magnitude.length << 1) + "x", bi);        return hash;    }    catch (NoSuchAlgorithmException e)    {        e.printStackTrace();    }    return "";}


not working method:

public 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 "";}

result: 1865e62e7129927f6e4cd9bff104f0 (length 30)

working method:

public static final String md5(final String toEncrypt) {    try {        final MessageDigest digest = MessageDigest.getInstance("md5");        digest.update(toEncrypt.getBytes());        final byte[] bytes = digest.digest();        final StringBuilder sb = new StringBuilder();        for (int i = 0; i < bytes.length; i++) {            sb.append(String.format("%02X", bytes[i]));        }        return sb.toString().toLowerCase();    } catch (Exception exc) {        return ""; // Impossibru!    }}

result: 1865e62e7129927f6e4c0d9bff1004f0 (length 32)