MD5 hashing in Android

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

    Far too wasteful toHex() conversion prevails in other suggestions, really.

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    
    public static String md5string(String s) {
        return toHex(md5plain(s));
    }
    
    public static byte[] md5plain(String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance(MD5);
            digest.update(s.getBytes());
            return digest.digest();
        } catch (NoSuchAlgorithmException e) {
            // never happens
            e.printStackTrace();
            return null;
        }
    }
    
    public static String toHex(byte[] buf) {
        char[] hexChars = new char[buf.length * 2];
        int v;
        for (int i = 0; i < buf.length; i++) {
            v = buf[i] & 0xFF;
            hexChars[i * 2] = HEX_ARRAY[v >>> 4];
            hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
    
    0 讨论(0)
  • 2020-11-29 18:52

    In our MVC application we generate for long param

    using System.Security.Cryptography;
    using System.Text;
        ...
        public static string getMD5(long id)
        {
            // convert
            string result = (id ^ long.MaxValue).ToString("X") + "-ANY-TEXT";
            using (MD5 md5Hash = MD5.Create())
            {
                // Convert the input string to a byte array and compute the hash. 
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(result));
    
                // Create a new Stringbuilder to collect the bytes and create a string.
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                    sBuilder.Append(data[i].ToString("x2"));
    
                // Return the hexadecimal string. 
                result = sBuilder.ToString().ToUpper();
            }
    
            return result;
        }
    

    and same in Android application (thenk helps Andranik)

    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    ...
    public String getIdHash(long id){
        String hash = null;
        long intId = id ^ Long.MAX_VALUE;
        String md5 = String.format("%X-ANY-TEXT", intId);
        try {
            MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] arr = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < arr.length; ++i)
                sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,3));
    
            hash = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            Log.e("MD5", e.getMessage());
        }
    
        return hash.toUpperCase();
    }
    
    0 讨论(0)
  • 2020-11-29 18:52

    MD5 is a bit old, SHA-1 is a better algorithm, there is a example here.

    (Also as they note in that post, Java handles this on it's own, no Android specific code.)

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-29 18:57

    The androidsnippets.com code does not work reliably because 0's seem to be cut out of the resulting hash.

    A better implementation is here.

    public static String MD5_Hash(String s) {
        MessageDigest m = null;
    
        try {
                m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
        }
    
        m.update(s.getBytes(),0,s.length());
        String hash = new BigInteger(1, m.digest()).toString(16);
        return hash;
    }
    
    0 讨论(0)
  • 2020-11-29 18:59

    Useful Kotlin Extension Function Example

    fun String.toMD5(): String {
        val bytes = MessageDigest.getInstance("MD5").digest(this.toByteArray())
        return bytes.toHex()
    }
    
    fun ByteArray.toHex(): String {
        return joinToString("") { "%02x".format(it) }
    }
    
    0 讨论(0)
提交回复
热议问题