【问题标题】:MD5 returns different values for the same inputMD5 为相同的输入返回不同的值
【发布时间】:2014-08-28 06:53:42
【问题描述】:

我在 Android 上,所以它只是 java,我有相同的输入字符串,但每次都得到不同的值。我错过了什么?谢谢

private String getShortenedKey(String key) {
        String shortenedKey=null;
        MessageDigest md = null;
        LogUtils.LOGD(HASH_ALGO, "before key: "+ System.currentTimeMillis());
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            shortenedKey = key;
        }
        LogUtils.LOGD(HASH_ALGO, "after key: "+ System.currentTimeMillis());

        md.update(key.getBytes());
        byte[] shortenedBytes = md.digest();
        shortenedKey = String.valueOf(shortenedBytes);
        return shortenedKey;
    }

输入字符串:

{"config":{"wp":"(1.000000,1.000000,1.000000,1.000000)","v":"8","unit":"auto","ef":true,"ws":1,"tt":0,"cs":1},"items":[{"startTime":1409180400,"id":"WorkXYZ@habit.skedgo.com_1409180400","class":"event","endTime":1409209200,"location":{"lng":151.20785,"lat":-33.85926},"priority":0},{"startTime":1409148000,"id":"HomeXYZ@habit.skedgo.com_1409148000","class":"event","endTime":1409234340,"location":{"lng":151.18089,"lat":-33.89153},"priority":0}]}

更新:这么多有效的答案,谢谢。我选择最容易改变的那个。干杯。

【问题讨论】:

    标签: java android md5


    【解决方案1】:

    这一行

    shortenedKey = String.valueOf(shortenedBytes);
    

    没有按照你的想法做。

    为了获得数组中字节值的字符串表示,您需要实现一个小实用方法。

    此外,如果对MessageDigest.getInstance("MD5"); 的调用抛出了NoSuchAlgorithmException,您的程序稍后将在md.update(key.getBytes());NullPointerException 一起崩溃。

    【讨论】:

    • 谢谢,我已经追踪了NoSuchAlgorithmException,如果发生这种情况,请使用原始密钥。
    【解决方案2】:

    @Henry 在他的回答中解释了这个问题,String.valueOf(shortenedBytes) 必须更改。

    替换这个;

    shortenedKey = String.valueOf(shortenedBytes);
    

    到这个;

    shortenedKey = new String(Base64.encode(shortenedBytes))
    

    你可以使用Bouncycastle的Base64

    Download the jar

    【讨论】:

      【解决方案3】:

      检查修改后的版本。 您可以对字节使用 base64 编码

      private String getShortenedKey(String key) {
          String shortenedKey=null;
          MessageDigest md = null;
          LogUtils.LOGD(HASH_ALGO, "before key: "+ System.currentTimeMillis());
          try {
              md = MessageDigest.getInstance("MD5");
      
              md.update(key.getBytes());
              byte[] shortenedBytes = md.digest();
              shortenedKey = Base64.encodeToString(shortenedBytes, Base64.NO_WRAP);
          } catch (NoSuchAlgorithmException e) {
              e.printStackTrace();
              shortenedKey = key;
          }
          LogUtils.LOGD(HASH_ALGO, "after key: "+ System.currentTimeMillis());
      
          return shortenedKey;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多