我正在考虑在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秘密密钥?
"string".getBytes()
看起来相当奇怪。它会返回平台相关的字节(需要指定编码!)并且不会涵盖整个字节值范围。我建议使用编码(如base64、base32或hexdigest)来表示密钥的字符串,或者使用密码强化(PBKDF)来返回纯净的分布良好的字节。(当然,这也是规范/Python示例的问题)。 - eckesgetBytes(“UTF-8”)
。正如您所说,Python示例中的字符串没有以u“....”
开头,我们不知道它是否为Python 3。 - BrunoString java.xml.bind.DatatypeConverter.printBase64Binary(byte[] val)
进行编码。 - Scruffy