简体   繁体   中英

Function returns wrong result but good result in the debugger with same string parameters

I've seen many things in my life but that's seems unbelievable for me. Actually I'm newbie in java.

I'm trying to set up oauth communication.

For this I need to sign each request. I use the following function for this:

private String computeHmac(String baseString, String key)
{
    Mac mac = null;
    try
    {
        mac = Mac.getInstance("HmacSHA1");
    }
    catch(NoSuchAlgorithmException ex) { } 
    SecretKeySpec secret = null;
    secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());

    try
    {
        mac.init(secret);
    }
    catch (InvalidKeyException ex)
    { 
        Log.e(Constants.LOG_TAG, "Invalid key: " + ex.getMessage());
    }
    mac.update(baseString.getBytes());
    byte[] digest = mac.doFinal();
    return Base64.encodeBytes(digest).trim();
}

The function above is wrapped into a custom class which I use for oauth related operations.

For oauth we must make two roundtrips before we can communicate with the target api.

First time the signature is generated correctly.

Second time the generated signature proved always wrong, therefore I started debugging. The function has two input parameters. I created two lines in the eclipse expression window. One with the function call and string variables, and a second one with the same function call and the exact string values which I copied out from the variable value.

The first expression's value was the same as before the incorrect signature.

Surprise: the second expression's value reflected the correct signature.

WTF???

Is there any special factor in java I'm unaware? Special string handling or anything?

It was an invisible character probably \\n at the end of string. It's worth to check this if someone encounters the same issue. I lost almost a day for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM