MD5 hashing in Android

前端 未结 16 1996
醉梦人生
醉梦人生 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:54

    A solution above using DigestUtils didn't work for me. In my version of Apache commons (the latest one for 2013) there is no such class.

    I found another solution here in one blog. It works perfect and doesn't need Apache commons. It looks a little shorter than the code in accepted answer above.

    public static String getMd5Hash(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String md5 = number.toString(16);
    
            while (md5.length() < 32)
                md5 = "0" + md5;
    
            return md5;
        } catch (NoSuchAlgorithmException e) {
            Log.e("MD5", e.getLocalizedMessage());
            return null;
        }
    }
    

    You will need these imports:

    import java.math.BigInteger;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    

提交回复
热议问题