Friday, February 10, 2012

How to Create a MD5-Hash and Dump as a Hex String in android?

It's quite easy to create an md5 hash and dump it as hex-string with the java.security package. This function 'public String md5(String s)' does the job for you :-)

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

No comments:

Post a Comment