如何用Java生成等价于Python示例的HMAC?
我正在考虑通过 Java中的Oauth实现一个获得Twitter授权的应用程序。 第一步是获取请求令牌 。 以下是应用程序引擎的Python示例 。
为了testing我的代码,我正在运行Python并使用Java检查输出。 以下是生成基于哈希的消息authentication码(HMAC)的Python示例:
#!/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.ge