public async Task <ActionResult> Send() { string input = null; // If not data came in, then return if (this.Request.Body == null) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict))); } // Read the input claims from the request body using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { input = await reader.ReadToEndAsync(); } // Check input content value if (string.IsNullOrEmpty(input)) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict))); } // Convert the input string into InputClaimsModel object InputClaimsModel inputClaims = InputClaimsModel.Parse(input); if (inputClaims == null) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict))); } if (string.IsNullOrEmpty(inputClaims.email)) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Email address is missing.", HttpStatusCode.Conflict))); } try { Console.WriteLine($"Sending email to '{inputClaims.email}'"); var totp = new Totp(Encoding.UTF8.GetBytes(inputClaims.email + AppSettings.TOTPSecret), step: AppSettings.TOTPStep, totpSize: 6); string code = totp.ComputeTotp(); string htmlTemplate = System.IO.File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Template.html")); MailMessage mailMessage = new MailMessage(); mailMessage.To.Add(inputClaims.email); mailMessage.From = new MailAddress(AppSettings.SMTPFromAddress); mailMessage.Subject = AppSettings.SMTPSubject; mailMessage.Body = string.Format(htmlTemplate, inputClaims.email, code); mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(AppSettings.SMTPServer, AppSettings.SMTPPort); smtpClient.Credentials = new NetworkCredential(AppSettings.SMTPUsername, AppSettings.SMTPPassword); smtpClient.EnableSsl = AppSettings.SMTPUseSSL; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Send(mailMessage); } catch (Exception ex) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Internal error: " + ex.Message, HttpStatusCode.Conflict))); } return(this.Ok("Sent")); }
static void Main(string[] args) { Console.WriteLine("Yooooooooooooo! Add a TOTP or retrieve a value for one."); Credentials.loadCredentials(); try { using (StreamReader sr = new StreamReader("basicTOTPs.db")) { try { String line; while (!sr.EndOfStream) { // read from file line = sr.ReadLine(); String[] split = line.Split(DELIMITER); Authenticator anAuthenticator = new Authenticator(); anAuthenticator.description = Credentials.decrypt(split[0]); anAuthenticator.secret = Credentials.decrypt(split[1]); Program.authenticators.Add(anAuthenticator); } } catch (IOException e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } } catch (FileNotFoundException) { Console.WriteLine("Couldn't find an authenticator file. If this is your first time running this, no worries."); Console.WriteLine("If you were expecting to load your authenticators, check to see if the file basicTOTPs.db is located in the same directory this program is running from."); } Boolean donezo = false; while (!donezo) { Console.WriteLine("Possible commands: add, list, help, exit"); String command = Console.ReadLine(); command = command.Trim(); switch (command) { case "add": Authenticator authToAdd = new Authenticator(); Console.WriteLine("Cool beans. Give me a name for the account/service you are going to add:"); authToAdd.description = Console.ReadLine(); Console.WriteLine("Okay, gimme the secret."); String secretToAdd = Console.ReadLine(); secretToAdd = Regex.Replace(secretToAdd, @"\s", ""); authToAdd.secret = secretToAdd; authenticators.Add(authToAdd); using (StreamWriter sw = new StreamWriter("basicTOTPs.db", true)) { sw.Write(Credentials.encrypt(authToAdd.description) + DELIMITER); sw.WriteLine(Credentials.encrypt(authToAdd.secret)); } Console.WriteLine("Great! You probably should hit list now to get a value to confirm your code with your service."); break; case "list": foreach (Authenticator auth in authenticators) { Totp atotp = new Totp(Base32Encoding.ToBytes(auth.secret)); String value = atotp.ComputeTotp(); Console.WriteLine(auth.description + ": " + value); } break; case "help": Console.WriteLine("add - use this to add an authenticator. authenticators are saved to basicTOTPs.db, encrypted using a key saved in your Credential Manager. Right now only supports the default TOTP implementation (SHA-1, 6 digits)"); Console.WriteLine("list - use this to generate values for all your authenticators. authenticators used are from basicTOTP, decrypted using a key saved in your Credential Manager. No time is listed for the time remaining for code validity."); Console.WriteLine("help - you are here!"); Console.WriteLine("exit - gracefully depart from this application. kudos to you!"); break; case "exit": Console.WriteLine("See ya!"); donezo = true; break; default: Console.WriteLine("Sorry, I don't understand that command :("); break; } } }
public async Task <ActionResult> Verify() { string input = null; // If not data came in, then return if (this.Request.Body == null) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict))); } // Read the input claims from the request body using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { input = await reader.ReadToEndAsync(); } // Check input content value if (string.IsNullOrEmpty(input)) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict))); } // Convert the input string into InputClaimsModel object InputClaimsModel inputClaims = InputClaimsModel.Parse(input); if (inputClaims == null) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict))); } try { byte[] secretKey = Convert.FromBase64String(this.DecryptAndBase64(inputClaims.secretKey)); Totp totp = new Totp(secretKey); long timeStepMatched; // Verify the TOTP code provided by the users bool verificationResult = totp.VerifyTotp( inputClaims.totpCode, out timeStepMatched, VerificationWindow.RfcSpecifiedNetworkDelay); if (!verificationResult) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("The verification code is invalid.", HttpStatusCode.Conflict))); } // Using the input claim 'timeStepMatched', we check whether the verification code has already been used. // For sign-up, the 'timeStepMatched' input claim is null and should not be evaluated // For sign-in, the 'timeStepMatched' input claim contains the last time a code matched (from the user profile), and if equal to // the last time matched from the verify totp step, we know this code has already been used and can reject if (!string.IsNullOrEmpty(inputClaims.timeStepMatched) && (inputClaims.timeStepMatched).Equals(timeStepMatched.ToString())) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("The verification code has already been used.", HttpStatusCode.Conflict))); } B2CResponseModel output = new B2CResponseModel(string.Empty, HttpStatusCode.OK) { timeStepMatched = timeStepMatched.ToString() }; return(Ok(output)); } catch (Exception ex) { return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel($"General error (REST API): {ex.Message}", HttpStatusCode.Conflict))); } }
internal Response GetLoginsHandler(Request req) { if (!req.TryDecrypt()) { return(new ErrorResponse(req, ErrorType.CannotDecryptMessage)); } var msg = req.Message; var id = msg.GetString("id"); var url = msg.GetString("url"); var submitUrl = msg.GetString("submitUrl"); Uri hostUri; Uri submitUri; if (!string.IsNullOrEmpty(url)) { hostUri = new Uri(url); } else { return(new ErrorResponse(req, ErrorType.NoUrlProvided)); } if (!string.IsNullOrEmpty(submitUrl)) { submitUri = new Uri(submitUrl); } else { submitUri = hostUri; } var resp = req.GetResponse(); resp.Message.Add("id", id); var items = FindMatchingEntries(url, null); if (items.ToList().Count > 0) { bool filter(PwEntry e) { var c = _ext.GetEntryConfig(e); var title = e.Strings.ReadSafe(PwDefs.TitleField); var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField); if (c != null) { return((title != hostUri.Host && entryUrl != hostUri.Host && !c.Allow.Contains(hostUri.Host)) || (submitUri.Host != null && !c.Allow.Contains(submitUri.Host) && submitUri.Host != title && submitUri.Host != entryUrl)); } return((title != hostUri.Host && entryUrl != hostUri.Host) || (submitUri.Host != null && title != submitUri.Host && entryUrl != submitUri.Host)); } var configOpt = new ConfigOpt(_host.CustomConfig); var config = _ext.GetConfigEntry(true); var autoAllowS = config.Strings.ReadSafe("Auto Allow"); var autoAllow = !string.IsNullOrWhiteSpace(autoAllowS); autoAllow = autoAllow || configOpt.AlwaysAllowAccess; var needPrompting = from e in items where filter(e.entry) select e; if (needPrompting.ToList().Count > 0 && !autoAllow) { var win = _host.MainWindow; using (var f = new AccessControlForm()) { win.Invoke((MethodInvoker) delegate { f.Icon = win.Icon; f.Plugin = _ext; f.Entries = (from e in items where filter(e.entry) select e.entry).ToList(); //f.Entries = needPrompting.ToList(); f.Host = submitUri.Host ?? hostUri.Host; f.Load += delegate { f.Activate(); }; f.ShowDialog(win); if (f.Remember && (f.Allowed || f.Denied)) { foreach (var e in needPrompting) { var c = _ext.GetEntryConfig(e.entry) ?? new EntryConfig(); var set = f.Allowed ? c.Allow : c.Deny; set.Add(hostUri.Host); if (submitUri.Host != null && submitUri.Host != hostUri.Host) { set.Add(submitUri.Host); } _ext.SetEntryConfig(e.entry, c); } } if (!f.Allowed) { items = items.Except(needPrompting); } }); } } foreach (var entryDatabase in items) { string entryUrl = String.Copy(entryDatabase.entry.Strings.ReadSafe(PwDefs.UrlField)); if (String.IsNullOrEmpty(entryUrl)) { entryUrl = entryDatabase.entry.Strings.ReadSafe(PwDefs.TitleField); } entryUrl = entryUrl.ToLower(); entryDatabase.entry.UsageCount = (ulong)LevenshteinDistance(submitUri.ToString().ToLower(), entryUrl); } var itemsList = items.ToList(); if (configOpt.SpecificMatchingOnly) { itemsList = (from e in itemsList orderby e.entry.UsageCount ascending select e).ToList(); ulong lowestDistance = itemsList.Count > 0 ? itemsList[0].entry.UsageCount : 0; itemsList = (from e in itemsList where e.entry.UsageCount == lowestDistance orderby e.entry.UsageCount select e).ToList(); } if (configOpt.SortResultByUsername) { var items2 = from e in itemsList orderby e.entry.UsageCount ascending, _ext.GetUserPass(e)[0] ascending select e; itemsList = items2.ToList(); } else { var items2 = from e in itemsList orderby e.entry.UsageCount ascending, e.entry.Strings.ReadSafe(PwDefs.TitleField) ascending select e; itemsList = items2.ToList(); } var entries = new JArray(itemsList.Select(item => { var up = _ext.GetUserPass(item); var TotpSettings = _ext.GetTotpSettings(item.entry); JArray fldArr = null; var fields = GetFields(configOpt, item); if (fields != null) { fldArr = new JArray(fields.Select(f => new JObject { { f.Key, f.Value } })); } string fldTotp = null; if (TotpSettings != null) { fldTotp = Totp.Generate(TotpSettings); } return(new JObject { { "name", item.entry.Strings.ReadSafe(PwDefs.TitleField) }, { "login", up[0] }, { "password", up[1] }, { "uuid", item.entry.Uuid.ToHexString() }, { "totp", fldTotp }, { "stringFields", fldArr } }); })); resp.Message.Add("count", itemsList.Count); resp.Message.Add("entries", entries); if (itemsList.Count > 0) { var names = (from e in itemsList select e.entry.Strings.ReadSafe(PwDefs.TitleField)).Distinct(); var n = String.Join("\n ", names); if (configOpt.ReceiveCredentialNotification) { _ext.ShowNotification(String.Format("{0}: {1} is receiving credentials for:\n {2}", req.GetString("id"), hostUri.Host, n)); } } return(resp); } resp.Message.Add("count", 0); resp.Message.Add("entries", new JArray()); return(resp); }
public string GenerateCode() { var totp = new Totp(Encoding.UTF8.GetBytes(secretKey), step: 5 * 60); return(totp.ComputeTotp()); }
public Token(Totp totp, StoredToken token) { this._totp = totp; this._storedToken = token; }
static void Main() { var skins = new List <Skin>(); var totpgen = new Totp(Base32.Base32Encoder.Decode(ConfigurationManager.AppSettings["SecretCode"])); HtmlWeb oWeb = new HtmlWeb(); HtmlDocument doc = oWeb.Load("https://hawkstore.com.ar/tienda/?orderby=price"); var cantPages = doc.DocumentNode.CssSelect("a.page-numbers").Count(); for (var j = 1; j <= cantPages; j++) { if (j != 1) { doc = oWeb.Load($"https://hawkstore.com.ar/tienda/page/{j}/?orderby=price"); } List <HtmlNode> skinName = doc.DocumentNode.CssSelect("h2.woocommerce-loop-product__title").ToList(); List <HtmlNode> skinPrice = doc.DocumentNode.CssSelect("span.price").ToList(); for (var i = 0; i < skinName.Count(); i++) { var _price = skinPrice[i].InnerText .Replace("$", string.Empty) .Replace(",", string.Empty) .Split('.'); var intPrice = int.Parse(_price[0]); if (!(skins.Any(x => x.Name == skinName[i].InnerHtml && x.Price == intPrice))) { skins.Add(new Skin { Name = skinName[i].InnerHtml, Price = intPrice, sales = 0, promedio = 0, dolar = 0, obs = "", SalesSkins = new List <SalesSkin>() }); } } } foreach (var skin in skins) { for (var i = 1; i < 6; i++) { var bitSkin = WebRequest.Create($"https://bitskins.com/api/v1/get_sales_info/?api_key={ConfigurationManager.AppSettings["APIKey"]}&code={totpgen.ComputeTotp()}&market_hash_name={skin.Name}&page={i}"); bitSkin.Method = "GET"; var responseObj = (HttpWebResponse)bitSkin.GetResponse(); using (var stream = responseObj.GetResponseStream()) { var sr = new StreamReader(stream); var result = new JavaScriptSerializer().Deserialize <DevolSkin>(sr.ReadToEnd()); sr.Close(); foreach (var sale in result.data.sales) { sale.price = sale.price.Trim('0').Replace('.', ','); if (sale.price[sale.price.Length - 1] == ',') { sale.price = sale.price.Replace(",", string.Empty); } sale.decimalPrice = decimal.Parse(sale.price) * (decimal)0.908; skin.SalesSkins.Add(sale); } } Thread.Sleep(125); } } var date = DateTime.Now; foreach (var skin in skins) { var promedioVenta = (decimal)0; var promedio = (decimal)0; foreach (var sale in skin.SalesSkins) { promedioVenta += decimal.Parse(sale.price); promedio += sale.decimalPrice; DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds(sale.sold_at).ToLocalTime(); if ((date - dtDateTime).TotalDays < 15) { skin.sales++; } } if (skin.SalesSkins.Count > 0) { skin.promedioVenta = Math.Round((promedioVenta / skin.SalesSkins.Count), 2); skin.promedio = Math.Round((promedio / skin.SalesSkins.Count), 2); skin.dolar = Math.Round((skin.Price / skin.promedio), 2); } else { skin.dolar = 0; skin.obs = "Sin ventas en BitSkins"; } } var wb = new XLWorkbook(); var ws = wb.Worksheets.Add("Skins en venta"); var headers = new List <string> { "Skin", "Precio AR$", "Promedio U$D", "U$D a recibir", "Precio por dolar", "Cant. Ventas en 15 días", "Observaciones" }; for (var i = 0; i < skins.Count; i++) { ws.Cell(i + 2, 1).Value = skins[i].Name; ws.Cell(i + 2, 2).Value = skins[i].Price; ws.Cell(i + 2, 3).Value = skins[i].promedioVenta; ws.Cell(i + 2, 4).Value = skins[i].promedio; ws.Cell(i + 2, 5).Value = skins[i].dolar; ws.Cell(i + 2, 6).Value = skins[i].sales; ws.Cell(i + 2, 7).Value = skins[i].obs; ws.Cell($"A{i + 2}").Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right); if (skins[i].dolar == 0) { for (var j = 1; j <= headers.Count; j++) { ws.Cell(i + 2, j).Style.Fill.BackgroundColor = XLColor.FromArgb(249, 81, 81); } } else if (skins[i].dolar < 65) { for (var j = 1; j <= headers.Count; j++) { ws.Cell(i + 2, j).Style.Fill.BackgroundColor = XLColor.FromArgb(255, 240, 124); } } } for (var i = 0; i < headers.Count; i++) { ws.Cell(1, i + 1).Value = headers[i]; ws.Cell(1, i + 1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center); ws.Column(i + 1).AdjustToContents(); } wb.SaveAs(@"E:\Documentos\DolarSkins.xlsx"); }
public static string GenerateTotpCode(int step = 30) { var otp = new Totp(rfcSecret, step); return(otp.ComputeTotp()); }
public static bool VerifyTotpCode(string totpCode, int step = 30) { var otp = new Totp(rfcSecret, step); return(otp.VerifyTotp(totpCode, out long timeStepMatched)); }
/// <summary> /// Verify OTP /// </summary> /// <param name="key"></param> /// <param name="otp"></param> /// <param name="step"></param> /// <param name="mode"></param> /// <param name="totpSize"></param> /// <param name="timeCorrection"></param> /// <returns></returns> public static bool IsVerify(string key, string otp, int step = 30, OtpHashMode mode = OtpHashMode.Sha1, int totpSize = 8, TimeCorrection timeCorrection = null) { Totp otpCalc = new Totp(Encoding.UTF8.GetBytes(key), step, OtpHashMode.Sha1, totpSize, timeCorrection); return(otpCalc.VerifyTotp(DateTime.Now, otp, out long timestemp)); }
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 var otp = new Totp(Base32Encoder.Decode(user.GoogleAuthenticatorSecretKey)); var isCodeValid = otp.VerifyTotp(code, out long timeStepMatched, new VerificationWindow(5, 5)); 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); // Add custom claims if (!user.Locale.IsNullOrEmpty()) { oAuthIdentity.AddClaim(new Claim("locale", user.Locale)); cookiesIdentity.AddClaim(new Claim("locale", user.Locale)); } var properties = CreateProperties(user, role); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
/// <summary> /// Tạo OTP /// </summary> /// <param name="key">Key-Mã object (id,guid)</param> /// <param name="step">Mã OTP sẽ được tạo mới sau [step] giây </param> /// <param name="mode">Các kiểu mã hóa</param> /// <param name="totpSize">Chiều dài mã OTP</param> /// <param name="timeCorrection">Thời gian</param> /// <returns></returns> public static string GenerateOtpCode(string key, int step = 30, OtpHashMode mode = OtpHashMode.Sha1, int totpSize = 8, TimeCorrection timeCorrection = null) { Totp otpCalc = new Totp(Encoding.UTF8.GetBytes(key), step, OtpHashMode.Sha1, totpSize, timeCorrection); return(otpCalc.ComputeTotp(DateTime.Now)); }
internal static string GetTwoFactorCode() { Totp totpgen = new Totp(Base32.Decode(AccountData.GetSecret())); return(totpgen.ComputeTotp()); }
public static string GenerateCode(string secret, int Algorithm, int Digits, int Period) { var totp = new Totp(Base32Encoding.ToBytes(secret), mode: (OtpHashMode)Algorithm, totpSize: Digits, step: Period); return(totp.ComputeTotp()); }
private string generate(string secret) { Totp generator = new Totp(secret); return(generator.now()); }
public static bool IsValid(byte[] secretKey, string code) { var totp = new Totp(secretKey); return(totp.VerifyTotp(code, out long timeStepMatched)); }
public Token(string raw) { _storedToken = Utilities.ParseBarcode(raw); _totp = new Totp(SecretAsBytes); }
public ApiPublicaService(IOrganizacaoRepository organizacaoRepository) { _totp = new Totp(Encoding.ASCII.GetBytes(_secretKey)); _organizacaoRepository = organizacaoRepository; }
private void ExecuteHandler(ClientSession session) { if (session.Account.IsVerified || Type == 4 && Argument == 11) { if (Data.HasValue && Type == 10 && Data.Value >= 973 && Data.Value <= 999 && !session.Character.EmoticonsBlocked) { if (Parameter == session.Character.CharacterId) { session.CurrentMapInstance?.Broadcast(session, StaticPacketHelper.GenerateEff(UserType.Player, session.Character.CharacterId, Data.Value + 4099), ReceiverType.AllNoEmoBlocked); } else if (Parameter.TryCastToInt(out int mateTransportId)) { Mate mate = session.Character.Mates.Find(s => s.MateTransportId == mateTransportId); if (mate != null) { session.CurrentMapInstance?.Broadcast(session, StaticPacketHelper.GenerateEff(UserType.Npc, mate.MateTransportId, Data.Value + 4099), ReceiverType.AllNoEmoBlocked); } } } else if (Type == 204) { if (Argument == 0 && short.TryParse(Parameter.ToString(), out short slot)) { ItemInstance shell = session.Character.Inventory.LoadBySlotAndType(slot, InventoryType.Equipment); if (shell?.ShellEffects.Count == 0 && shell.Upgrade > 0 && shell.Rare > 0 && session.Character.Inventory.CountItem(1429) >= ((shell.Upgrade / 10) + shell.Rare)) { shell.SetShellEffects(); session.SendPacket( UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("OPTION_IDENTIFIED"), 0)); session.SendPacket(StaticPacketHelper.GenerateEff(UserType.Player, session.Character.CharacterId, 3006)); session.Character.Inventory.RemoveItemAmount(1429, (shell.Upgrade / 10) + shell.Rare); } } } else if (Type == 205) { if (Parameter.TryCastToShort(out short slot)) { ItemInstance inv = session.Character.Inventory.LoadBySlotAndType(slot, InventoryType.Equipment); if (inv.Rare < 1 || inv.Rare > 8 || inv.Item.LevelMinimum > 99 || inv.BoundCharacterId == null) { return; } short[][] parfumeReq = { new short[] { 0, 0, 0, 0, 0, 5, 10, 10, 20 }, new short[] { 0, 0, 0, 0, 5, 10, 10, 20, 40 }, new short[] { 0, 0, 0, 5, 10, 10, 20, 40, 80 }, new short[] { 0, 0, 5, 5, 10, 20, 40, 80, 120 }, new short[] { 0, 0, 5, 10, 20, 40, 80, 120, 160 }, new short[] { 0, 0, 5, 20, 40, 80, 120, 160, 200 }, new short[] { 0, 0, 10, 40, 80, 120, 160, 200, 300 }, new short[] { 0, 0, 10, 40, 80, 120, 160, 200, 400 } }; int[] goldReq = { 1000, 2000, 5000, 8000, 10000, 12500, 15000, 17500, 20000, 30000 }; if (session.Character.Inventory.CountItem(1428) >= parfumeReq[inv.Rare - 1][(inv.Item.LevelMinimum / 10) - 1] && session.Character.Gold >= goldReq[(inv.Item.LevelMinimum / 10) - 1]) { session.Character.Inventory.RemoveItemAmount(1428, parfumeReq[inv.Rare - 1][(inv.Item.LevelMinimum / 10) - 1]); session.Character.Gold -= goldReq[(inv.Item.LevelMinimum / 10) - 1]; session.SendPacket(session.Character.GenerateGold()); inv.BoundCharacterId = session.Character.CharacterId; session.SendPacket( UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("SHELL_PERFUMED"), 0)); } } } else if (Type == 300) { if (Argument == 8023 && Parameter.TryCastToShort(out short slot)) { ItemInstance box = session.Character.Inventory.LoadBySlotAndType(slot, InventoryType.Equipment); if (box != null) { box.Item.Use(session, ref box, 1, new[] { Data?.ToString() ?? string.Empty }); } } } else if (Type == 506) { session.Character.IsWaitingForEvent |= ServerManager.Instance.EventInWaiting; } else if (Type == 199 && Argument == 2) { short[] listWingOfFriendship = { 2160, 2312, 10048 }; short vnumToUse = -1; foreach (short vnum in listWingOfFriendship) { if (session.Character.Inventory.CountItem(vnum) > 0) { vnumToUse = vnum; } } if (vnumToUse != -1 || session.Character.IsSpouseOfCharacter(Parameter)) { ClientSession sess = ServerManager.Instance.GetSessionByCharacterId(Parameter); if (sess != null) { if (session.Character.IsFriendOfCharacter(Parameter)) { if (sess.CurrentMapInstance?.MapInstanceType == MapInstanceType.BaseMapInstance) { if (session.Character.MapInstance.MapInstanceType != MapInstanceType.BaseMapInstance || (ServerManager.Instance.ChannelId == 51 && session.Character.Faction != sess.Character.Faction)) { session.SendPacket( session.Character.GenerateSay( Language.Instance.GetMessageFromKey("CANT_USE_THAT"), 10)); return; } short mapy = sess.Character.PositionY; short mapx = sess.Character.PositionX; short mapId = sess.Character.MapInstance.Map.MapId; ServerManager.Instance.ChangeMap(session.Character.CharacterId, mapId, mapx, mapy); if (!session.Character.IsSpouseOfCharacter(Parameter)) { session.Character.Inventory.RemoveItemAmount(vnumToUse); } } else { session.SendPacket( UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("USER_ON_INSTANCEMAP"), 0)); } } } else { session.SendPacket( UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("USER_NOT_CONNECTED"), 0)); } } else { session.SendPacket( session.Character.GenerateSay(Language.Instance.GetMessageFromKey("NO_WINGS"), 10)); } } else if (Type == 400) { if (!session.HasCurrentMapInstance) { return; } MapNpc npc = session.CurrentMapInstance.Npcs.Find(n => n.MapNpcId.Equals(Argument)); if (npc != null) { NpcMonster mapobject = ServerManager.GetNpcMonster(npc.NpcVNum); int rateDrop = ServerManager.Instance.Configuration.RateDrop; int delay = (int)Math.Round( (3 + (mapobject.RespawnTime / 1000d)) * session.Character.TimesUsed); delay = delay > 11 ? 8 : delay; if (session.Character.LastMapObject.AddSeconds(delay) < DateTime.UtcNow) { if (mapobject.Drops.Any(s => s.MonsterVNum != null) && mapobject.VNumRequired > 10 && session.Character.Inventory .CountItem(mapobject.VNumRequired) < mapobject.AmountRequired) { session.SendPacket( UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("NOT_ENOUGH_ITEM"), 0)); return; } Random random = new Random(); double randomAmount = ServerManager.RandomNumber() * random.NextDouble(); DropDTO drop = mapobject.Drops.Find(s => s.MonsterVNum == npc.NpcVNum); if (drop != null) { int dropChance = drop.DropChance; if (randomAmount <= (double)dropChance * rateDrop / 5000.000) { short vnum = drop.ItemVNum; ItemInstance newInv = session.Character.Inventory.AddNewToInventory(vnum) .FirstOrDefault(); session.Character.LastMapObject = DateTime.UtcNow; session.Character.TimesUsed++; if (session.Character.TimesUsed >= 4) { session.Character.TimesUsed = 0; } if (newInv != null) { session.SendPacket(UserInterfaceHelper.GenerateMsg( string.Format(Language.Instance.GetMessageFromKey("RECEIVED_ITEM"), newInv.Item.Name), 0)); session.SendPacket(session.Character.GenerateSay( string.Format(Language.Instance.GetMessageFromKey("RECEIVED_ITEM"), newInv.Item.Name), 11)); } else { session.SendPacket(UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("NOT_ENOUGH_PLACE"), 0)); } } else { session.SendPacket( UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("TRY_FAILED"), 0)); } } } else { session.SendPacket(UserInterfaceHelper.GenerateMsg( string.Format(Language.Instance.GetMessageFromKey("TRY_FAILED_WAIT"), (int)(session.Character.LastMapObject.AddSeconds(delay) - DateTime.UtcNow) .TotalSeconds), 0)); } } } else if (Type == 710) { if (Value != null) { // TODO: MAP TELEPORTER } } else if (Type == 750) { const short baseVnum = 1623; if (Argument.TryCastToByte(out byte faction) && (Enum.IsDefined(typeof(FactionType), faction) || Enum.IsDefined(typeof(FactionType), (byte)(faction / 2))) && session.Character.Inventory.CountItem(baseVnum + faction) > 0) { if (faction < 3) { if (session.Character.Family != null) { session.SendPacket( UserInterfaceHelper.GenerateMsg(Language.Instance.GetMessageFromKey("IN_FAMILY"), 0)); return; } session.Character.Faction = (FactionType)faction; session.Character.Inventory.RemoveItemAmount(baseVnum + faction); session.SendPacket("scr 0 0 0 0 0 0 0"); session.SendPacket(session.Character.GenerateFaction()); session.SendPacket(StaticPacketHelper.GenerateEff(UserType.Player, session.Character.CharacterId, 4799 + faction)); session.SendPacket(UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey($"GET_PROTECTION_POWER_{faction}"), 0)); } else { if (session.Character.Family == null || session.Character.Family.FamilyCharacters .Find(s => s.Authority.Equals(FamilyAuthority.Head))?.CharacterId .Equals(session.Character.CharacterId) != true) { session.SendPacket( UserInterfaceHelper.GenerateMsg(Language.Instance.GetMessageFromKey("NO_FAMILY"), 0)); return; } if (session.Character.Family.LastFactionChange > DateTime.UtcNow.AddDays(-1).Ticks) { session.SendPacket(UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey("CHANGE_NOT PERMITTED"), 0)); return; } session.Character.Faction = (FactionType)(faction / 2); session.Character.Inventory.RemoveItemAmount(baseVnum + faction); session.SendPacket("scr 0 0 0 0 0 0 0"); session.SendPacket(session.Character.GenerateFaction()); session.SendPacket(StaticPacketHelper.GenerateEff(UserType.Player, session.Character.CharacterId, 4799 + (faction / 2))); session.SendPacket(UserInterfaceHelper.GenerateMsg( Language.Instance.GetMessageFromKey($"GET_PROTECTION_POWER_{faction / 2}"), 0)); session.Character.Family.LastFactionChange = DateTime.UtcNow.Ticks; session.Character.Save(); ServerManager.Instance.FamilyRefresh(session.Character.Family.FamilyId); CommunicationServiceClient.Instance.SendMessageToCharacter(new ScsCharacterMessage { DestinationCharacterId = session.Character.Family.FamilyId, SourceCharacterId = 0, SourceWorldId = ServerManager.Instance.WorldId, Message = "fhis_stc", Type = MessageType.Family }); } } } else if (Type == 2) { session.CurrentMapInstance?.Broadcast( UserInterfaceHelper.GenerateGuri(2, 1, session.Character.CharacterId), session.Character.PositionX, session.Character.PositionY); } else if (Type == 4) { const int speakerVNum = 2173; const int petnameVNum = 2157; if (Argument == 1 && Data.HasValue) { Mate mate = session.Character.Mates.Find(s => s.MateTransportId == Data.Value); if (mate != null && session.Character.Inventory.CountItem(petnameVNum) > 0) { mate.Name = Value.Truncate(16); session.CurrentMapInstance?.Broadcast(mate.GenerateOut(), ReceiverType.AllExceptMe); session.CurrentMapInstance?.Broadcast(mate.GenerateIn()); session.SendPacket(mate.GenerateCond()); session.SendPacket( UserInterfaceHelper.GenerateInfo(Language.Instance.GetMessageFromKey("NEW_NAME_PET"))); session.SendPacket(session.Character.GeneratePinit()); session.SendPackets(session.Character.GeneratePst()); session.SendPackets(session.Character.GenerateScP()); session.Character.Inventory.RemoveItemAmount(petnameVNum); } } // presentation message if (Argument == 2) { int presentationVNum = session.Character.Inventory.CountItem(1117) > 0 ? 1117 : (session.Character.Inventory.CountItem(9013) > 0 ? 9013 : -1); if (presentationVNum != -1) { string message = string.Empty; string[] valuesplit = Value?.Split(' '); if (valuesplit == null) { return; } for (int i = 0; i < valuesplit.Length; i++) { message += valuesplit[i] + "^"; } message = message.Substring(0, message.Length - 1); // Remove the last ^ message = message.Trim(); if (message.Length > 60) { message = message.Substring(0, 60); } session.Character.Biography = message; session.SendPacket( session.Character.GenerateSay(Language.Instance.GetMessageFromKey("INTRODUCTION_SET"), 10)); session.Character.Inventory.RemoveItemAmount(presentationVNum); } } // Speaker if (Argument == 3 && session.Character.Inventory.CountItem(speakerVNum) > 0) { string message = $"[{session.Character.Name}]:"; int baseLength = message.Length; string[] valuesplit = Value?.Split(' '); if (valuesplit == null) { return; } for (int i = 0; i < valuesplit.Length; i++) { message += valuesplit[i] + " "; } if (message.Length > 120 + baseLength) { message = message.Substring(0, 120 + baseLength); } message = message.Replace("\n", string.Empty).Replace("\r", string.Empty) .Replace($"<{Language.Instance.GetMessageFromKey("SPEAKER")}>", string.Empty).Trim(); message = $"<{Language.Instance.GetMessageFromKey("SPEAKER")}> {message}"; if (session.Character.IsMuted()) { session.SendPacket( session.Character.GenerateSay( Language.Instance.GetMessageFromKey("SPEAKER_CANT_BE_USED"), 10)); return; } session.Character.Inventory.RemoveItemAmount(speakerVNum); ServerManager.Instance.Broadcast(session.Character.GenerateSay(message, 13)); if (ServerManager.Instance.Configuration.UseChatLogService) { ChatLogServiceClient.Instance.LogChatMessage(new ChatLogEntry { Sender = session.Character.Name, SenderId = session.Character.CharacterId, Receiver = null, ReceiverId = null, MessageType = ChatLogType.Speaker, Message = message }); } } if (Argument == 11 && !string.IsNullOrWhiteSpace(Value) && !string.IsNullOrWhiteSpace(session.Account.TotpSecret)) { Totp totp = new Totp(Base32Encoding.ToBytes(session.Account.TotpSecret)); if (totp.VerifyTotp(Value, out long _, VerificationWindow.RfcSpecifiedNetworkDelay)) { session.Character.GeneralLogs.Add(new GeneralLogDTO { AccountId = session.Account.AccountId, IpAddress = session.IpAddress, LogType = GeneralLogType.TOTP.ToString(), LogData = "SUCCESS", Timestamp = DateTime.UtcNow }); session.Account.IsVerified = true; session.SendPacket(session.Character.GenerateSay(Language.Instance.GetMessageFromKey("TOTP_VERIFIED"), 12)); } else { session.Character.GeneralLogs.Add(new GeneralLogDTO { AccountId = session.Account.AccountId, IpAddress = session.IpAddress, LogType = GeneralLogType.TOTP.ToString(), LogData = "FAIL", Timestamp = DateTime.UtcNow }); session.Disconnect(); } } } else if (Type == 199 && Argument == 1) { if (!session.Character.IsFriendOfCharacter(Parameter)) { session.SendPacket(Language.Instance.GetMessageFromKey("CHARACTER_NOT_IN_FRIENDLIST")); return; } session.SendPacket(UserInterfaceHelper.GenerateDelay(3000, 4, $"#guri^199^2^{Parameter}")); } else if (Type == 201) { if (session.Character.StaticBonusList.Any(s => s.StaticBonusType == StaticBonusType.PetBasket)) { session.SendPacket(session.Character.GenerateStashAll()); } } else if (Type == 202) { session.SendPacket( session.Character.GenerateSay(Language.Instance.GetMessageFromKey("PARTNER_BACKPACK"), 10)); session.SendPacket(session.Character.GeneratePStashAll()); } else if (Type == 208 && Argument == 0) { if (short.TryParse(Value, out short mountSlot) && Parameter.TryCastToShort(out short pearlSlot)) { ItemInstance mount = session.Character.Inventory.LoadBySlotAndType <ItemInstance>(mountSlot, InventoryType.Main); ItemInstance pearl = session.Character.Inventory.LoadBySlotAndType(pearlSlot, InventoryType.Equipment); if (mount != null && pearl != null) { pearl.HoldingVNum = mount.ItemVNum; session.Character.Inventory.RemoveItemFromInventory(mount.Id); } } } else if (Type == 209 && Argument == 0) { if (short.TryParse(Value, out short mountSlot) && Parameter.TryCastToShort(out short pearlSlot)) { ItemInstance fairy = session.Character.Inventory.LoadBySlotAndType(mountSlot, InventoryType.Equipment); ItemInstance pearl = session.Character.Inventory.LoadBySlotAndType(pearlSlot, InventoryType.Equipment); if (fairy != null && pearl != null) { pearl.HoldingVNum = fairy.ItemVNum; pearl.ElementRate = fairy.ElementRate; session.Character.Inventory.RemoveItemFromInventory(fairy.Id); } } } else if (Type == 203 && Argument == 0) { // SP points initialization int[] listPotionResetVNums = { 1366, 1427, 5115, 9040 }; int vnumToUse = -1; foreach (int vnum in listPotionResetVNums) { if (session.Character.Inventory.CountItem(vnum) > 0) { vnumToUse = vnum; } } if (vnumToUse != -1) { if (session.Character.UseSp) { ItemInstance specialistInstance = session.Character.Inventory.LoadBySlotAndType((byte)EquipmentType.Sp, InventoryType.Wear); if (specialistInstance != null) { specialistInstance.SlDamage = 0; specialistInstance.SlDefence = 0; specialistInstance.SlElement = 0; specialistInstance.SlHP = 0; specialistInstance.DamageMinimum = 0; specialistInstance.DamageMaximum = 0; specialistInstance.HitRate = 0; specialistInstance.CriticalLuckRate = 0; specialistInstance.CriticalRate = 0; specialistInstance.DefenceDodge = 0; specialistInstance.DistanceDefenceDodge = 0; specialistInstance.ElementRate = 0; specialistInstance.DarkResistance = 0; specialistInstance.LightResistance = 0; specialistInstance.FireResistance = 0; specialistInstance.WaterResistance = 0; specialistInstance.CriticalDodge = 0; specialistInstance.CloseDefence = 0; specialistInstance.DistanceDefence = 0; specialistInstance.MagicDefence = 0; specialistInstance.HP = 0; specialistInstance.MP = 0; session.Character.Inventory.RemoveItemAmount(vnumToUse); session.Character.Inventory.DeleteFromSlotAndType((byte)EquipmentType.Sp, InventoryType.Wear); session.Character.Inventory.AddToInventoryWithSlotAndType(specialistInstance, InventoryType.Wear, (byte)EquipmentType.Sp); session.SendPacket(session.Character.GenerateCond()); session.SendPacket(specialistInstance.GenerateSlInfo()); session.SendPacket(session.Character.GenerateLev()); session.SendPacket(session.Character.GenerateStatChar()); session.SendPacket( UserInterfaceHelper.GenerateMsg(Language.Instance.GetMessageFromKey("POINTS_RESET"), 0)); } } else { session.SendPacket( session.Character.GenerateSay( Language.Instance.GetMessageFromKey("TRANSFORMATION_NEEDED"), 10)); } } else { session.SendPacket( session.Character.GenerateSay(Language.Instance.GetMessageFromKey("NOT_ENOUGH_POINTS"), 10)); } } }
public async Task TotpTest() { var totp = new Totp(Base32Encoding.ToBytes(totpSecret)); var totpCode = totp.ComputeTotp(); }
public void Login() { // Navigate to Facebook _webDriver.Url = "https://www.facebook.com/"; // Find the username field (Facebook calls it "email") and enter value var input = _webDriver.FindElement(By.Id("email")); input.SendKeys(_appSettings.UserName); // Find the password field and enter value input = _webDriver.FindElement(By.Id("pass")); input.SendKeys(_appSettings.Password); // Click on the login button ClickAndWaitForPageToLoad(_webDriver, By.Name("login")); if (!string.IsNullOrWhiteSpace(_appSettings.TwoFASeed)) { // A 2FA seed code was passed, let's generate the 2FA code var otpKeyBytes = Base32Encoding.ToBytes(_appSettings.TwoFASeed); var totp = new Totp(otpKeyBytes); var twoFactorCode = totp.ComputeTotp(); // Enter the code into the UI input = _webDriver.FindElement(By.Id("approvals_code")); input.SendKeys(twoFactorCode); } // At this point, Facebook will launch a post-login "wizard" that will // keep asking unknown amount of questions (it thinks it's the first time // you logged in using this computer). We'll just click on the "continue" // button until they give up and redirect us to our "wall". try { while (_webDriver.FindElement(By.Id("checkpointSubmitButton")) != null) { // Clicking "continue" until we're done ClickAndWaitForPageToLoad(_webDriver, By.Id("checkpointSubmitButton")); } } catch { // We will try to click on the next button until it's not there or we fail. // Facebook is unexpected as to what will happen, but this approach seems // to be pretty reliable } for (int i = 0; i < 30; i++) { _webDriver.ExecuteJavaScript("window.scrollTo(0, document.body.scrollHeight)"); Thread.Sleep(3000); } var elements = _webDriver.FindElements(By.XPath("//div[@data-pagelet]")); foreach (var item in elements) { var attr = item.GetAttribute("data-pagelet"); if (!attr.StartsWith("FeedUnit")) { continue; } var text = item.Text; if (_appSettings.IncludeUsers != null) { foreach (var includeUser in _appSettings.IncludeUsers) { if (!text.Contains(includeUser)) { continue; } } } if (_appSettings.ExcludedUsers != null) { foreach (var excludeUser in _appSettings.ExcludedUsers) { if (text.Contains(excludeUser)) { continue; } } } if (text.Contains("updated his profile picture") || text.Contains("updated her profile picture") || text.Contains("updated his cover photo") || text.Contains("updated her cover photo")) { var likeBtn = item.FindElement(By.XPath(".//div[@aria-label=\"Like\"]")); var child = likeBtn.FindElement(By.XPath(".//div")); if (string.IsNullOrEmpty(child.GetAttribute("style"))) { likeBtn.Click(); } else { // Already liked } } } Console.WriteLine("Finished automation"); }
public static bool IsValid(string str) { if (string.IsNullOrWhiteSpace(str)) { return(false); } var uri = new Uri(str); if (!System.Uri.IsWellFormedUriString(str, UriKind.Absolute)) { return(false); } if (uri.Scheme != "otpauth") { return(false); } if (uri.Host != "totp") { return(false); } if (string.IsNullOrWhiteSpace(uri.AbsolutePath.TrimStart('/'))) { return(false); } var label = uri.AbsolutePath.TrimStart('/'); if (string.IsNullOrWhiteSpace(label)) { return(false); } var parsed = HttpUtility.ParseQueryString(uri.Query); var issuer = parsed["issuer"]; if (string.IsNullOrWhiteSpace(issuer)) { return(false); } var secret = parsed["secret"]; if (string.IsNullOrWhiteSpace(secret)) { return(false); } try { var key = Base32Encoding.ToBytes(secret); var totp = new Totp(key); var code = totp.ComputeTotp(); if (string.IsNullOrWhiteSpace(code)) { return(false); } } catch (Exception) { return(false); } return(true); }
public async Task <OperationDataResult <EformAuthorizeResult> > AuthenticateUser(LoginModel model) { Log.LogEvent("AuthService.AuthenticateUser: called"); if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password)) { return(new OperationDataResult <EformAuthorizeResult>(false, "Empty username or password")); } var user = await _userService.GetByUsernameAsync(model.Username); if (user == null) { return(new OperationDataResult <EformAuthorizeResult>(false, $"User with username {model.Username} not found")); } var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true); if (!signInResult.Succeeded && !signInResult.RequiresTwoFactor) { if (signInResult.IsLockedOut) { return(new OperationDataResult <EformAuthorizeResult>(false, "Locked Out. Please, try again after 10 min")); } // Credentials are invalid, or account doesn't exist return(new OperationDataResult <EformAuthorizeResult>(false, "Incorrect password.")); } // Confirmed email check if (!user.EmailConfirmed) { return(new OperationDataResult <EformAuthorizeResult>(false, $"Email {user.Email} not confirmed")); } // TwoFactor check var psk = user.GoogleAuthenticatorSecretKey; var code = model.Code; var isTwoFactorAuthForced = _appSettings.Value.IsTwoFactorForced; if (user.TwoFactorEnabled || isTwoFactorAuthForced) { // check input params if (string.IsNullOrEmpty(psk) || string.IsNullOrEmpty(code)) { return(new OperationDataResult <EformAuthorizeResult>(false, "PSK or code is empty")); } if (psk != user.GoogleAuthenticatorSecretKey) { return(new OperationDataResult <EformAuthorizeResult>(false, "PSK is invalid")); } // check code var otp = new Totp(Base32.FromBase32String(user.GoogleAuthenticatorSecretKey)); var isCodeValid = otp.VerifyTotp(code, out _, new VerificationWindow(300, 300)); if (!isCodeValid) { return(new OperationDataResult <EformAuthorizeResult>(false, "Invalid code")); } // update user entity if (!user.IsGoogleAuthenticatorEnabled) { user.IsGoogleAuthenticatorEnabled = true; var updateResult = _userManager.UpdateAsync(user).Result; if (!updateResult.Succeeded) { return(new OperationDataResult <EformAuthorizeResult>(false, "PSK or code is empty")); } } } var token = await GenerateToken(user); var roleList = _userManager.GetRolesAsync(user).Result; if (!roleList.Any()) { return(new OperationDataResult <EformAuthorizeResult>(false, $"Role for user {model.Username} not found")); } return(new OperationDataResult <EformAuthorizeResult>(true, new EformAuthorizeResult { Id = user.Id, access_token = token, userName = user.UserName, role = roleList.FirstOrDefault(), FirstName = user.FirstName, LastName = user.LastName, })); }
protected void ValidateOtp() { IsStartup = false; IsValidOtp = Totp.VerifyTotp(InOtpString, out _); }
public string Code(string id, DateTime time) { Totp = new Totp(Encoding.ASCII.GetBytes(id), mode: OtpHashMode.Sha256, step: 30); return(Totp.ComputeTotp(time)); }
public static bool VerifyOtp(byte[] key, string otpCode) { var totp = new Totp(key, mode: OtpHashMode.Sha1, totpSize: 6); return(totp.VerifyTotp(otpCode, out _)); }
public static string Get2FaOtp(string secretKey, DateTime timeStamp) { var totp = new Totp(Encoding.UTF8.GetBytes(secretKey)); return(totp.ComputeTotp(timeStamp)); }
public string Generate(DateTime timeStamp) { var generator = new Totp(Encoding.UTF8.GetBytes(_otpSecretKey)); return(generator.ComputeTotp(timeStamp)); }
private void CreateTotp(string secretKey) { _totp = new Totp(Encoding.UTF8.GetBytes(secretKey), _options.StepInSeconds); }
/// <summary> /// Asks the user to choose a password file, decrypts it, /// generates an OTP code from the secret in the totp field, and copies the resulting value to the clipboard. /// </summary> public void GenerateTotpCode(bool copyToClipboard, bool typeTotpCode) { var selectedFile = RequestPasswordFile(); // If the user cancels their selection, the password decryption should be cancelled too. if (selectedFile == null) { return; } KeyedPasswordFile passFile; try { passFile = passwordManager.DecryptPassword(selectedFile, true); } catch (Exception e) when(e is GpgError || e is GpgException || e is ConfigurationException) { notificationService.ShowErrorWindow("TOTP decryption failed: " + e.Message); return; } catch (Exception e) { notificationService.ShowErrorWindow($"TOTP decryption failed: An error occurred: {e.GetType().Name}: {e.Message}"); return; } String secretKey = null; foreach (var k in passFile.Keys) { // totp: Xxxx4 if (k.Key == "totp") { secretKey = k.Value; } // otpauth: //totp/account?secret=FxxxX&digits=6 if (k.Key == "otpauth") { var regex = new Regex("secret=([a-zA-Z0-9]+)&", RegexOptions.Compiled | RegexOptions.IgnoreCase); var matches = regex.Match(k.Value); if (matches.Success) { secretKey = matches.Groups[1].Value; } } } var foo = String.Join(",", passFile.Keys.Select(f => f.Key)); if (secretKey == null) { notificationService.ShowErrorWindow($"TOTP decryption failed: Failed to find an OTP secret. Keys = ${foo}"); return; } var secretKeyBytes = Base32Encoding.ToBytes(secretKey); var totp = new Totp(secretKeyBytes); var totpCode = totp.ComputeTotp(); if (copyToClipboard) { ClipboardHelper.Place(totpCode, TimeSpan.FromSeconds(ConfigManager.Config.Interface.ClipboardTimeout)); if (ConfigManager.Config.Notifications.Types.TotpCopied) { notificationService.Raise($"The totp code has been copied to your clipboard.\nIt will be cleared in {ConfigManager.Config.Interface.ClipboardTimeout:0.##} seconds.", Severity.Info); } } if (typeTotpCode) { KeyboardEmulator.EnterText(totpCode, ConfigManager.Config.Output.DeadKeys); } }