private void btnSetup_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var setupCode = tfA.GenerateSetupCode(this.txtAccountTitle.Text, this.txtSecretKey.Text, pbQR.Width, pbQR.Height);

            WebClient wc = new WebClient();
            MemoryStream ms = new MemoryStream(wc.DownloadData(setupCode.QrCodeSetupImageUrl));
            this.pbQR.Image = Image.FromStream(ms);

            this.txtSetupCode.Text = "Account: " + setupCode.Account + System.Environment.NewLine +
                "Secret Key: " + setupCode.AccountSecretKey + System.Environment.NewLine +
                "Encoded Key: " + setupCode.ManualEntryKey;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.QueryString["key"]))
            {
                Response.Redirect("~/default.aspx?key=" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10));
            }

            this.lblSecretKey.Text = Request.QueryString["key"];

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var setupInfo = tfa.GenerateSetupCode("Test Two Factor", "*****@*****.**", Request.QueryString["key"], 300, 300);

            string qrCodeImageUrl = setupInfo.QrCodeSetupImageUrl;
            string manualEntrySetupCode = setupInfo.ManualEntryKey;

            this.imgQrCode.ImageUrl = qrCodeImageUrl;
            this.lblManualSetupCode.Text = manualEntrySetupCode;
        }
        private bool ValidateGoogleCode()
        {
            string UserName = null;

            if (System.Web.HttpContext.Current.Request.Cookies["PPusernameMerchant"] != null)
            {
                UserName = ClassLibrary1.ClassAccount.cookie解密(System.Web.HttpContext.Current.Request.Cookies["PPusernameMerchant"]["username"]);
            }
            if (UserName != null)
            {
                using (var db = (new DBClient()).GetClient())
                {
                    var data = db.Queryable <Sugar.Enties.table_商户账号>().Where(it => it.商户ID == UserName).First();
                    if (data.二步验证状态 == true)
                    {
                        if (TextGoogleValidate.Text.Length != 6)
                        {
                            ClassLibrary1.ClassMessage.HinXi(Page, "验证码不和规范");
                            return(false);
                        }
                        TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

                        var result = tfa.ValidateTwoFactorPIN(data.keyga, TextGoogleValidate.Text);
                        if (!result)
                        {
                            ClassLibrary1.ClassMessage.HinXi(Page, "验证码错误");
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
        protected void ProceedBtn_Click(object sender, EventArgs e)
        {
            string user_enter          = gAuthTb.Text;
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            bool isCorrectPIN          = tfa.ValidateTwoFactorPIN(ViewState["key"].ToString(), user_enter);

            if (isCorrectPIN == true)
            {
                String input_username = username_tb.Text;
                UserBO userbo         = new UserBO();
                user   returnedObj    = new user();
                returnedObj = userbo.getUserById(input_username);
                //to create session for user
                Session["LoginUserName"] = returnedObj.User_ID.ToString();
                string guid = Guid.NewGuid().ToString();
                //create second session for user and assigning a random GUID
                Session["AuthToken"] = guid;

                //Session["authWin"] = guidWN;
                //Create cokie and store the same value of second session in cookie
                Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                Response.Cookies.Add(new HttpCookie("CurrentLoggedInUser", returnedObj.User_ID.ToString()));
                Response.Cookies["AuthToken"].Expires           = DateTime.Now.AddDays(1); //so the cookie will be expired if user didn't log out properly
                Response.Cookies["CurrentLoggedInUser"].Expires = DateTime.Now.AddDays(1); //so the cookie will be expired if user didn't log out properly
                Response.Redirect("Dashboard.aspx");                                       //login pass
            }
            else
            {
                modalOverlay.Visible = false;
            }
        }
Example #5
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            var tfA    = new TwoFactorAuthenticator();
            var result = tfA.ValidateTwoFactorPin(txtSecretKey.Text, txtCode.Text);

            MessageBox.Show(result ? "Validated!" : "Incorrect", "Result");
        }
Example #6
0
        public ActionResult Login(LoginModel login)
        {
            string message = "";
            bool   status  = false;

            //check UserName and password form our database here
            if (login.UserName == "Admin" && login.Password == "12345") // Admin as user name and 12345 as Password
            {
                status              = true;
                message             = "Two Factor Authentication Verification";
                Session["UserName"] = login.UserName;
                //Two Factor Authentication Setup
                TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
                string UserUniqueKey = (login.UserName + key);
                Session["UserUniqueKey"] = UserUniqueKey;
                var setupInfo = TwoFacAuth.GenerateSetupCode("Dot Net Detail", login.UserName, UserUniqueKey, 300, 300);
                ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                ViewBag.SetupCode       = setupInfo.ManualEntryKey;
            }
            else
            {
                message = "Please Enter the Valid Credential!";
            }
            ViewBag.Message = message;
            ViewBag.Status  = status;
            return(View());
        }
Example #7
0
        public IActionResult LoginTwoFactor(LoginTwoFactorVM model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Login"));
            }

            Korisnik korisnik = ctx.Korisnik
                                .SingleOrDefault(x => x.KorisnickoIme == model.username && x.LozinkaHash == PasswordSettings.GetHash(model.password, Convert.FromBase64String(x.LozinkaSalt)));

            if (korisnik == null)
            {
                ViewData["poruka"] = "Pogrešan username ili password";
                return(View("Login"));
            }


            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string current = TwoFacAuth.GetCurrentPIN(korisnik.TwoFactorUniqueKey);
            bool   isValid = current.Equals(model.TwoFactorPin);

            //bool isValid = true;
            if (isValid)
            {
                HttpContext.SetLogiraniKorisnik(korisnik, snimiUCookie: model.ZapamtiLozinku);
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ViewData["poruka"] = "Pogrešan kod";
                return(View("LoginTwoFactor", model));
            }
        }
Example #8
0
        public ActionResult Login(LoginModel login)
        {
            string message = "";
            bool   status  = false;

            //Checking username and password
            if (login.Username == "Admin" && login.Password == "admin")
            {
                status = true;
                Session["username"] = login.Username;

                //"2FA Setup
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                //
                var SetupInfo = tfa.GenerateSetupCode("QR Code", login.Username, key, 300, 300);
                ViewBag.BarcodeImageUrl = SetupInfo.QrCodeSetupImageUrl;
            }
            else
            {
                message           = "Login failed";
                ViewBag.FailLogin = true;
            }

            ViewBag.Message = message;
            ViewBag.Status  = status;

            return(View());
        }
Example #9
0
        private void 更新内容()//更新出去
        {
            if (TextBox_后台账号名称.Text.Length > 1)
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                var result = tfa.ValidateTwoFactorPIN(获取密匙(), TextBox_验证密匙.Text);

                if (result)
                {
                    //this.lblValidationResult.Text = this.txtCode.Text + " 是UTC时间内有效PIN码 " + DateTime.UtcNow.ToString();
                    //this.lblValidationResult.ForeColor = System.Drawing.Color.Green;


                    操作更新();
                }
                else
                {
                    ClassLibrary1.ClassMessage.HinXi(Page, "KEY错误");

                    //this.lblValidationResult.Text = this.txtCode.Text + " 是UTC时间内不有效的PIN码 " + DateTime.UtcNow.ToString();
                    //this.lblValidationResult.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                ClassLibrary1.ClassMessage.HinXi(Page, "检查所有栏位是否都已填写");
            }
        }
Example #10
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
        bool isCorrectPIN          = tfa.GetCurrentPIN("SuperSuperSuperSecretKeyGoesHere") == NameTextBox.Text;

        lblCheck.Text = isCorrectPIN.ToString();
    }
        public ActionResult Authentication()
        {
            var user = NewspaperSBTSession.CurrentUser;

            if (user == null)
            {
                return(RedirectToAction("Index", "Login"));
            }

            if (user.Userid.ToString() != null)
            {
                TwoFactorAuthenticator tf = new TwoFactorAuthenticator();
                var secretkey             = Encryption.Randomkey(8);
                secretkey   = secretkey + user.Fullname;
                user.tokken = secretkey;
                var setupInfo = tf.GenerateSetupCode("NewsPaperSBT.com", user.Fullname, secretkey, false, 100);
                ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                ViewBag.SetupCode       = setupInfo.ManualEntryKey;
                return(View());
            }
            else
            {
                return(View("Index"));
            }
        }
        public ActionResult Authentication(int tokken)
        {
            var user = NewspaperSBTSession.CurrentUser;

            if (user == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            TwoFactorAuthenticator tf = new TwoFactorAuthenticator();
            bool isValid = tf.ValidateTwoFactorPIN(user.tokken.ToString(), tokken.ToString());

            if (isValid)
            {
                string PageName = bal.getuserProfileStatus(user.Userid);
                if (!string.IsNullOrEmpty(PageName))
                {
                    return(RedirectToAction("Index", PageName));
                }
            }
            else
            {
                return(RedirectToAction("Authentication", "login"));
            }
            return(null);
        }
Example #13
0
        private void OK_Click(object sender, EventArgs e)
        {
            var tfa      = new TwoFactorAuthenticator();
            var verified = tfa.ValidateTwoFactorPIN(account, PasswordTextBox.Text);

            DialogResult = verified ? DialogResult.OK : DialogResult.Abort;
        }
Example #14
0
        public async Task <JsonResult> GetTwoFactorDataFor(int hidrogenianId)
        {
            _logger.LogInformation("AccountController.GetTwoFactorDataFor - hidrogenianId=" + hidrogenianId);

            var secretKey = await _accountService.RetrieveTwoFaSecretKeyFor(hidrogenianId);

            if (secretKey == null)
            {
                return(new JsonResult(new { Result = RESULTS.FAILED, Message = "Error occurred while looking for your Two-Factor Authentication." }));
            }

            if (secretKey.Length == 0)
            {
                return(new JsonResult(new { Result = RESULTS.SUCCESS }));
            }

            var twoFa = new TwoFaVM {
                Id = hidrogenianId
            };
            var identity = await _accountService.GetAccountIdentity(hidrogenianId);

            var tfa           = new TwoFactorAuthenticator();
            var authenticator = tfa.GenerateSetupCode(
                HidroConstants.PROJECT_NAME, identity.Email,
                secretKey, false, 200
                );

            twoFa.QrImageUrl   = authenticator.QrCodeSetupImageUrl;
            twoFa.ManualQrCode = authenticator.ManualEntryKey;

            return(new JsonResult(new { Result = RESULTS.SUCCESS, Message = twoFa }));
        }
        private void btnTest_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var result = tfA.ValidateTwoFactorPIN(txtSecretKey.Text, this.txtCode.Text);

            MessageBox.Show(result ? "Validated!" : "Incorrect", "Result");
        }
Example #16
0
        /// <summary>
        /// 生成设置代码。
        /// </summary>
        /// <param name="accountTitle"></param>
        /// <param name="secretKey"></param>
        /// <returns>QrCodeImageUrl</returns>
        public static string Generate(string accountTitle, string secretKey)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var setupCode = tfA.GenerateSetupCode(accountTitle, accountTitle, secretKey, false, 50);

            return(setupCode.QrCodeSetupImageUrl);
        }
Example #17
0
        public Task <bool> ValidateAsync(string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user)
        {
            TwoFactorAuthenticator autenticador = new TwoFactorAuthenticator();
            var resultado = autenticador.ValidateTwoFactorPIN(user.Id, token);

            return(Task.FromResult(resultado));
        }
Example #18
0
 public ActionResult validateSms(string phoneCode)
 {
     try
     {
         if (Session["phoneCode"].ToString() == phoneCode)
         {
             ViewData["step"] = "third";
             ViewBag.Action   = "google_auth";
             AzureConnection db        = new AzureConnection();
             string          email     = Session["email"].ToString();
             var             user_data = db.user_table.Where(a => a.email == email).FirstOrDefault();
             user_data.qrScanned = true;
             db.SaveChanges();
             TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
             SetupCode setupInfo        = tfa.GenerateSetupCode("TRUSTBTC", Session["email"].ToString(), Session["qrkey"].ToString(), 300, 300);
             ViewData["qrUrl"] = setupInfo.QrCodeSetupImageUrl;
             return(View("google_auth"));
         }
         else
         {
             ViewData["step"] = "second";
             ViewBag.Action   = "google_auth";
             ViewBag.Message  = "Code isn't correct.";
             return(View("google_auth"));
         }
     }
     catch
     {
         return(RedirectToAction("", "Home"));
     }
 }
Example #19
0
        public TwoFactorValidation ValidateGoogleAuthSetup(string twoFactorCode)
        {
            var model   = new TwoFactorValidation();
            var userId  = Security.GetUserId();
            var details = CustomDatabase.GetUserDetails(userId);

            if (details != null && details.IsValidated)
            {
                throw new UnauthorizedAccessException("This account has already setup GoogleAuthenticator");
            }

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            var isValid = tfa.ValidateTwoFactorPIN(details.Configuration, twoFactorCode);

            if (isValid)
            {
                details.IsValidated = true;
                CustomDatabase.Update(details);
                model.IsValid  = true;
                model.Settings = GetMySettings();
            }
            else
            {
                model.IsValid = false;
            }
            return(model);
        }
Example #20
0
        protected void btnVerifyCode_Click(object sender, EventArgs e)
        {
            Page.Validate(valGroup);
            if (!Page.IsValid)
            {
                return;
            }

            if (String.IsNullOrEmpty(AuthCode))
            {
                throw new InvalidOperationException("Validation required but no authcode provided");
            }

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            if (tfa.ValidateTwoFactorPIN(AuthCode, txtCode.Text, new TimeSpan(0, 2, 0)))
            {
                TFACodeVerified?.Invoke(this, new EventArgs());
            }
            else
            {
                FailureCount++;
                System.Threading.Thread.Sleep(1000); // pause for a second to thwart dictionary attacks.
                TFACodeFailed?.Invoke(this, new EventArgs());
            }
            txtCode.Text = string.Empty;    // clear it regardless.
        }
Example #21
0
        public static ReponseApi ReconfiguraToken(string app, string usuario, string email)
        {
            ReponseApi res = new ReponseApi();

            try
            {
                TwoFactorAuthenticator autenticador = new TwoFactorAuthenticator();
                ResponseQRGoogle       resGoogle    = new ResponseQRGoogle();
                var key                = TwoStepsAuthenticator.Authenticator.GenerateKey();
                var setupInfo          = autenticador.GenerateSetupCode(app, email, key, false, 4);
                var codigoRecuperacion = TwoStepsAuthenticator.CounterAuthenticator.GenerateKey();

                resGoogle.QRImagen     = setupInfo.QrCodeSetupImageUrl;
                resGoogle.LlaveSecreta = key;
                resGoogle.CodigoManual = setupInfo.ManualEntryKey;

                string idUsuario;
                idUsuario = EjecucionSP.ActualizaToken(usuario, app, key, setupInfo.ManualEntryKey, codigoRecuperacion);

                string cuerpoCorreo = "<h1>Código de Recuperación</h1><br>" + codigoRecuperacion;

                Correo.EnviarMensaje("*****@*****.**", "Configuración de Doble Factor para " + app, cuerpoCorreo);

                res.Codigo    = 1;
                res.Mensaje   = idUsuario;
                res.Respuesta = resGoogle;
            }
            catch (Exception ex)
            {
                res.Codigo  = 0;
                res.Mensaje = ex.Message;
            }

            return(res);
        }
 public IActionResult Send2FA()
 {
     if (HttpContext.Session.GetString("LoginID") != null)
     {
         return(RedirectToAction("Profile"));
     }
     if (TempData["LoginEmail"] != null)
     {
         string email = TempData["LoginEmail"].ToString();
         //Two Factor Authentication Setup
         TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
         User   loggingIn     = _context.GetUserByEmail(email);
         string UserUniqueKey = (email + GoogleAuthKey);
         TempData["UserUniqueKey"] = UserUniqueKey; //Session
         var setupInfo = TwoFacAuth.GenerateSetupCode("Centrics Network", email, UserUniqueKey, 300, 300);
         ViewBag.Message = "Enter your code displayed in Google Authenticator.";
         if (loggingIn.Authenticated == false)
         {
             ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
             ViewBag.SetupCode       = setupInfo.ManualEntryKey;
             TempData["LoginEmail"]  = email;
         }
         else if (loggingIn.Authenticated == true)
         {
             ViewBag.BarcodeImageUrl = null;
             ViewBag.SetupCode       = null;
             TempData["LoginEmail"]  = email;
         }
         return(View());
     }
     return(View("Error"));
 }
Example #23
0
        /// <inheritdoc />
        /// <summary>
        /// Explicitly implement this interface method - which overrides the base class's implementation
        /// </summary>
        /// <param name="purpose"></param>
        /// <param name="token"></param>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        async Task <bool> IUserTokenProvider <BackOfficeIdentityUser, int> .ValidateAsync(string purpose, string token, UserManager <BackOfficeIdentityUser, int> manager, BackOfficeIdentityUser user)
        {
            if (purpose == Constants.GoogleAuthenticatorProviderName)
            {
                var twoFactorAuthenticator = new TwoFactorAuthenticator();

                using (var scope = Current.ScopeProvider.CreateScope(autoComplete: true))
                {
                    var result = await scope.Database.Query <TwoFactor>()
                                 .Where(x => x.UserId == user.Id && x.Key == Constants.GoogleAuthenticatorProviderName && x.Confirmed)
                                 .ToListAsync();

                    if (result.Any() == false)
                    {
                        return(false);
                    }

                    var key        = result.First().Value;
                    var validToken = twoFactorAuthenticator.ValidateTwoFactorPIN(key, token);
                    return(validToken);
                }
            }

            /* if (purpose == Constants.YubiKeyProviderName)
             * {
             *   var yubiKeyService = new YubiKeyService();
             *   var response = yubiKeyService.Validate(token, user.Id);
             *   return Task.FromResult(response != null && response.Status == YubicoResponseStatus.Ok);
             * }*/

            return(false);
        }
        public static bool ValidateCode(string userAccountSecreteKey, string code)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            bool isCorrectPin          = tfa.ValidateTwoFactorPIN(userAccountSecreteKey, code, new TimeSpan(0, 15, 0));

            return(isCorrectPin);
        }
