Skip to content

Instantly share code, notes, and snippets.

@chomy
Created July 2, 2016 09:19
Show Gist options
  • Save chomy/66a84f8bea3d322de36d108ee406a3cc to your computer and use it in GitHub Desktop.
Save chomy/66a84f8bea3d322de36d108ee406a3cc to your computer and use it in GitHub Desktop.
Time based one time password generator, based on RFC6238 and Google Authenticator
#!/usr/bin/python
import array
import base64
import hmac
import math
import sha
import time
from hashlib import sha1
def get_otp(key, step):
hashed = hmac.new(key,step,sha1)
binary = array.array('B', hashed.hexdigest().decode('hex'));
offset = binary[19]&0x0F
binary = ((binary[offset] & 0x7F)<<24)|((binary[offset+1]&0xFF)<<16)|((binary[offset+2]&0xFF)<<8)|(binary[offset+3]&0xFF);
return '%06d'%(binary%1000000)
def calc_step():
now = math.floor(time.time())
step = int(math.floor(now/30))
result = hex(step).replace('0x','')
while(len(result)<16):
result = '0'+result
return result.decode('hex')
if(__name__=='__main__'):
key = base64.b32decode("JBSWY3DPEHPK3PXP")
step = calc_step()
print get_otp(key, step)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment