MD5 hashing in Android

前端 未结 16 1994
醉梦人生
醉梦人生 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 19:03

    The accepted answer didn't work for me in Android 2.2. I don't know why, but it was "eating" some of my zeros (0) . Apache commons also didn't work on Android 2.2, because it uses methods that are supported only starting from Android 2.3.x. Also, if you want to just MD5 a string, Apache commons is too complex for that. Why one should keep a whole library to use just a small function from it...

    Finally I found the following code snippet here which worked perfectly for me. I hope it will be useful for someone...

    public String MD5(String md5) {
       try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
              sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
           }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch(UnsupportedEncodingException ex){
        }
        return null;
    }
    

提交回复
热议问题