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

dfr*_*kow 50 java sha1 oauth cryptoapi hmac

我正在寻找通过 Java中的Oauth实现一个获得Twitter授权的应用程序.第一步是获取请求令牌.这是app引擎的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]
Run Code Online (Sandbox Code Playgroud)

输出:

$ ./foo.py
+3h2gpjf4xcynjCGU5lbdMBwGOc=
Run Code Online (Sandbox Code Playgroud)

如何在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) {
}
Run Code Online (Sandbox Code Playgroud)

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

Python示例中的算法是什么?如何在没有算法的情况下创建Java密钥?

Bru*_*uno 68

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));
Run Code Online (Sandbox Code Playgroud)

生产:

+3h2gpjf4xcynjCGU5lbdMBwGOc=
Run Code Online (Sandbox Code Playgroud)

请注意,我在sun.misc.BASE64Encoder这里用于快速实现,但您应该使用不依赖于Sun JRE的东西.例如,Commons Codec中的base64编码器将是更好的选择.

  • `"string".getBytes()`看起来很奇怪.它将返回平台dependend字节(指定编码!),它不会覆盖整个字节值范围.我希望使用编码(如bae64,base32或hexdigest)作为密钥的字符串表示,或者使用密码强化(PBKDF)来返回纯粹的分布式字节.(但当然这也是spec/python样本的问题). (2认同)

小智 21

一个小问题,但如果你正在寻找等效的hmac(键,消息),那么默认情况下python库将使用MD5算法,因此你需要在Java中使用HmacMD5算法.

我之所以提到这个是因为我遇到了这个确切的问题,并且发现这个答案很有帮助,但是我错过了将摘要方法传递给hmac()的部分,从而导致了一个兔子洞.希望这个答案可以防止其他人在将来做同样的事情.

例如在Python REPL中

>>> import hmac
>>> hmac.new("keyValueGoesHere", "secretMessageToHash").hexdigest()
'1a7bb3687962c9e26b2d4c2b833b2bf2'
Run Code Online (Sandbox Code Playgroud)

这相当于Java方法:

import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HashingUtility {
    public static String HMAC_MD5_encode(String key, String message) throws Exception {

        SecretKeySpec keySpec = new SecretKeySpec(
                key.getBytes(),
                "HmacMD5");

        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(keySpec);
        byte[] rawHmac = mac.doFinal(message.getBytes());

        return Hex.encodeHexString(rawHmac);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在我的示例中,我做的相当于.hexdigest()

  • encodeHexString在Android上不起作用,所以我不得不使用它:返回new String(Hex.encodeHex(rawHmac)); (3认同)