title: Google Authenticator implementation in Python
body: <p>I am trying to use one-time passwords that can be generated using <a href="https://market.android.com/details?id=com.google.android.apps.authenticator" rel="noreferrer">Google Authenticator application</a>.</p>
  <h2>What Google Authenticator does</h2>
  <p>Basically, Google Authenticator implements two types of passwords:</p>
  <ul>
  <li><strong>HOTP</strong> - HMAC-based One-Time Password, which means the password is changed with each call, in compliance to <a href="https://www.rfc-editor.org/rfc/rfc4226" rel="noreferrer">RFC4226</a>, and</li>
  <li><strong>TOTP</strong> - Time-based One-Time Password, which changes for every 30-seconds period (as far as I know).</li>
  </ul>
  <p>Google Authenticator is also available as Open Source here: <a href="http://code.google.com/p/google-authenticator/" rel="noreferrer">code.google.com/p/google-authenticator</a></p>
  <h2>Current code</h2>
  <p>I was looking for existing solutions to generate HOTP and TOTP passwords, but did not find much. The code I have is the following snippet responsible for generating HOTP:</p>
  <pre><code>import hmac, base64, struct, hashlib, time
  
  def get_token(secret, digest_mode=hashlib.sha1, intervals_no=None):
      if intervals_no == None:
          intervals_no = int(time.time()) // 30
      key = base64.b32decode(secret)
      msg = struct.pack(&quot;&gt;Q&quot;, intervals_no)
      h = hmac.new(key, msg, digest_mode).digest()
      o = ord(h[19]) &amp; 15
      h = (struct.unpack(&quot;&gt;I&quot;, h[o:o+4])[0] &amp; 0x7fffffff) % 1000000
      return h
  </code></pre>
  <p>The problem I am facing is that the password I generate using the above code is not the same as generated using Google Authenticator app for Android. Even though I tried multiple <code>intervals_no</code> values (exactly first 10000, beginning with <code>intervals_no = 0</code>), with <code>secret</code> being equal to key provided within the GA app.</p>
  <h2>Questions I have</h2>
  <p>My questions are:</p>
  <ol>
  <li>What am I doing wrong?</li>
  <li>How can I generate HOTP and/or TOTP in Python?</li>
  <li>Are there any existing Python libraries for this?</li>
  </ol>
  <p>To sum up: please give me any clues that will help me implement Google Authenticator authentication within my Python code.</p>