2016-01-22 29 views
1

我嘗試在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庫中使用它來重寫它?謝謝

+1

你用python把它們做到base64,用java生成十六進制(base16) – Ferrybig

+0

它幫助了我,謝謝! –

回答

1

你的python代碼和java代碼不匹配,因爲python代碼使用base 64,而java代碼使用十六進制(base 16)。

您應該更改phyton代碼以使用base16作爲其輸出,這可以使用hex()函數完成,關心如何正確填充數字以及java代碼的0個字符。