Example #25
0
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            bool   checkPin            = false;
            string pin                 = txtPIN.Text;
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();

            checkPin = tfa.ValidateTwoFactorPIN(("!8R8Vrreugfifbtljuf" + txtUsername.Text), pin);

            if (!checkPin)
            {
                btnSubmit.Enabled   = false;
                txtPIN.Enabled      = false;
                btnSubmit.Visible   = false;
                txtPIN.Visible      = false;
                btnLogin.Visible    = true;
                txtPassword.Visible = true;
                txtUsername.Visible = true;
                txtUsername.Text    = "";
                txtPassword.Text    = "";
                lblSuccess.Text     = "Invalid PIN";
                txtPIN.Text         = "";
            }
            else
            {
                login();
            }
        }
Example #26
0
        public ActionResult Login(LoginModel login)
        {
            string message = "";
            bool   status  = false;

            if (login.username == "DurelleAbdul" && login.password == "26661543")
            {
                status              = true;
                message             = "2FA Verification";
                Session["Username"] = login.username;

                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                string userUniqueKey       = login.username + key;
                Session["UserUniqueKey"] = userUniqueKey;
                var setupinfo = tfa.GenerateSetupCode("Superstore validation", login.username, userUniqueKey, 300, 300);
                ViewBag.BarcodeImageUrl = setupinfo.QrCodeSetupImageUrl;
                ViewBag.SetupCode       = setupinfo.ManualEntryKey;
            }
            else
            {
                message = "Invalid credential";
            }
            ViewBag.Message = message;
            ViewBag.Status  = status;
            return(View());
        }
