【问题标题】:What will be the Android/Java equivalent of MD5 function in PHP?PHP 中 MD5 函数的 Android/Java 等效项是什么?
【发布时间】:2011-03-31 01:43:00
【问题描述】:

我在 Android/Java 中计算 MD5 如下:

byte raw[] = md.digest();   
StringBuffer hexString = new StringBuffer();
for (int i=0; i<raw.length; i++)
    hexString.append(Integer.toHexString(0xFF & raw[i]));
v_password = hexString.toString();

但是与 PHP 的 md5() 函数不匹配。

MD5 - PHP - 原始值 - catch12 - 214423105677f2375487b4c6880c12ae MD5 - JAVA - 原始值 - catch12 - 214423105677f2375487b4c688c12ae

这是如何引起的,我该如何解决,以便 Android/Java 和 PHP 生成完全相同的 MD5 哈希?

【问题讨论】:

    标签: java php md5


    【解决方案1】:

    当字节小于0x10 时,您需要在十六进制值前面加上0。这是一个完整的例子:

    public static String md5(String string) {
        byte[] hash;
    
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
    
        StringBuilder hex = new StringBuilder(hash.length * 2);
    
        for (byte b : hash) {
            int i = (b & 0xFF);
            if (i < 0x10) hex.append('0');
            hex.append(Integer.toHexString(i));
        }
    
        return hex.toString();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 2014-06-15
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      相关资源
      最近更新 更多