1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Introduction to HMAC & Using in Python

Discussion in 'Python' started by pradeep, Apr 23, 2013.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    HMAC stands for Hash-base Message Authentication Code, it is key based message digest algorithm which can be used for verifying the integrity of the message (i.e. the original message from which the hash is generated) or to verify the authenticity of the sender of the message or both. Nowadays, HMAC is being widely used in various systems & domains, like server-to-server communications, Web Service APIs, etc. A well known use of HMAC is in Amazon's AWS API calls where the signature is generated using HMAC.

    HMAC can use a variety of hashing algorithms, like MD5, SHA1, SHA256, etc. HMAC function is not very processing intensive, so it has been widely accepted, and it is relatively easy to implement in mobile & embedded devices too while maintaining decent security.

    Using HMAC in Python



    Since Python version 2.2 the HMAC module comes with Python installation, and the hashing library hashlib comes with the Python installation from version 2.5 onwards, in case you are having Python versions lesser than earlier mentioned, you'll need to manually install the HMAC/hashlib libraries.

    Once you are all set, creating the HMAC digest is pretty simple, follow the next code example where we'll generate a HMAC-MD5 digest with Python code:

    Code:
    import hmac
    from hashlib import md5
    
    key = 'HAHGDSHHHKMYKEY'
    
    h = hmac.new(key,'',md5)
    
    ## add content
    h.update('Asha')
    
    ## print the HMAC digest
    print h.hexdigest()
    
    That was easy, now I'll demonstrate a real-world example of generating Amazon S3 sharing file URL:

    Code:
    import hmac
    from hashlib import sha1
    import base64
    import time
    import urllib
    
    s3_path = '/g4ebucket/data.tgz'
    s3_access_key = 'hsjahhjj33'
    s3_secret_key = 'kAJSJSDhAKJSj/kajskSAKj/='
    s3_expiry = time.time() + 60 * 10 ## 10 minutes
    
    str_to_sign = "GET\n\n\n%s\n%s" % s3_expiry,s3_path
    
    h = hmac.new(s3_secret_key,'',hashlib.sha())
    
    h.update(str_to_sign)
    
    ## read more about signing method: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
    signature = urllib.urlencode( base64.b64encode( h.digest ) )
    
    ## print out the URL
    print "http://s3.amazonaws.com%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s" % s3_path, s3_access_key, s3_expiry, signature
    
     
    shabbir likes this.

Share This Page