如何在Java中生成等效于Python示例的HMAC?

dfrankow:

我正在寻找实现Java中通过Oauth获得Twitter授权的应用程序第一步是获取请求令牌这是应用引擎Python示例

为了测试我的代码,我正在运行Python并使用Java检查输出。这是Python生成基于哈希的消息认证代码(HMAC)的示例:

#!/usr/bin/python

from hashlib import sha1
from hmac import new as hmac

key = "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50"
message = "foo"

print "%s" % hmac(key, message, sha1).digest().encode('base64')[:-1]

输出:

$ ./foo.py
+3h2gpjf4xcynjCGU5lbdMBwGOc=

如何用Java复制此示例?

我看过Java 中HMAC示例

try {
    // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104
    // In practice, you would save this key.
    KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
    SecretKey key = keyGen.generateKey();

    // Create a MAC object using HMAC-MD5 and initialize with key
    Mac mac = Mac.getInstance(key.getAlgorithm());
    mac.init(key);

    String str = "This message will be digested";

    // Encode the string into bytes using utf-8 and digest it
    byte[] utf8 = str.getBytes("UTF8");
    byte[] digest = mac.doFinal(utf8);

    // If desired, convert the digest into a string
    String digestB64 = new sun.misc.BASE64Encoder().encode(digest);
} catch (InvalidKeyException e) {
} catch (NoSuchAlgorithmException e) {
} catch (UnsupportedEncodingException e) {
}

它使用javax.crypto.Mac,一切都很好。但是,SecretKey构造函数采用字节和算法。

Python示例中的算法是什么?没有算法怎么能创建Java密钥?

布鲁诺 :

HmacSHA1似乎是您需要的算法名称:

SecretKeySpec keySpec = new SecretKeySpec(
        "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50".getBytes(),
        "HmacSHA1");

Mac mac = Mac.getInstance("HmacSHA1");
mac.init(keySpec);
byte[] result = mac.doFinal("foo".getBytes());

BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(result));

产生:

+3h2gpjf4xcynjCGU5lbdMBwGOc=

请注意,这里我已经使用sun.misc.BASE64Encoder了快速实现,但是您可能应该使用不依赖于Sun JRE的东西。例如,Common Codec中的base64-encoder将是一个更好的选择。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章