public async Task <ActionResult> EnableGoogleAuthenticator(GoogleAuthenticatorViewModel model) { if (ModelState.IsValid) { byte[] secretKey = Base32Encoder.Decode(model.SecretKey); long timeStepMatched = 0; var otp = new Totp(secretKey); if (otp.VerifyTotp(model.Code.Trim(), out timeStepMatched, new VerificationWindow(2, 2))) { var user = UserManager.FindById(User.Identity.GetUserId()); user.IsGoogleAuthenticatorEnabled = true; user.GoogleAuthenticatorSecretKey = model.SecretKey; user.TwoFactorEnabled = true; await UserManager.UpdateAsync(user); return(RedirectToAction("Index", "Manage")); } else { ModelState.AddModelError("Code", "The Code is not valid"); } } return(View(model)); }
public async Task <ActionResult> EnableTotp(EnableTotpViewModel model) { if (this.ModelState.IsValid) { var key = Base32Encoder.Decode(model.Key); var totp = new Totp(key); long timeStep; if (totp.VerifyTotp(model.Code, out timeStep, new VerificationWindow(2, 2))) { var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId()); user.EnableTotp(key); var results = await this.UserManager.UpdateAsync(user); if (results.Succeeded) { await this.SignInAsync(user, false); return(this.RedirectToAction("Index")); } foreach (var error in results.Errors) { this.ModelState.AddModelError(string.Empty, error); } } } return(this.View(model)); }
public ActionResult Enable(string secretKey, string code) { if (User == null) { ModelState.AddModelError("not-authenticated", "you are not logged in"); return(View()); } if (User.TotpSecret != null) { ModelState.AddModelError("already-enabled", "Google Authenticator is already enabled"); return(View()); } var secretKeyBytes = Base32Encoder.Decode(secretKey); if (!VerifyCode(secretKeyBytes, code)) { ModelState.AddModelError("wrong-code", "The code is not valid"); ViewBag.SecretKey = secretKey; ViewBag.BarcodeUrl = GenerateBarcodeUrl(secretKeyBytes); return(View()); } User.TotpSecret = secretKey; Session.TotpAuthenticated = true; return(RedirectHome()); }
public ActionResult Verify(string code) { if (User == null) { ModelState.AddModelError("not-authenticated", "you are not logged in"); return(View()); } if (User.TotpSecret == null) { ModelState.AddModelError("not-enabled", "Google Authenticator is not enabled"); return(View()); } var secretKeyBytes = Base32Encoder.Decode(User.TotpSecret); if (!VerifyCode(secretKeyBytes, code)) { ModelState.AddModelError("wrong-code", "the code that you entered is not valid"); return(View()); } Session.TotpAuthenticated = true; return(RedirectHome()); }
public async Task <ActionResult> EnableGoogleAuthenticator(GoogleAuthenticatorViewModel model) { if (ModelState.IsValid) { byte[] secretKey = Base32Encoder.Decode(model.SecretKey); long timeStepMatched = 0; var otp = new Totp(secretKey); if (otp.VerifyTotp(model.Code, out timeStepMatched, new VerificationWindow(2, 2))) { var uid = User.Identity.GetUserId(); var user = await UserManager.FindByIdAsync(uid); var googleAuthClaim = UserManager.GetClaims(uid).FirstOrDefault(x => x.Type == Claims.GoogleAuthSecret); if (googleAuthClaim != null) { await UserManager.RemoveClaimAsync(uid, new Claim(Claims.GoogleAuthSecret, model.SecretKey)); } await UserManager.AddClaimAsync(uid, new Claim(Claims.GoogleAuthSecret, model.SecretKey)); return(RedirectToAction("Index", "Manage")); } else { ModelState.AddModelError("Code", "The Code is not valid"); } } return(View(model)); }
public async Task <ActionResult> EnableGoogleAuthenticator(GoogleAuthenticatorViewModel model) { string returnUrl = TempData["returnUrl"] == null ? "" : TempData["returnUrl"].ToString(); string userName = TempData["returnUrl"] == null ? "" : TempData["userName"].ToString(); if (ModelState.IsValid) { byte[] secretKey = Base32Encoder.Decode(model.SecretKey); long timeStepMatched = 0; var otp = new Totp(secretKey); if (otp.VerifyTotp(model.Code, out timeStepMatched, new VerificationWindow(2, 2))) { var user = await UserManager.FindByNameAsync(userName); user.IsGoogleAuthenticatorEnabled = true; user.TwoFactorEnabled = true; user.GoogleAuthenticatorSecretKey = model.SecretKey; await UserManager.UpdateAsync(user); return(Redirect(returnUrl)); } else { ModelState.AddModelError("Code", "The Code is not valid"); } } TempData["returnUrl"] = returnUrl; return(View(model)); }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.ColoredConsole() .CreateLogger(); Console.Write("Input key: "); string key = Console.ReadLine(); var decodedKey = Base32Encoder.Decode(key); var otp = new Totp(decodedKey); var task = Task.Factory.StartNew(() => { while (true) { otp = new Totp(decodedKey); Log.Information(otp.ComputeTotp()); Thread.Sleep(1000); } }, TaskCreationOptions.LongRunning); Task.WaitAll(task); Console.ReadKey(); }
public Task <bool> ValidateAsync(string purpose, string token, UserManager <CustomUser, int> manager, CustomUser user) { var decodedKey = Base32Encoder.Decode(user.AuthenticatorKey); var otp = new Totp(decodedKey); var valid = otp.VerifyTotp(token, out _, new VerificationWindow(2, 2)); return(Task.FromResult(valid)); }
public void decoding(string expectedResult, string input) { var arrayExpectedResult = Encoding.ASCII.GetBytes(expectedResult); var result = Base32Encoder.Decode(input, true); Assert.Equal(result, arrayExpectedResult); }
public Task <bool> ValidateAsync(string purpose, string token, UserManager <UserAccount, string> manager, UserAccount user) { long timeStepMatched = 0; Totp totp = new Totp(Base32Encoder.Decode(user.GoogleAuthenticatorSecretKey)); bool IsValid = totp.VerifyTotp(token, out timeStepMatched, new VerificationWindow(2, 2)); return(Task.FromResult(IsValid)); }
public Task <bool> ValidateAsync(string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user) { long timeStepMatched; var otp = new Totp(Base32Encoder.Decode(user.PhoneNumber)); var valid = otp.VerifyTotp(token, out timeStepMatched, new VerificationWindow(2, 2)); return(Task.FromResult(valid)); }
public Task <bool> ValidateAsync(string purpose, string token, UserManager <User> manager, User user) { var otp = new Totp(Base32Encoder.Decode(user.AuthenticatorKey)); long timeStepMatched; var valid = otp.VerifyTotp(token, out timeStepMatched, new VerificationWindow(2, 2)); return(Task.FromResult(valid)); }
private static Totp TotpFromUrl(Uri url) { int digits; var collection = ParseAndValidateQueryString(url, out digits); if (!ValidateQueryStringFields(collection, UrlConstants.AlgorithmParameter, UrlConstants.DigitsParameter, UrlConstants.PeriodParameter, UrlConstants.SecretParameter)) { throw new ArgumentException("Invalid parameter in query string"); } OtpHashMode algorithm = OtpHashMode.Sha1; if (collection.AllKeys.Contains(UrlConstants.AlgorithmParameter)) { var algorithmRaw = collection[UrlConstants.AlgorithmParameter]; if (!Enum.TryParse <OtpHashMode>(algorithmRaw, true, out algorithm)) { throw new ArgumentException(string.Format("Invalid Algorithm {0}", algorithmRaw)); } } int period = 30; // the spec indicates that 30 is the default int tempPeriod; if (collection.AllKeys.Contains(UrlConstants.PeriodParameter)) { if (int.TryParse(collection[UrlConstants.PeriodParameter], out tempPeriod)) { if (tempPeriod < 1) { throw new ArgumentException(string.Format("Invalid Period {0}, must be at least 1", tempPeriod)); } else { period = tempPeriod; } } else { throw new ArgumentException(string.Format("Invalid digits {0}, must be a number", collection[UrlConstants.DigitsParameter])); } } var key = Base32Encoder.Decode(collection[UrlConstants.SecretParameter]); return(new Totp(key, step: period, mode: algorithm, totpSize: digits)); }
static void Main(string[] args) { var preSecret = "1234567890"; //for (int i = 0; i < 10; i++) //{ // Console.WriteLine(HashedOneTimePassword.GeneratePassword(preSecret, i)); //} //long[] seconds = new long[] { 59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000 }; //foreach (var second in seconds) //{ // Console.WriteLine(TimeBasedOneTimePassword.GetPassword(preSecret, TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(second), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8)); //} var enc = new Base32Encoder(); while (true) { // feed this into GA to create a new Application string secret = enc.Encode(Encoding.ASCII.GetBytes(preSecret)); Console.WriteLine(secret); //this will get the preSecret key back ... var preSecretBack = Encoding.UTF8.GetString ( enc.Decode(secret)); Console.WriteLine(preSecretBack); // this would be a VALID password right now Console.WriteLine("Valid pw: " + TimeBasedOneTimePassword.GetPassword(preSecret)); Console.WriteLine("Enter your password: "******"") { break; } // this will check the entered password (possibly from GA) ... if (TimeBasedOneTimePassword.IsValid(preSecret, password)) { Console.WriteLine("Success!"); } else { Console.WriteLine("ERROR!"); } } return; }
public static bool VerifyGoogleTwoFactorCode(string key, string code) { try { byte[] secretKey = Base32Encoder.Decode(key); long timeStepMatched = 0; var otp = new Totp(secretKey); return(otp.VerifyTotp(code, out timeStepMatched, new VerificationWindow(5, 5))); } catch {} return(false); }
public static bool VerifyOtpCode(string privateKey, string code) { try { var otp = new Totp(Base32Encoder.Decode(privateKey)); return(otp.VerifyTotp(code, out _, VerificationWindow.RfcSpecifiedNetworkDelay)); } catch (Exception) { return(false); } }
public async Task <HttpResponseMessage> VerifyToken(string token, string phoneNumber) { long timeStepMatched = 0; var user = UserManager.Users.First(u => u.PhoneNumber == phoneNumber); var otp = new Totp(Base32Encoder.Decode(user.SinchAuthSecretKey)); bool valid = otp.VerifyTotp(token, out timeStepMatched, new VerificationWindow(2, 2)); if (!valid) { return(new HttpResponseMessage(HttpStatusCode.Forbidden)); } OneTimeLinks.AddLink(user.Id); return(new HttpResponseMessage(HttpStatusCode.OK)); }
public static bool VerifyGoogleTwoFactorCode(string key, string code) { try { var secretKey = Base32Encoder.Decode(key); var otp = new Totp(secretKey); long _; return(otp.VerifyTotp(code, out _, new VerificationWindow(5, 5))); } catch (Exception ex) { Log.Exception("[VerifyGoogleTwoFactorCode] Verification Failed", ex); } return(false); }
public Task <bool> ValidateAsync( string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user) { long timeStepMatched = 0; byte[] decodedKey = Base32Encoder.Decode(user.GoogleAuthenticatorSecretKey); var otp = new Totp(decodedKey); bool valid = otp.VerifyTotp( token, out timeStepMatched, new VerificationWindow(2, 2)); return(Task.FromResult(valid)); }
/// <summary> /// Verifies the users short code. /// </summary> /// <param name="manager">The manager.</param> /// <param name="codeType">Type of the code.</param> /// <param name="userid">The userid.</param> /// <param name="code">The code.</param> protected async Task <bool> VerifyUserTwoFactorCodeAsync(TwoFactorComponent component, TwoFactorType twofactorType, string userid, string code, string code2 = "") { if (string.IsNullOrEmpty(code)) { return(false); } var user = await UserManager.FindByIdAsync(userid); if (user == null) { return(false); } var twofactorMethod = user.TwoFactor.FirstOrDefault(x => x.Component == component && x.Type == twofactorType); if (twofactorMethod == null) { return(false); } if (twofactorType == TwoFactorType.GoogleCode) { byte[] secretKey = Base32Encoder.Decode(twofactorMethod.Data); long timeStepMatched = 0; var otp = new Totp(secretKey); return(otp.VerifyTotp(code, out timeStepMatched, new VerificationWindow(2, 2))); } if (twofactorType == TwoFactorType.Password) { return(await UserManager.CheckPasswordAsync(user, code)); } if (twofactorType == TwoFactorType.Question) { return(twofactorMethod.Data2 == code && twofactorMethod.Data4 == code2); } if (twofactorType == TwoFactorType.PinCode) { return(twofactorMethod.Data == code); } return(await UserManager.VerifyTwoFactorTokenAsync(userid, twofactorType.ToString(), code)); }
public Task <bool> ValidateAsync(string purpose, string token, UserManager <ApplicationUser, string> manager, ApplicationUser user) { long timeStepMatched; var claim = user.Claims.FirstOrDefault(x => x.ClaimType == Claims.GoogleAuthSecret); if (claim == null || claim.ClaimValue.IsEmpty()) { return(Task.FromResult(false)); } var otp = new Totp(Base32Encoder.Decode(claim.ClaimValue)); // TODO: move window parameters to config bool valid = otp.VerifyTotp(token, out timeStepMatched, new VerificationWindow(2, 2)); return(Task.FromResult(valid)); }
public async Task <ActionResult> EnableGoogleAuthenticator(VerifyCodeViewModel model) { byte[] secretKey = Base32Encoder.Decode(model.SecretKey); long timeStepMatched = 0; var otp = new Totp(secretKey); if (otp.VerifyTotp(model.Code, out timeStepMatched, new VerificationWindow(2, 2))) { //var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); var userd = Session["userId"]; var user = await UserManager.FindByIdAsync(userd.ToString()); //var userName = db.Users.Where(c => c.Id.Equals(user)).Select(d => d.Email).First(); user.IsGoogleAuthenticatorEnabled = true; user.GoogleAuthenticatorSecretKey = model.SecretKey; await UserManager.UpdateAsync(user); //var provider = Session["Provider"]; //var returnUrl = Session["ReturnUrl"]; //var RememberMe = Session["RememberMe"]; //model.Provider = provider.ToString(); var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent : model.RememberMe, rememberBrowser : model.RememberBrowser); switch (result) { case SignInStatus.Success: return(RedirectToLocal(model.ReturnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid code."); return(View(model)); } } else { ModelState.AddModelError("Code", "The Code is not valid"); } return(View(model)); }
public string SetTwoStepVerif(string verifKey) { byte[] secretKey = Base32Encoder.Decode(Session["secretKey"].ToString()); long timeStepMatched = 0; var totp = new Totp(secretKey); var message = ""; if (totp.VerifyTotp(verifKey, out timeStepMatched, new VerificationWindow(1, 1))) { message = "成功"; } else { message = "失敗"; } return(message); }
public void TestGoogleAuthenticator() { var secretBase32 = "ABCDABCD33ABCDABCD44"; var secret = Base32Encoder.Decode(secretBase32); var appIdentity = "VitaBookStore"; var current = GoogleAuthenticatorUtil.GetCurrentCounter(); for (int i = -1; i <= 4; i++) { var passcode = GoogleAuthenticatorUtil.GeneratePasscode(secret, current + i); Trace.WriteLine("Passcode: " + passcode); } //Paste this URL into browser to see QR image var url = GoogleAuthenticatorUtil.GetQRUrl(appIdentity, secretBase32); Trace.WriteLine("QR URL: " + url); // Trace.WriteLine("Key for phone app, manual entry: " + secretBase32); }
public ActionResult AuthKey(int id, string key, string code) { var ctx = new DataAccess.SirCoNominaDataContext(); var emp = ctx.Empleados.Where(i => i.idempleado == id).Single(); byte[] secretKey = Base32Encoder.Decode(key); long timeStepMatched = 0; var otp = new Totp(secretKey); if (otp.VerifyTotp(code, out timeStepMatched, new VerificationWindow(2, 2))) { emp.authkey = key; ctx.SaveChanges(); return(Content("SUCCESS")); } return(Content("FAILED")); }
public async Task Confirm(GoogleAuthConfirmationModel confirmationModel, string userId) { Logger.Debug(CurrentClassName, nameof(Confirm), $"Decoding secret key '{confirmationModel.SecretKey}'"); var secretKey = Base32Encoder.Decode(confirmationModel.SecretKey); long timeStepMatched = 0; Logger.Debug(CurrentClassName, nameof(Confirm), $"Generating TOTP-key"); var otp = new Totp(secretKey); if (otp.VerifyTotp(confirmationModel.InputCode, out timeStepMatched)) { var user = await Repository.FindById(userId); user.IsGoogleAuthenticatorEnabled = true; user.GoogleAuthenticatorSecretKey = confirmationModel.SecretKey; await Repository.UpdateUser(user); } throw new Exception("Code is not valid"); }
public async Task <ActionResult> SendCode(string returnUrl, bool rememberMe) { var userId = await SignInManager.GetVerifiedUserIdAsync(); var user = UserManager.FindById(userId); if (userId == null) { return(View("Error")); } var model = new SendCodeViewModel() { SelectedProvider = user.SinchAuthSecretKey, ReturnUrl = returnUrl }; var otp = new Totp(Base32Encoder.Decode(user.SinchAuthSecretKey)); var date = DateTime.UtcNow; var code = otp.ComputeTotp(date); return(View(model)); }
protected void Verify(object sender, EventArgs e) { var secretBytes = Base32Encoder.Decode(SharedKeyField.Value); var otp = new Totp(secretBytes); var providedCode = CodeVerification.Text; var correctCode = otp.VerifyTotp(providedCode.Trim(), out _, new VerificationWindow(2, 2)); if (correctCode) { var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); var user = manager.FindById(Convert.ToInt32(User.Identity.GetUserId())); user.TwoFactorEnabled = true; user.AuthenticatorKey = SharedKeyField.Value; manager.Update(user); Response.Redirect("/Account/TwoFactorAuthentication", true); } else { FailureText.Text = "Invalid verification code."; ErrorMessage.Visible = true; } }
public async Task <ActionResult> EnableGoogleAuthenticator(GoogleAuthenticatorViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var secretKey = Base32Encoder.Decode(model.SecretKey); long timeStepMatched; var otp = new Totp(secretKey); if (otp.VerifyTotp(model.Code, out timeStepMatched, new VerificationWindow(2, 2))) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); user.PhoneNumberConfirmed = true; user.PhoneNumber = model.SecretKey; await UserManager.UpdateAsync(user); return(RedirectToAction("Index", "Manage")); } ModelState.AddModelError("Код", "Неправильный код"); return(View(model)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager <EformUserManager>(); var user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("The user name or password is incorrect.", "The user name or password is incorrect."); return; } // get role var role = userManager.GetRolesAsync(user.Id).Result?.FirstOrDefault(); // TwoFactor check var requestData = await context.Request.ReadFormAsync(); var psk = user.GoogleAuthenticatorSecretKey; var code = requestData.Get("code"); var isTwoFactorAuthForced = SettingsHelper.GetTwoFactorAuthForceInfo(); if (user.TwoFactorEnabled || isTwoFactorAuthForced) { // check input params if (string.IsNullOrEmpty(psk) || string.IsNullOrEmpty(code)) { context.SetError("PSK or code is empty", "PSK or code is empty"); return; } if (psk != user.GoogleAuthenticatorSecretKey) { context.SetError("PSK is invalid", "PSK is invalid"); return; } // check code long timeStepMatched = 0; var otp = new Totp(Base32Encoder.Decode(user.GoogleAuthenticatorSecretKey)); var isCodeValid = otp.VerifyTotp(code, out timeStepMatched, new VerificationWindow(1, 1)); if (!isCodeValid) { context.SetError("Invalid code", "Invalid code"); return; } // update user entity if (!user.IsGoogleAuthenticatorEnabled) { user.IsGoogleAuthenticatorEnabled = true; var updateResult = userManager.UpdateAsync(user).Result; if (!updateResult.Succeeded) { context.SetError("PSK or code is empty", "PSK or code is empty"); return; } } } var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); var properties = CreateProperties(user, role); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public static byte[] ToBytes(string text) { Base32Encoder _encoder = new Base32Encoder(); byte[] result = null; try { result = _encoder.Decode(text); } catch (Exception ex) { throw ex; } return result; }
public async Task <ActionResult> EnableAuthenticator(EnableAuthenticatorViewModel viewModel) { var userId = User.Identity.GetUserId(); var user = await UserManager.FindByIdAsync(userId); if (user == null) { return(HttpNotFound($"Unable to load user with ID '{userId}'.")); } if (!ModelState.IsValid) { // If hidden fields in view risky then delete them // Following code fetched them in case of failded post var vm = await GetEnableAuthenticatorViewModelAsync(); return(View("EnableAuthenticator", vm)); } // Strip spaces and hypens var verificationCode = viewModel.Code.Replace(" ", string.Empty).Replace("-", string.Empty); //var is2faTokenValid = await UserManager.VerifyTwoFactorTokenAsync( // user, UserManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); byte[] authenticatorKey = Base32Encoder.Decode(viewModel.UnformattedAuthenticatorKey); long timeStepMatched = 0; var otp = new Totp(authenticatorKey); var is2faTokenValid = otp.VerifyTotp(viewModel.Code, out timeStepMatched, new VerificationWindow(2, 2)); if (!is2faTokenValid) { // If hidden fields in view risky then delete them // Following code fetched them in case of failded post var vm = await GetEnableAuthenticatorViewModelAsync(); ModelState.AddModelError("", "Verification code is invalid."); return(View("EnableAuthenticator", vm)); } await _userManager.SetTwoFactorEnabledAsync(user.Id, true); //var userId = await _userManager.GetUserIdAsync(user); //Logger.LogInfo($"User with ID '{userId}' has enabled 2FA with an authenticator app."); ViewBag.StatusMessage = "Your authenticator app has been verified."; //if (await _userManager.CountRecoveryCodesAsync(user) == 0) //{ // var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); // RecoveryCodes = recoveryCodes.ToArray(); // return RedirectToPage("./ShowRecoveryCodes"); //} //else //{ // return RedirectToPage("./TwoFactorAuthentication"); //} return(RedirectToAction("EnableAuthenticator")); //return new EmptyResult(); }