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

编程入门 行业动态 更新时间:2024-10-26 04:32:21
本文介绍了如何在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 23:54:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/744729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   如何在   Python   Java   HMAC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!