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

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

问题描述

我正在考虑在Java中实现一个通过Oauth 获得 Twitter授权的应用程序。第一步是获取请求令牌。这是app引擎的 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示例

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中生成HMAC等效于Python示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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