def get_code(secret): secret = base64.b32decode(b32pad(secret.upper())) auth = OtpAuth(secret) # a secret string code = auth.totp() # generate a time based code code = str(code).zfill(6) return code
def googleScan(inputStr): from otpauth import OtpAuth auth = OtpAuth(inputStr) # a secret string # to_google(self, type, label, issuer, counter=None) s = auth.to_google(type='totp', issuer="PyPI", label='SHA1', counter='6') print(s) return s
def register(): if request.method == 'POST': print 'Username: '******'Username'] print 'Password: '******'Password'] # Connect to database db = sqlite3.connect('google_authenticator.db') cursor = db.cursor() # Create secret and add user to database secret = base64.b32encode(os.urandom(10)).decode('utf-8') query = 'INSERT INTO USERS (USER, PASSWORD, GOOGLEAUTH) VALUES (\"' + request.form['Username'] + '\",\"' + request.form['Password'] + '\",\"' + secret + '\");' cursor.execute(query) db.commit() db.close() # Create unique QR code given secret, label, and issuer auth = OtpAuth(secret) secret_uri = auth.to_uri('totp', GALabel, GAIssuer) qr = QRCode() qr.add_data(secret_uri) qr.make() img = qr.make_image() #img.show() # Opens tmp QR code image print 'Secret: ', secret print 'Secret Uri: ', secret_uri # Display QR code in web browser return redirect(getQRCodeGoogleUrl(secret_uri)) return "Nothing to see here."
def controle_otp(): auth = OtpAuth(db_auth) print(auth) controle = auth.valid_totp(int(input('Voer code in'))) if controle == True: print('Code geaccepteerd') else: print('Helaas de code is onjuist')
def test_totp(): print "\n1.b test totp" auth = OtpAuth('python') code = auth.totp() assert auth.valid_totp(code) print "secret <%s> code <%s>" % (auth.secret, code) #print dir(auth) print "completed successfully"
def otpauth_totp(f_key): print "\n1.b test totp" auth = OtpAuth(f_key) # default step=30 code = auth.totp() assert auth.valid_totp(code) print "secret <%s> code <%s>" % (auth.secret, code) #print dir(auth) print "completed successfully"
def create_tsa(username, user_hash): print str(user_hash) auth = OtpAuth(str(user_hash)) # a secret string s = auth.to_uri('totp', 'User:'******'Kuorra') img = qrcode.make(s) f = open("static/qr/output.png", "wb") img.save(f) f.close()
def test_to_uri_totp(f_provider,f_authKey): print "\n2.b test to uri totp" auth = OtpAuth(f_provider) expect = 'otpauth://totp/'+f_provider+'?secret='+f_authKey+'&issuer=' + f_provider assert auth.to_uri('totp', 'python', 'python') == expect print "provider <%s> authKey <%s> secret <%s> to_uri <%s>" % (f_provider, f_authKey, auth.secret, expect) #print dir(auth) print "completed successfully"
def test_to_google_hotp(f_provider,f_authKey): print "\n3.a test to google hotp" auth = OtpAuth(f_provider) expect = 'otpauth://hotp/'+f_provider+'?secret=' + f_authKey + '&issuer='+f_provider+'&counter=4' assert auth.to_google('hotp', 'python', 'python', 4) == expect print "provider <%s> authKey <%s> secret <%s> to_google <%s>" % (f_provider, f_authKey, auth.secret, expect) print dir(auth) print "completed successfully"
def test_totp(): print "\n1.b test totp" secret= 'dev_annie_04' auth = OtpAuth(secret) code = auth.totp() assert auth.valid_totp(code) print "secret <%s> code <%s>" % (auth.secret, code) #print dir(auth) print "completed successfully"
def controle_otp(response, pincode): auth = OtpAuth(response) controle = auth.valid_totp(int(pincode)) if controle == True: print('Code geaccepteerd') return True else: print('Helaas de code is onjuist') return False
def post(self, client_id, user_id): args = self.parser.parse_args() if args.secret_key != db.hget("apps:" + client_id, "secret_key"): abort(401) auth = OtpAuth(args.secret_key) return dict( valid=auth.valid_totp(args.code), )
def nieuwe_gebruiker(): global db_auth Random = str( (''.join(random.choice('ABDJFHE34543234') for _ in range(16)))) db_auth = Random print(Random) auth = OtpAuth(Random) # Moet 16 lang zijn s = auth.to_uri('totp', 'Jelle Huisman', 'NS Fietsenstalling') import qrcode img = qrcode.make(s) img.show()
def check_password(orm, user, code): if not user or (user.inv_login and user.inv_login>time.time()): logger.debug("interval error") return False user.inv_login = time.time()+30 auth = OtpAuth(user.secret) result = False if auth.valid_totp(code): user.inv_login = None result = True orm.commit() return result
def send_email(orm, user, reset_url, mail_type): """ mail_type: register ro resetpw """ secret = user.secret if mail_type=="register" else user.resetpw logger.debug(secret) auth = OtpAuth(secret) uri = auth.to_uri('totp', user.email, 'userga') qrurl = "?".join(['https://chart.googleapis.com/chart', urlencode({'cht': 'qr', 'chs': '200x200', 'chl': uri})]) logger.debug(qrurl) logger.debug(mail_type) sendmail(user.email, secret, uri, qrurl, reset_url, mail_type)
def put(self, user_id): """ This is the endpoint that creates the user 2fa --- tags: - users 2fa parameters: - in: body name: body schema: id: 2fa_in properties: twoFACode: type: string description: code for 2fa twoFASecret: type: integer description: secret key for user responses: 201: description: user 2fa secret schema: id: success properties: success: type: boolean value: true 400: description: invalid 2fa secret or code schema: id: error 404: description: invalid user schema: id: error """ if user_id is None: return jsonify(error="invalid user id"), 404 user = User.query.filter_by(id=user_id).first() if user is None: return jsonify(error="invalid user"), 404 user2fa_secret = request.json.get('twoFASecret', None) if not user2fa_secret: return jsonify(error="invalid 2fa secret"), 400 user2fa_code = request.json.get('twoFACode', None) if user2fa_code is None: return jsonify(error="invalid 2fa code"), 400 auth = OtpAuth(user2fa_secret) if auth.valid_totp(user2fa_code): user.secure_id = user2fa_secret db.session.commit() return jsonify(success=True), 201 return jsonify(error="wrong code"), 400
def nieuwe_gebruiker(): global db_auth Random = str( (''.join(random.choice('ABDJFHE34543234') for _ in range(16)))) db_auth = Random print('test' + db_auth) auth = OtpAuth(Random) s = auth.to_uri('totp', 'NS', 'NS Fietsenstalling') qr = QRCode(version=1, error_correction=ERROR_CORRECT_L) qr.add_data(s) qr.make() img = qr.make_image() img.save("qrcode.png") return db_auth
def create_qr(self): id = str(self.id) auth = OtpAuth(app.config['SECRET_KEY'] + id) # a secret string email = self.email s = auth.to_uri('totp', email, 'Unit963') qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=15, border=5, ) qr.add_data(s) img = qr.make_image(fill_color="#05528a", back_color="white") img.save('./MFA/static/QR/' + id + '.png')
def post(self, request): """ 用户登录API """ data = request.data user = auth.authenticate(username=data["username"], password=data["password"]) # 如果用户名或者密码错误就什么都没有返回 if user: if user.is_disabled: return self.error("Your account has been disabled") # 如果不需要双因素验证,直接就返回得了,否则向下执行 if not user.two_factor_auth: auth.login(request, user) return self.success("Succeeded") # 来到这里自然说明要双因素验证 # 如果双因素验证码不在tfa_code请求数据里面,就返回错误 if user.two_factor_auth and "tfa_code" not in data: return self.error("tfa_required") # 来到这里,说明需要双因素验证,而且双因素验证码也满足,这里就是判断两码是否一致 # 成功就返回secceeded,错误就返回无效的双因素验证码提示信息 # 传过来的tfa_code不是和数据库保存的数据一致,需要使用OtpAuth的valid_totp再加工一下还原 if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]): auth.login(request, user) return self.success("Succeeded") else: return self.error("Invalid two factor verification code") else: # 最终如果是用户名或者密码出错就返回响应的信息 return self.error("Invalid username or password")
def post(self, request): """ User login api """ data = request.data user = auth.authenticate(username=data["username"], password=data["password"]) # None is returned if username or password is wrong if user: if user.is_disabled: return self.error("Your account has been disabled") if not user.two_factor_auth: auth.login(request, user) return self.success("Succeeded") # `tfa_code` not in post data if user.two_factor_auth and "tfa_code" not in data: return self.error("tfa_required") if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]): auth.login(request, user) return self.success("Succeeded") else: return self.error("Invalid two factor verification code") else: if '@' in data["username"]: return self.error("Don't use email, use your username") return self.error("Invalid username or password")
def _email_two_factor_auth(user): # send email to user that has details on # how to apply TOTP to login to pybossa if user and user.email_addr: msg = dict(subject='One time password generation details for Pybossa', recipients=[user.email_addr]) msg['body'] = render_template('/account/email/otp.md', user=user) otpauths[user.email_addr] = None otpauths[user.email_addr] = OtpAuth( base64.b32encode(os.urandom(10)).decode('utf-8')) otpsecret = otpauths[user.email_addr] if otpsecret is None: flash(gettext("Problem with generating one time password"), 'error') else: otpcode = otpsecret.totp(period=600) # otp valid for 10 mins print '********** OTP code generated before sending email: %r' % otpcode msg['html'] = render_template('/account/email/otp.html', user=user, otpcode=otpcode) mail_queue.enqueue(send_mail, msg) flash( gettext( "An email has been sent to you with one time password"), 'success') else: flash( gettext("We don't have this email in our records. " "You may have signed up with a different " "email or used Twitter, Facebook, or " "Google to sign-in"), 'error')
def post(self, request): """ User login api """ data = request.data user = auth.authenticate(username=data["username"], password=data["password"]) # None is returned if username or password is wrong if user: if user.is_disabled: return self.error("Ваш аккаунт был отключен.") if not user.two_factor_auth: auth.login(request, user) return self.success("Успешно") # `tfa_code` not in post data if user.two_factor_auth and "tfa_code" not in data: return self.error("2фа необходима") if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]): auth.login(request, user) return self.success("Успешно") else: return self.error("Неверный код 2фа") else: return self.error("Неверное имя пользователя или пароль")
def _get_tfa_code(self): # 获取双因素代码 # 正向查询:一对多,查找第一条 user = User.objects.first() code = OtpAuth(user.tfa_token).totp() if len(str(code)) < 6: code = (6 - len(str(code))) * "0" + str(code) return code
def _get_tfa_code(self): # 获得验证码 # 先查找数据库对应的用户,生成一个二维码 user = User.objects.first() code = OtpAuth(user.tfa_token).totp() if len(str(code)) < 6: code = (6 - len(str(code))) * "0" + str(code) return code
def POST_TSA(username, **k): message = None # Error message form = config.web.input() # get form data result = config.model.get_users(username) # search for username data user_hash = str(result.user_hash) auth = OtpAuth(user_hash) if auth.valid_totp(form.authenticator): app.session.loggedin = True raise config.web.seeother('/') else: message = "Two Step Authenticator not valid" # Error message result = config.model.get_users( username) # search for username data result.username = config.make_secure_val(str( result.username)) # apply HMAC for username return config.render.tsa(result, message) # render tsa.html
def segundo_fator(self, metodo, chave): """ Calcula e retorna one-time passwords para uso como segundo fator de autenticação baseados em tempo ou hashes criptografados. ARGS: - metodo (string): pode ser 'time' ou 'hmac'. - chave (string): a chave privada usada para gerar os códigos. """ au = OtpAuth(chave) if metodo == 'time': return au.totp() elif metodo == 'hmac': return au.hotp() else: raise ValueError('método não identificado')
def set_password(orm, email, code): user = get_user(orm, email) if not user or (user.inv_setpw and user.inv_setpw>time.time()): logger.debug("interval error") return False user.inv_setpw = time.time()+30 secret = user.resetpw if user.resetpw else user.secret auth = OtpAuth(secret) logger.debug(auth.valid_totp(code)) if user.expires and user.expires>time.time() and auth.valid_totp(code): user.inv_setpw = None if user.resetpw: user.secret = user.resetpw user.resetpw = None user.expires = None orm.commit() return True orm.commit() return False
def test_hotp(): auth = OtpAuth('python') code = auth.hotp(4) assert auth.valid_hotp(code) == 4 # false assert auth.valid_hotp(1234567) is False assert auth.valid_hotp(123456) is False assert auth.valid_hotp('123456') is False
def gen_TOTP(rand_text): token = bool(1) auth = OtpAuth(rand_text) print("Ref creating main is : " + rand_text) ref_totp = auth.totp() str_totp = "" if (ref_totp > 99999): str_totp = str(ref_totp) if (99999 >= ref_totp > 9999): str_totp = "0" + str(ref_totp) if (9999 >= ref_totp > 999): str_totp = "00" + str(ref_totp) if (999 >= ref_totp > 99): str_totp = "000" + str(ref_totp) if (99 >= ref_totp > 9): str_totp = "0000" + str(ref_totp) if (9 >= ref_totp): str_totp = "00000" + str(ref_totp) print("TOTP : ", str_totp) return 0
def put(self, request): code = request.data["code"] user = request.user if not user.two_factor_auth: return self.error("2ФА уже выключена") if OtpAuth(user.tfa_token).valid_totp(code): user.two_factor_auth = False user.save() return self.success("Успешно") else: return self.error("Неверный код")
def put(self, request): code = request.data["code"] user = request.user if not user.two_factor_auth: return self.error("2FA is already turned off") if OtpAuth(user.tfa_token).valid_totp(code): user.two_factor_auth = False user.save() return self.success("Succeeded") else: return self.error("Invalid code")
def login(): if request.method == 'POST': print 'Username: '******'Username'] print 'Password: '******'Password'] print 'Google Auth Code: ', request.form['GoogleAuth'] # Connect to database and query for user&password db = sqlite3.connect('google_authenticator.db') cursor = db.cursor() cursor.execute('SELECT GOOGLEAUTH FROM USERS WHERE USER=\'' + request.form['Username'] + '\' AND PASSWORD=\'' + request.form['Password'] + '\';') secret = cursor.fetchone() db.close() # Query returns None if user&password don't exist if secret is None: return "Unsuccesful login attempt." # Verify google authentication code with secret from database else: # Generate the otpauth protocal string. secret = secret[0] print 'Secret: ', secret auth = OtpAuth(secret) secret_uri = auth.to_uri('totp', GALabel, GAIssuer) # algorithm type, label, issuer # Generate TOTP code given code uri code = auth.totp() # Generate time based code print 'Code Uri: ', secret_uri print 'Valid Google Auth Code: ', code # Compare code provided by user with valid code if auth.valid_totp(int(request.form['GoogleAuth'])): return "Successfully logged in!" else: print "Invalid Google Authenticator." return "Unsuccessful login attempt." return "Unsuccessful login attempt." return "Nothing to see here."
def post(self, request): """ Open 2FA """ code = request.data["code"] user = request.user if OtpAuth(user.tfa_token).valid_totp(code): user.two_factor_auth = True user.save() return self.success("Succeeded") else: return self.error("Invalid code")
def test_tfa_login(self): token = self._set_tfa() code = OtpAuth(token).totp() if len(str(code)) < 6: code = (6 - len(str(code))) * "0" + str(code) response = self.client.post(self.login_url, data={"username": self.username, "password": self.password, "tfa_code": code}) self.assertDictEqual(response.data, {"error": None, "data": "Succeeded"}) user = auth.get_user(self.client) self.assertTrue(user.is_authenticated)
def post(self, request): """ 开启 2FA 模式 """ code = request.data["code"] user = request.user # 从数据库查找出对应的code和传过来的code比较,成功就设置双因素验证为True if OtpAuth(user.tfa_token).valid_totp(code): user.two_factor_auth = True user.save() return self.success("Succeeded") else: return self.error("Invalid code")
def test_totp(): auth = OtpAuth('python') code = auth.totp() assert auth.valid_totp(code) # false assert auth.valid_totp(1234567) is False assert auth.valid_totp(123456) is False
def get(self, request): """ Get QR code """ user = request.user if user.two_factor_auth: return self.error("2FA is already turned on") token = rand_str() user.tfa_token = token user.save() label = f"{SysOptions.website_name_shortcut}:{user.username}" image = qrcode.make(OtpAuth(token).to_uri("totp", label, SysOptions.website_name)) return self.success(img2base64(image))
def post(self, client_id, user_id): args = self.parser.parse_args() if args.secret_key != db.hget("apps:" + client_id, "secret_key"): abort(401) app_name = db.hget("apps:" + client_id, "name") user = db.hgetall( "apps:{}:users:{}".format(client_id, user_id), ) auth = OtpAuth(args.secret_key) code = auth.totp() res = requests.post( CHIKKA_SMS_ENDPOINT, data=dict( message_type="SEND", # Inconsistent mobile_number=user["number"], shortcode=current_app.config["CHIKKA_SHORTCODE"], message_id=simpleflake(), message="""{} Code: {} - """.format(app_name, code), request_cost="FREE", client_id=current_app.config["CHIKKA_CLIENT_ID"], secret_key=current_app.config["CHIKKA_SECRET_KEY"], ), ) if res.status_code != requests.codes.ok: abort(500) return ""
def qrCoderValid(inputStr): auth = OtpAuth(inputStr) hotp_code = auth.hotp(6) valid = auth.valid_hotp(hotp_code) # hotp_code = auth.hotp(6) # valid = auth.valid_hotp(hotp_code) totp_code = auth.totp(period=30, ) print(totp_code) if auth.valid_totp(totp_code): return totp_code return totp_code
def post(self, request): data = request.data user = auth.authenticate(username=request.user.username, password=data["password"]) if user: if user.two_factor_auth: if "tfa_code" not in data: return self.error("tfa_required") if not OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]): return self.error("Invalid two factor verification code") data["new_email"] = data["new_email"].lower() if User.objects.filter(email=data["new_email"]).exists(): return self.error("The email is owned by other account") user.email = data["new_email"] user.save() return self.success("Succeeded") else: return self.error("Wrong password")
def test_to_google_raise(): auth = OtpAuth('python') auth.to_google('invalid', 'python', 'python')
def test_to_google_totp(): auth = OtpAuth('python') expect = 'otpauth://totp/python?secret=OB4XI2DPNY&issuer=python' assert auth.to_google('totp', 'python', 'python') == expect
def check_otp(self, otp): otpa = OtpAuth(self.secret) return otpa.valid_totp(otp)
def _create_otp_secret(): otp_secret = OtpAuth(base64.b32encode(os.urandom(10)).decode('utf-8')) return otp_secret.totp()
def test_to_google_hotp_raise(): auth = OtpAuth('python') auth.to_google('hotp', 'python', 'python')
def generate_qr_code(totp, username): otpa = OtpAuth(totp.secret) uri = otpa.to_uri( 'totp', 'BobCraft:{0}'.format(username), 'BobCraft') return qrcode.make(uri)
def test_to_google_hotp(): auth = OtpAuth('python') expect = 'otpauth://hotp/python?secret=OB4XI2DPNY&issuer=python&counter=4' assert auth.to_google('hotp', 'python', 'python', 4) == expect
#!/usr/bin/env python from otpauth import OtpAuth import time, base64 secret = "QDQQFZ6AUZQ2YR6N" # key for gooby:1 auth = OtpAuth(base64.b32decode(secret)) print "[+]User: gooby, password:1" print "[+]TOTP token: [%d]" % auth.totp() print "[+]%s " % time.strftime("%c")
def otpauth_totp(f_key): print "\ntotp per raw secret" auth = OtpAuth(f_key) # default step=30 code = auth.totp() assert auth.valid_totp(code) print "secret <%s> code <%s>" % (auth.secret, code)
import socket from otpauth import OtpAuth auth = OtpAuth('secret') UDP_IP = "127.0.0.1" UDP_PORT = 5005 print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT MESSAGE = str(auth.totp()) sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
''' // // nemo2 connect api // wscat --connect ws://54.215.201.239:8081/5d86cc5c-6d4b-4bf8-f8bd-a6963b279fb1/026283/event // ''' host='54.215.201.239' port='8081' dev_uuid='49ff3cdf-1a08-4541-9fb4-8c82f4e343c5' app_uuid='c1838690-6ec1-49d5-edd3-32da0b8114b4' from otpauth import OtpAuth app_key="This is interesting What is going on Need a long sentence carry on and take more" auth = OtpAuth(app_key) app_token = auth.totp() exchange='event' url ='ws://' + host + ':' + port + '/' + app_uuid +'/' + str(app_token) + '/' + exchange import json d1='{".insert":{"binding":"cloud.' + dev_uuid + '.device.ip.*.temperature"}}' d2 = json.loads(d1) data = json.dumps(d2) ''' // // main // WebSocket = require('ws')