private void button1_Click(object sender, EventArgs e) { if ("" == txtKey.Text.Trim()) { MessageBox.Show("没有密钥,请生成或者粘贴一个密钥到密钥输入框中"); return; } if ("开始" == button1.Text) { h = new TOTP(RemoveSpaces()); txtKey.Enabled = false; timer1.Start(); button1.Text = "停止"; } else { txtKey.Enabled = true; timer1.Stop(); count = 0; button1.Text = "开始"; } }
public void TOTP_GenerateCode() { var result = TOTP.GenerateCode(); Assert.IsNotNull(result.Secret); Assert.AreNotEqual(0, result.Code); }
// GET: Validate public ActionResult Check(string barcode) { if (barcode.Length != 12 + TOTP.digits || barcode.Any(a => !"0123456789".Contains(a))) { return(View("NotValidFormat")); } var memberId = barcode.Substring(0, 12); var code = barcode.Substring(12); var member = UserManager.Users.FirstOrDefault(a => a.MembershipNumber.Equals(memberId)); if (member == null) { return(View("UnAuthorized")); } if (member.SharedBarcodeSecret == null) { return(View("UnAuthorized")); } var totp = new TOTP(member.SharedBarcodeSecret); if (totp.ConfirmCode(code)) { return(View("Authorized", member)); } return(View("UnAuthorized")); }
/// <summary> /// CheckPin method inplementation /// </summary> private bool CheckPin(AuthenticationContext usercontext, int pin) { foreach (HashMode algo in Enum.GetValues(typeof(HashMode))) { if (algo <= Algorithm) { if (TOTPShadows <= 0) { if (!KeysManager.ValidateKey(usercontext.UPN)) { throw new CryptographicException(string.Format("SECURTY ERROR : Invalid Key for User {0}", usercontext.UPN)); } byte[] encodedkey = KeysManager.ProbeKey(usercontext.UPN); DateTime call = DateTime.UtcNow; TOTP gen = new TOTP(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code gen.Compute(call); return(pin == gen.OTP); } else { // Current TOTP if (!KeysManager.ValidateKey(usercontext.UPN)) { throw new CryptographicException(string.Format("SECURTY ERROR : Invalid Key for User {0}", usercontext.UPN)); } byte[] encodedkey = KeysManager.ProbeKey(usercontext.UPN); DateTime tcall = DateTime.UtcNow; TOTP gen = new TOTP(encodedkey, usercontext.UPN, tcall, algo, this.Duration, this.Digits); // eg : TOTP code gen.Compute(tcall); if (pin == gen.OTP) { return(true); } // TOTP with Shadow (current - x latest) for (int i = 1; i <= TOTPShadows; i++) { DateTime call = tcall.AddSeconds(-(i * this.Duration)); TOTP gen2 = new TOTP(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code gen2.Compute(call); if (pin == gen2.OTP) { return(true); } } // TOTP with Shadow (current + x latest) - not possible. but can be usefull if time sync is not adequate for (int i = 1; i <= TOTPShadows; i++) { DateTime call = tcall.AddSeconds(i * this.Duration); TOTP gen3 = new TOTP(encodedkey, usercontext.UPN, call, algo, this.Duration, this.Digits); // eg : TOTP code gen3.Compute(call); if (pin == gen3.OTP) { return(true); } } } } } return(false); }
public void Veryfying() { var key = TOTP.GenerateKey(); var code = TOTP.GenerateCode(key); var result = TOTP.VerifyCode(key, code); result.Should().BeTrue(); }
public Barcode(User _user) { if (!_user.IsLoggedIn || string.IsNullOrEmpty(_user.GetProperty(UserConstants.SECRET))) { throw new UnauthorizedAccessException(); } this.user = _user; this.memberid = user.GetProperty(UserConstants.MemberID); var secret = user.GetProperty(UserConstants.SECRET); var secretBytes = Convert.FromBase64String(secret); this.totp = new TOTP(secretBytes); this.cacheBitmap = null; this.cacheData = ""; }
private void MainForm_Load(object sender, EventArgs e) { _totp = new TOTP( ConfigurationManager.AppSettings.Get("TotpKey"), Int32.Parse(ConfigurationManager.AppSettings.Get("OtpDigits") ?? TOTP.DefaultLength.ToString()), Int32.Parse(ConfigurationManager.AppSettings.Get("OtpWindow") ?? TOTP.DefaultTimeInterval.ToString())); this.Text = ConfigurationManager.AppSettings.Get("TotpAccountName") ?? "TOTP OTP"; _updateOtpTimer = new Timer(); _updateOtpTimer.Interval = 100; _updateOtpTimer.Tick += new EventHandler(UpdateOtp_Tick); _updateOtpTimer.Enabled = true; progressOtp.Minimum = 0; progressOtp.Maximum = _totp.Window; }
/// <summary> /// Bare bones One Time Password generator using TOTP /// The key and optional related info are stored in app.config /// </summary> /// <param name="args"></param> static void Main(string[] args) { // TotpKey: this is provided when you set up the authenticator as a Base32 encoded string // OtpDigits: Number of digits to use (default is 6) // OtpWindow: Seconds in window for TOTP (rate codes refresh, default is 30s) var totp = new TOTP( ConfigurationManager.AppSettings.Get("TotpKey"), Int32.Parse(ConfigurationManager.AppSettings.Get("OtpDigits") ?? TOTP.DefaultLength.ToString()), Int32.Parse(ConfigurationManager.AppSettings.Get("OtpWindow") ?? TOTP.DefaultTimeInterval.ToString())); // Account name is not needed but if given set the title Console.Title = ConfigurationManager.AppSettings.Get("TotpAccountName") ?? "TOTP OTP"; while (true) { EraseConsole(); Console.WriteLine($"{totp.Otp} : {SecondsRemaining(totp.SecondsRemaining)} [{RemainingProgressBar(totp.SecondsRemaining, totp.Window)}]"); System.Threading.Thread.Sleep(250); } }
public async Task <IHttpActionResult> Get(string secret) { var identity = (ClaimsIdentity)User.Identity; var phone = identity.Claims.Where(c => c.Type == ClaimTypes.MobilePhone) .Select(c => c.Value).SingleOrDefault(); //TODO: Send SMS to the staff members' number above TOTP t = new TOTP(secret, 300); int pass = t.now(); IdentityMessage message = new IdentityMessage() { Body = "passcode: " + pass, Destination = "+256706430315", Subject = "Security Code" }; await _smService.SendAsync(message); PassBackModel p = new PassBackModel(); p.message = "sent"; return(Ok(p)); }
public IHttpActionResult Post([FromBody] PassCodeModel p) { var identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; //string userId = User.Identity.GetUserId(); PassCodeModel n = p; TOTP t = new TOTP(p.imei, 300); bool x = false; x = t.verify(n.passcode); if (x) { return(Ok(new PassBackModel() { message = "Verified" })); } else { return(BadRequest("Invalid passcode")); } }
static void Main(string[] args) { TOTP t = new TOTP(args[0]); Console.WriteLine("Your OTP = " + t.now().ToString("D6")); }
public void TOTP_IsValid_out_of_sync_clocks() { var result = TOTP.GenerateCode(); Assert.IsTrue(TOTP.IsValid(result.Code, result.Secret, DateTime.UtcNow.AddSeconds(-32), 90)); }
public void TOTP_IsValid_fails() { var result = TOTP.GenerateCode(); Assert.IsFalse(TOTP.IsValid(result.Code, result.Secret, DateTime.UtcNow.AddSeconds(300), 90)); }
public bool Validate(byte[] secretKey, int code) { return(TOTP.ValidateTOTP(secretKey, code)); }
public static void Main(string[] args) { // //////////////////////////////////////////////////////////// // Initialization Stuff // // //////////////////////////////////////////////////////////// const int INTERVAL = 30; const int DIGITS = 6; byte[] BASE32_SECRET = Encoding.ASCII.GetBytes("JBSWY3DPEHPK3PXP"); byte[] SHA1_DIGEST = Encoding.ASCII.GetBytes("SHA1"); const int SHA1_BITS = 160; TOTP tdata = new TOTP(BASE32_SECRET, SHA1_BITS, SHA1_Encrypt, SHA1_DIGEST, DIGITS, INTERVAL); HOTP hdata = new HOTP(BASE32_SECRET, SHA1_BITS, SHA1_Encrypt, SHA1_DIGEST, DIGITS); Console.WriteLine("\\\\ totp tdata \\\\"); Console.WriteLine("tdata.digits: `" + tdata.digits + "`"); Console.WriteLine("tdata.interval: `" + tdata.interval + "`"); Console.WriteLine("tdata.bits: `" + tdata.bits + "`"); Console.WriteLine("tdata.type: `" + tdata.method + "`"); Console.WriteLine("tdata.algo: `" + tdata.algo + "`"); Console.WriteLine("tdata.digest: `" + tdata.digest + "`"); Console.WriteLine("tdata.base32_secret: `" + tdata.base32_secret + "`"); Console.WriteLine("// totp tdata //\n"); Console.WriteLine("\\\\ hotp hdata \\\\"); Console.WriteLine("hdata.digits: `" + hdata.digits + "`"); Console.WriteLine("hdata.bits: `" + hdata.bits + "`"); Console.WriteLine("hdata.type: `" + hdata.method + "`"); Console.WriteLine("hdata.algo: `" + hdata.algo + "`"); Console.WriteLine("hdata.getDigest: `" + hdata.digest + "`"); Console.WriteLine("hdata.base32_secret: `" + hdata.base32_secret + "`"); Console.WriteLine("// hotp hdata //\n"); Console.WriteLine("Current Time: `" + (DateTimeOffset.Now.ToUnixTimeSeconds()) + "`"); // ///////////////////////////////////////////////////////////// // URI Example // // ///////////////////////////////////////////////////////////// const String name1 = "name1"; const String name2 = "name2"; const String whatever1 = "*****@*****.**"; const String whatever2 = "*****@*****.**"; // show example of URis // totp uri String uri1 = OTPUri.build_uri(tdata, name1, whatever1, 0); // hotp uri const int counter = 52; String uri2 = OTPUri.build_uri(hdata, name2, whatever2, counter); Console.WriteLine("TOTP URI 1: `" + uri1 + "`\n"); Console.WriteLine("HOTP URI 2: `" + uri2 + "`\n"); // ///////////////////////////////////////////////////////////// // BASE32 Stuff // // ///////////////////////////////////////////////////////////// // Already seeded the random generator and popped the first result const int BASE32_LEN = 16; byte[] base32_new_secret = null; try { base32_new_secret = tdata.random_base32(BASE32_LEN, OTP.DEFAULT_BASE32_CHARS); Console.WriteLine("Generated BASE32 Secret: `" + (Encoding.ASCII.GetString(base32_new_secret)) + "`"); } catch (BASE32FormatError e) { Console.WriteLine(e); Console.WriteLine("Did not generate a valid base32 byte array"); Environment.Exit(1); } Console.WriteLine(""); // line break for readability // ///////////////////////////////////////////////////////////// // TOTP Stuff // // ///////////////////////////////////////////////////////////// // Get TOTP for a time block // 1. Generate and load totp key into buffer // 2. Check for error try { // totp.now int totp_err_1 = tdata.now(); Console.WriteLine("TOTP Generated: `" + totp_err_1 + "`"); // totp.at int totp_err_2 = tdata.at(1, 0); Console.WriteLine("TOTP Generated: `" + totp_err_2 + "`"); // Do a verification for a hardcoded code // Won't succeed, this code is for a timeblock far into the past bool tv1 = tdata.verify(576203, DateTimeOffset.Now.ToUnixTimeSeconds(), 4); // Will Succeed, timeblock 0 for JBSWY3DPEHPK3PXP == 282760 bool tv2 = tdata.verify(282760, 0, 4); Console.WriteLine("TOTP Verification 1: `" + tv1 + "`"); Console.WriteLine("TOTP Verification 2: `" + tv2 + "`"); } catch (Exception e) { // HMACGenerationError || BASE32FormatError Console.WriteLine(e); Console.WriteLine("TOTP Error 1"); Environment.Exit(1); } Console.WriteLine(""); // line break for readability // ///////////////////////////////////////////////////////////// // HOTP Stuff // // ///////////////////////////////////////////////////////////// // Get HOTP for token 1 // 1. Generate and load hotp key into buffer // 2. Check for error try { int hotp_err_1 = hdata.at(1); Console.WriteLine("HOTP Generated at 1: `" + hotp_err_1 + "`"); // Do a verification for a hardcoded code // Will succeed, 1 for JBSWY3DPEHPK3PXP == 996554 bool hv = hdata.verify(996554, 1); Console.WriteLine("HOTP Verification 1: `" + hv + "`"); } catch (Exception e) { // HMACGenerationError || BASE32FormatError Console.WriteLine(e); Console.WriteLine("HOTP Error 1"); Environment.Exit(1); } Console.ReadLine(); }
public void TOTP_Calc() { using( var totp = new TOTP<HMACSHA1>("7777777777777777") ) { Assert.AreEqual("724477", totp.Calculate(Environment.UnixEpochDateTime)); Assert.AreEqual("683298", totp.Calculate(30)); Assert.AreEqual("891123", totp.Calculate(60)); } using( var totp = new TOTP<HMACSHA1>("JBSWY3DPK5XXE3DE", 60) ) { Assert.AreEqual("495334", totp.Calculate(Environment.UnixEpochDateTime)); Assert.AreEqual("495334", totp.Calculate(30)); Assert.AreEqual("052202", totp.Calculate(60)); } }