时间戳变量在1行代码后发生变化

时间:2015-02-13 20:03:09

标签: java android hash md5

我正在尝试创建一个动态md5哈希系统,用于对Marvel API进行身份验证。

我创建一个时间戳变量,添加私钥/公钥,然后尝试将其转换为md5哈希。当我打印出结果时,url中的时间戳和要散列的字符串中的时间戳变得不同。

//I declare the timestamp here
    Long tsLong = System.currentTimeMillis()/1000;
    final String ts = tsLong.toString();

//Create the string to be hashed
    final String toHash = ts + privateKey + publicKey;

    url = "" + publicKey;

    String hash = new String();
//my hashing algorithm
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashe = md.digest(toHash.getBytes("UTF-8"));
        StringBuffer hex = new StringBuffer(2*hashe.length);
        for (byte b : hashe) {
            hex.append(String.format("%02x", b&0xff));
        }
        hash = hex.toString();
    }
    catch(NoSuchAlgorithmException e) {

    }
    catch(UnsupportedEncodingException e) {

    }
//append the url to include the hash
    url += "&hash=";
    url += hash;

//call the api
    RequestQueue queue = VolleySingleton.getInstance().getRequestQueue();

    JsonObjectRequest obj = new JsonObjectRequest
            (Request.Method.GET,
                    url,
                    null,
                    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            parseJSONResponse(response);
            for (int i = 0; i < eventArray.size(); i++) {
                mTV.append("Id: " + String.valueOf(eventArray.get(i).id) + '\n' +
                        "Title: " + eventArray.get(i).title + '\n' +
                        "Description: " + eventArray.get(i).description + '\n');
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
//i get an authentication error so here is the log code
            Log.i("tag", url);
            Log.i("tag", toHash);

        }
    });

    queue.add(obj);

这是logcat输出

02-13 15:00:10.036    5681-5681/kim.albert.marveleventtracker I/tag﹕ http://gateway.marvel.com/v1/public/events?limit=66&ts=1423538706&apikey=fc57c9d09a46a0bdb06bd811ec4fc078&hash=0a670ef8de3c08d7c3d9dd1bc20aee75
02-13 15:00:10.036    5681-5681/kim.albert.marveleventtracker I/tag﹕ 1423857609172469841247e9a7aa64c3c89771a81299a67ef4fc57c9d09a46a0bdb06bd811ec4fc078

您可以看到:url ts和toHash具有不同的值。这是为什么?

1 个答案:

答案 0 :(得分:0)

我是个傻瓜。我很难将ts编码到我的网址中,而不是通过添加生成的ts来更新它。