如何在Java中基于此方法在python中为HmacSHA1算法生成Hash?
问题描述:
我尝试在Python中实现这个Java方法,但似乎很难用纯Python重写它。如何在Java中基于此方法在python中为HmacSHA1算法生成Hash?
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')
什么和如何在standart Python库中使用它来重写它?谢谢
答
你的python代码和java代码不匹配,因为python代码使用base 64,而java代码使用十六进制(base 16)。
您应该更改phyton代码以使用base16作为其输出,这可以使用hex()
函数完成,关心如何正确填充数字以及java代码的0个字符。
你用python把它们做到base64,用java生成十六进制(base16) – Ferrybig
它帮助了我,谢谢! –