如何在 Java 中生成与 Python 示例等效的 HMAC? [英] How to generate an HMAC in Java equivalent to a Python example?

查看:38
本文介绍了如何在 Java 中生成与 Python 示例等效的 HMAC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在 Java 中实现一个通过 Oauth 获得 Twitter 授权的应用程序.第一步是获取请求令牌.这是应用引擎的 Python 示例.

I'm looking at implementing an app getting Twitter authorization via Oauth in Java. The first step is getting a request token. Here is a Python example for app engine.

为了测试我的代码,我正在运行 Python 并使用 Java 检查输出.以下是 Python 生成基于哈希的消息身份验证代码 (HMAC) 的示例:

To test my code, I am running Python and checking output with Java. Here is an example of Python generating a Hash-Based Message Authentication Code (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 中复制此示例?

How does one replicate this example in Java?

我在 Java 中看到了一个 HMAC 示例:

I've seen an example of HMAC in Java:

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 构造函数接受字节和算法.

It uses javax.crypto.Mac, all good. However, the SecretKey constructors take bytes and an algorithm.

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

What's the algorithm in the Python example? How can one create a Java secret key without an algorithm?

推荐答案

HmacSHA1 似乎是你需要的算法名称:

HmacSHA1 seems to be the algorithm name you need:

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 编码器例如,将是更好的选择.

Note that I've used sun.misc.BASE64Encoder for a quick implementation here, but you should probably use something that doesn't depend on the Sun JRE. The base64-encoder in Commons Codec would be a better choice, for example.

这篇关于如何在 Java 中生成与 Python 示例等效的 HMAC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