Example #27
0
        /// <inheritdoc />
        /// <summary>
        /// Explicitly implement this interface method - which overrides the base class's implementation
        /// </summary>
        /// <param name="purpose"></param>
        /// <param name="token"></param>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        Task <bool> IUserTokenProvider <BackOfficeIdentityUser, int> .ValidateAsync(string purpose, string token, UserManager <BackOfficeIdentityUser, int> manager, BackOfficeIdentityUser user)
        {
            if (purpose == Constants.GoogleAuthenticatorProviderName)
            {
                var twoFactorAuthenticator = new TwoFactorAuthenticator();
                var database = ApplicationContext.Current.DatabaseContext.Database;
                var result   = database.Fetch <TwoFactor>(string.Format("WHERE [userId] = {0} AND [key] = '{1}' AND [confirmed] = 1",
                                                                        user.Id, Constants.GoogleAuthenticatorProviderName));
                if (result.Any() == false)
                {
                    return(Task.FromResult(false));
                }

                var key        = result.First().Value;
                var validToken = twoFactorAuthenticator.ValidateTwoFactorPIN(key, token);
                return(Task.FromResult(validToken));
            }

            /* if (purpose == Constants.YubiKeyProviderName)
             * {
             *   var yubiKeyService = new YubiKeyService();
             *   var response = yubiKeyService.Validate(token, user.Id);
             *   return Task.FromResult(response != null && response.Status == YubicoResponseStatus.Ok);
             * }*/

            return(Task.FromResult(false));
        }
