Last active
April 1, 2017 00:54
-
-
Save jimbojetset/d6d8e0858cdc5cd79d2a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3.5 | |
# -*- coding: utf-8 -*- | |
""" | |
Copyright (c) 2015 James Booth | |
This program is free software: you can redistribute it and/or modify | |
it under the terms of the GNU General Public License as published by | |
the Free Software Foundation, either version 3 of the License, or | |
(at your option) any later version. | |
This program is distributed in the hope that it will be useful, | |
but WITHOUT ANY WARRANTY; without even the implied warranty of | |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License | |
along with this program. If not, see <http://www.gnu.org/licenses/>. | |
Python V3.5 Google two-factor authentication Class. | |
""" | |
from base64 import b32decode | |
import time | |
import struct | |
from hashlib import sha1 | |
import hmac | |
class Totp(object): | |
class TotpException(Exception): | |
def __init__(self, msg): | |
self.msg = msg | |
def __str__(self): | |
return repr(self.msg) | |
def __init__(self, interval=30, pin_length=6): | |
self.__interval = interval | |
self.__pin_length = pin_length | |
def generate_pin(self, base32secret): | |
if not base32secret: | |
raise TOTP.TOTPException('No base32secret supplied') | |
try: | |
secret_bytes = b32decode(base32secret.upper()) | |
time_seconds = int(int(time.time())/ self.__interval) | |
time_bytes = struct.pack('>Q', time_seconds) | |
hmacsha1 = hmac.new(secret_bytes, time_bytes, sha1) | |
hash_bytes = bytearray.fromhex(str(hmacsha1.hexdigest())) | |
offset = hash_bytes[-1] & 0xF | |
data = hash_bytes[offset:offset + 4][::-1] | |
integer = int.from_bytes(data, byteorder='little', signed=True) & 0x7FFFFFFF | |
return str(integer)[-6:] | |
except: | |
raise Totp.TotpException('Invalid base32secret supplied') | |
# Test Code | |
totp = Totp() | |
pin = totp.generate_pin('fzwa7rpj2v4i7xocxnrdys4t4swzkn5g') | |
print (pin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment