MD5散列不同的值

时间:2015-04-18 12:25:19

标签: java php hash md5

在将数据从应用程序发送到服务器之前,我使用MD5哈希。

Java代码:

    String hash = "";
    String name = nameText.getText();
    try{
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update((name + score + HASH_SALT).getBytes());
        byte byteData[] = md.digest();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
        hash = sb.toString();
    } catch (Exception e) {
        hash = "";
    }


    try {
        String urlParameters = PARAM_NAME + name + PARAM_SCORE + score + PARAM_HASH + hash;
        URL url = new URL(HIGHSCORES_ADD + urlParameters);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.getInputStream();
        urlConnection.disconnect();
    } catch (Exception e){
        Gdx.app.log( "HighScores", "Could not submit score" + e.getMessage());
    } finally {
        ((Game)Gdx.app.getApplicationListener()).setScreen(new MainMenu());
    }

PHP代码:

<?php
         $db = mysql_connect("host", "root", "password") or die('Could not connect: ' . mysql_error());
         mysql_select_db("db1") or die('Could not select database');

         $score = (int)$_GET['score'];
         $hash = $_GET['hash'];
         $name = mysql_real_escape_string($_GET['name'], $db);
         $timestamp = date("Y-m-d H:i:s");
         $secretKey="mySecretKey";

         $real_hash = md5($score . $hash . $secretKey);

         if($real_hash == $hash) {
             $query = "INSERT INTO highscores (id, date, score, name) VALUES (NULL, '$timestamp', '$score', '$name')";
             $result = mysql_query($query) or die('Query failed: ' . mysql_error());
         }
    ?>

在PHP代码$hash$real_hash值不同,但两个文件中的数据相同。什么可以导致这种差异?我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

md.update((name + score + HASH_SALT).getBytes());

md.update()中的字符串与php代码中的md5()中的字符串不同,因此您无法获得相同的哈希值。

$real_hash = md5($score . $hash . $secretKey);