MD5 hashing in Android

前端 未结 16 2028
醉梦人生
醉梦人生 2020-11-29 18:06

I have a simple android client which needs to \'talk\' to a simple C# HTTP listener. I want to provide a basic level of authentication by passing username/password in POST r

16条回答
  •  被撕碎了的回忆
    2020-11-29 18:47

    This is a slight variation of Andranik and Den Delimarsky answers above, but its a bit more concise and doesn't require any bitwise logic. Instead it uses the built-in String.format method to convert the bytes to two character hexadecimal strings (doesn't strip 0's). Normally I would just comment on their answers, but I don't have the reputation to do so.

    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
    
            StringBuilder hexString = new StringBuilder();
            for (byte digestByte : md.digest(input.getBytes()))
                hexString.append(String.format("%02X", digestByte));
    
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    If you'd like to return a lower case string instead, then just change %02X to %02x.

    Edit: Using BigInteger like with wzbozon's answer, you can make the answer even more concise:

    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            BigInteger md5Data = new BigInteger(1, md.digest(input.getBytes()));
            return String.Format("%032X", md5Data);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    

提交回复
热议问题