Example #28
0
        public static bool ValidateTwoFactorPasscode(User user, CMSDataContext db, string passcode)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var secretKey = Get2FASecret(db);

            return(passcode?.Length == 6 && tfa.ValidateTwoFactorPIN(Get2FAUserSecret(user, secretKey), passcode));
        }
        public bool ValidatePin(string pin, string secretCode)
        {
            var tfa          = new TwoFactorAuthenticator();
            var isCorrectPin = tfa.ValidateTwoFactorPIN(secretCode, pin);

            return(isCorrectPin);
        }
Example #30
0
        public TwoFactorSetup(string appName, string appInfo, string secretCode, int timeout)
        {
            InitializeComponent();

            //generate code for the Google Authenticator app
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var    setupInfo           = tfa.GenerateSetupCode(appName, appInfo, secretCode, 300, 300); //the width and height of the Qr Code in pixels
            string qrCodeImageUrl      = setupInfo.QrCodeSetupImageUrl;                                 //  assigning the Qr code information + URL to string

            /*if qr code is downloaded succesfully, it is displayed, if there is connection error
             *  or timeout is exceeded, an error message is displayed instead*/

            byte[] data = { };
            try
            {
                WebClientWithTimeout webClient = new WebClientWithTimeout(timeout);
                data = webClient.DownloadData(qrCodeImageUrl);
                MemoryStream mem         = new MemoryStream(data);
                var          QrCodeImage = Image.FromStream(mem);
                qrcodelabel.Size  = QrCodeImage.Size;
                qrcodelabel.Text  = "";
                qrcodelabel.Image = QrCodeImage;
            }
            catch (Exception e)
            {
                qrcodelabel.Text      = "Cannot download QR code";
                qrcodelabel.ForeColor = Color.Red;
            }

            //show manual entry code
            string manualEntrySetupCode = setupInfo.ManualEntryKey;

            secretcodelabel.Text = manualEntrySetupCode;
        }
