简体   繁体   English

函数返回错误的结果,但在调试器中使用相同的字符串参数返回良好的结果

[英]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. 其实我是Java的新手。

I'm trying to set up oauth communication. 我正在尝试建立oauth通信。

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. 上面的函数被包装到一个自定义类中,该类用于与oauth相关的操作。

For oauth we must make two roundtrips before we can communicate with the target api. 对于oauth,我们必须进行两次往返,才能与目标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. 我在Eclipse表达式窗口中创建了两行。 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??? WTF ???

Is there any special factor in java I'm unaware? 我不知道Java中有什么特殊因素吗? Special string handling or anything? 特殊的字符串处理还是什么?

It was an invisible character probably \\n at the end of string. 它是一个不可见的字符,可能在字符串末尾\\ n。 It's worth to check this if someone encounters the same issue. 如果有人遇到相同的问题,值得检查一下。 I lost almost a day for this. 我为此损失了将近一天的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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