Q:

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

I try to implement this Java method in Python, but it seems to hard to rewrite it in pure 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;
}

I tried this one, but it generates other hash.
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')

What and how should I use in standart Python library to rewrite it? Thank you

A:

Your python code and java code don't match in the fact that the python code uses base 64, while the java code uses hexadecimal (base 16).
You should change the phyton code to use base16 for its output, this can be done with the hex() function, caring to correctly pad the number with the correct numbers of 0 characters the java code does.