Example #31
0
        public ActionResult Login()
        {
            var username = Request["username"];
            var password = Request["password"];
            var token    = Request["token"];

            if (username == "yanick" && password == "yanick")
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                bool isCorrectPIN          = tfa.ValidateTwoFactorPIN("MY_SECRET_KEY", token);
                if (isCorrectPIN)
                {
                    ViewBag.Message = "Login and Token Correct";
                }
                else
                {
                    ViewBag.Message = "Wrong credentials and token";
                }
            }
            else
            {
                ViewBag.Message = "Wrong credentials";
            }

            return(View());
        }
Example #32
0
        public bool CheckTFA(string tfa)
        {
            BsonDocument           acc  = Projected(TFA_INTERNAL);
            TwoFactorAuthenticator tfao = new TwoFactorAuthenticator();

            return(tfao.ValidateTwoFactorPIN(acc[TFA_INTERNAL].AsString, tfa));
        }
Example #33
0
        /// <summary>
        /// 获取当前验证码
        /// </summary>
        /// <param name="tokenSecretKey">Token密钥</param>
        /// <returns></returns>
        public static string CreateGoogleCode(string tokenSecretKey)
        {
            var Authenticator = new TwoFactorAuthenticator();
            var codes         = Authenticator.GetCurrentPINs(getDecodeString(tokenSecretKey), TimeSpan.FromSeconds(30));

            return(codes[codes.Length - 1]);
        }
        protected void btnValidate_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var result = tfa.ValidateTwoFactorPIN(Request.QueryString["key"], this.txtCode.Text);

            if (result)
            {
                this.lblValidationResult.Text = this.txtCode.Text + " is a valid PIN at UTC time " + DateTime.UtcNow.ToString();
                this.lblValidationResult.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                this.lblValidationResult.Text = this.txtCode.Text + " is not a valid PIN at UTC time " + DateTime.UtcNow.ToString();
                this.lblValidationResult.ForeColor = System.Drawing.Color.Red;
            }
        }
        public void FindIterationNumber()
        {
            string secretKey = "PJWUMZKAUUFQKJBAMD6VGJ6RULFVW4ZH";
            string targetCode = "267762";

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            var mins = DateTime.UtcNow.Subtract(_epoch).TotalMinutes;

            long currentTime = 1416643820;

            for (long i = currentTime; i >= 0; i=i-60)
            {
                var result = tfa.GeneratePINAtInterval(secretKey, i, 6);
                if (result == targetCode)
                {
                    Assert.IsTrue(true);
                }
            }

            Assert.IsTrue(false);
        }