3

im facing problem while running code below always give "Error: Non-base32 digit found" i did searched online and fix it by using utf-8 for secret = base64.b32decode(bytes(secret, 'utf-8')) but its not working giving me same error. Any suggestion? i'm using python 3.8

import hmac
import base64
import hashlib
import datetime
import time


#totp
interval=30 #seconds


#otp
digest=hashlib.sha1
digits=6 #number of integers supported?
secret='123456789abcdefg'



#totp
now=datetime.datetime.now()
i=time.mktime(now.timetuple())
timecode=int(i/interval)


#otp
base64_secret = base64.b32decode(secret,casefold=True)
res = []
while timecode != 0:
    res.append(chr(timecode & 0xFF))
    timecode = timecode >> 8
bytestring=''.join(reversed(res)).rjust(8,'\0') #padding=8
hmac_hash = hmac.new(
    base64_secret,
    bytestring,
    digest
).digest()

offset=ord(hmac_hash[19]) & 0xf
code = ((ord(hmac_hash[offset]) & 0x7f) << 24 |
    (ord(hmac_hash[offset + 1]) & 0xff) << 16 |
    (ord(hmac_hash[offset + 2]) & 0xff) << 8  |
    (ord(hmac_hash[offset + 3]) & 0xff))

code = code % 10 ** digits

print (code)
Jessa
  • 31
  • 1
  • 3

1 Answers1

3

The Wikipedia article on base32 says that the most common version of base32 uses as digits the 26 letters in the standard alphabet, together with the digits in the range 2-7. Your code was trying to use as digits the numbers 1,8,9. Those are not base 32 digits, hence the error.

To solve that bug, swap out those 3 digits with letters something like:

secret='234567abcdefghij'

With that change, this bug disappears. Unfortunately, other bugs in your code appear, but that is a separate question.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • ya you right, starting now giving me TypeError: Unicode-objects must be encoded before hashing – Jessa Jan 19 '22 at 01:28