我正在考虑实现一个应用程序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 密钥?