繁体   English   中英

如何在Java中基于此方法在python的HmacSHA1算法上生成哈希?

[英]How to generate Hash on HmacSHA1 algorithm in python based on this method in Java?

我尝试在Python中实现此Java方法,但是用纯Python重写它似乎很难。

public static String CalculateHash(String input, String token) {
    SecretKeySpec signingKey = new SecretKeySpec(token.getBytes(), "HmacSHA1");

    Mac mac = null;
    mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);

    assert mac != null;


    byte[] bytes = mac.doFinal(input.getBytes(Charset.forName("UTF-8")));
    String form = "";

    for (byte aByte : bytes) {
        String str = Integer.toHexString(((int) aByte) & 0xff);
        if (str.length() == 1) {
            str = "0" + str;
        }
        form = form + str;
    }

    return form;
}

我尝试了这个,但是它会生成其他哈希。

def sign_request():
    from hashlib import sha1
    import hmac

    # key = CONSUMER_SECRET& #If you dont have a token yet
    key = "CONSUMER_SECRET&TOKEN_SECRET"


    # The Base String as specified here:
    raw = "BASE_STRING" # as specified by oauth

    hashed = hmac.new(key, raw, sha1)

    # The signature
    return hashed.digest().encode("base64").rstrip('\n')

我应该在标准的Python库中使用什么以及如何使用它来重写它? 谢谢

您的python代码和java代码不匹配,因为python代码使用base 64,而java代码使用十六进制(base 16)。

您应该将phyton代码更改为使用base16作为其输出,这可以通过hex()函数来完成,注意正确地用Java代码执行的正确数字0填充数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM