如何在 Java 中生成相当于 Python 示例的 HMAC?

2023-12-30

我正在考虑实现一个应用程序Twitter 通过 Oauth 授权 http://apiwiki.twitter.com/Authentication在爪哇。第一步是获取请求令牌 http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-oauth-request_token。这里有一个Python示例 http://github.com/tav/tweetapp/blob/master/standalone/twitter_oauth_handler.py对于应用程序引擎。

为了测试我的代码,我运行 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]

Output:

$ ./foo.py
+3h2gpjf4xcynjCGU5lbdMBwGOc=

如何用 Java 复制这个示例?

我见过一个HMAC 示例 http://exampledepot.8waytrips.com/egs/javax.crypto/GenMac.html在爪哇中:

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) {
}

It uses javax.crypto.Mac http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/crypto/Mac.html, 都好。但是,那密钥 http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/crypto/SecretKey.html构造函数需要字节和算法。

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 的东西。Commons Codec 中的 base64 编码器 http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html例如,将是一个更好的选择。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Java 中生成相当于 Python 示例的 HMAC? 的相关文章

随机推荐