Zagorodniy Olexiy
Zagorodniy Olexiy

Reputation: 2212

HMAC-SHA1 in Python3 'bytes' object has no attribute 'encode'

As was described in this answer i've implement HMAC-SHA1 signature method.

def sign_request():
    from hashlib import sha1
    import hmac

    key = b"CONSUMER_SECRET&"  
    basestr = b"BASE_STRING"
    hashed = hmac.new(key, basestr, sha1)
    return hashed.digest().encode("base64").rstrip('\n')

But i've got AttributeError, 'bytes' object has no attribute 'encode'. As i understood, that is why i'm using Python3, but i don't know how to fix it.

Upvotes: 0

Views: 1374

Answers (1)

Osadhi Virochana
Osadhi Virochana

Reputation: 1302

That is because it is a byte and you are trying to encode like string. I fixed it:

from base64 import encodebytes
def sign_request():
    from hashlib import sha1
    import hmac

    key = b"CONSUMER_SECRET&"  
    basestr = b"BASE_STRING"
    hashed = hmac.new(key, basestr, sha1)
    return str(encodebytes(hashed.digest())).rstrip('\n')
print(sign_request())

Upvotes: 3

Related Questions