Jorsher Jorsher - 7 months ago 57
Android Question

How to hash a string in Android?

I am working on an Android app and have a couple strings that I would like to encrypt before sending to a database. I'd like something that's secure, easy to implement, will generate the same thing every time it's passed the same data, and preferably will result in a string that stays a constant length no matter how large the string being passed to it is. Maybe I'm looking for a hash.


This snippet calculate md5 for any given string

public String md5(String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest ="MD5");
        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) {
    return "";


Hope this is useful for you