public void TimeCorrection_TotpComputeTotpSpecificDateWithCorrection() { var correction = new TimeCorrection(DateTime.UtcNow.AddSeconds(100)); // 100 ensures that at a minimum we are 3 steps away var correctedTotp = new Totp(OtpCalculationTests.RfcTestKey, timeCorrection: correction); var specificCode = correctedTotp.ComputeTotp(DateTime.UtcNow); var utcCode = correctedTotp.ComputeTotp(); Assert.AreEqual(specificCode, utcCode, "The 2 compute totp overloads didn't produce the same results"); }
public void ShowCodes(bool isShowCodes) { if (isShowCodes) { this.Code = totp.ComputeTotp(); this.NextCode = totp.ComputeTotp(DateTime.UtcNow.AddSeconds(30)); } else { this.Code = null; this.NextCode = null; } }
public void TotpUtcOverload() { var totp = new Totp(OtpCalculationTests.RfcTestKey); // we don't want this test to barely hit the time window crossover. // If there is at least 1 remaining second we should be OK while (totp.RemainingSeconds() == 0) { Thread.Sleep(100); } var code1 = totp.ComputeTotp(DateTime.UtcNow); var code2 = totp.ComputeTotp(); Assert.AreEqual(code1, code2); }
public static object GetKey2FA(string key) { object result; try { object obj; try { byte[] array = Base32Encoding.ToBytes(key.Trim().Replace(" ", "")); Totp totp = new Totp(array, 30, 0, 6, null); obj = totp.ComputeTotp(DateTime.UtcNow); goto IL_44; } catch (Exception) { } obj = null; IL_44: result = obj; } catch (Exception exception) { return(""); } return(result); }
private async Task <ResultWithError <ErrorData> > Process(GenerateRemoteMultiFactorAuthCodeCommand request, CancellationToken cancellationToken) { var currentUserMaybe = this._currentUserService.CurrentUser; if (currentUserMaybe.HasNoValue) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound))); } var userMaybe = await this._userRepository.Find(this._currentUserService.CurrentUser.Value.UserId, cancellationToken); if (userMaybe.HasNoValue) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound))); } var user = userMaybe.Value; var totp = new Totp(user.SecurityStamp.ToByteArray()); var generated = totp.ComputeTotp(); user.AddDomainEvent(new MfaTokenGeneratedEvent( request.TwoFactorProvider, user.Id, generated)); return(ResultWithError.Ok <ErrorData>()); }
void otpCopyToolStripItem_Click(object sender, EventArgs e) { PwEntry entry; if (this.GetSelectedSingleEntry(out entry)) { if (!entry.Strings.Exists(OtpAuthData.StringDictionaryKey)) { if (MessageBox.Show("Must configure TOTP on this entry. Do you want to do this now?", "Not Configured", MessageBoxButtons.YesNo) == DialogResult.Yes) { ShowOneTimePasswords form = new ShowOneTimePasswords(entry, host); form.ShowDialog(); } } else { var data = OtpAuthData.FromString(entry.Strings.Get(OtpAuthData.StringDictionaryKey).ReadString()); var totp = new Totp(data.Key, step: data.Step, mode: data.OtpHashMode, totpSize: data.Size); var text = totp.ComputeTotp().ToString().PadLeft(data.Size, '0'); if (ClipboardUtil.CopyAndMinimize(new KeePassLib.Security.ProtectedString(true, text), true, this.host.MainWindow, entry, this.host.Database)) { this.host.MainWindow.StartClipboardCountdown(); } } } }
private string GenerateOtp() { byte[] otpKey = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); Totp totp = new Totp(otpKey, 600); return(totp.ComputeTotp()); }
private async Task <ResultWithError <ErrorData> > Process(CancellationToken cancellationToken) { var currentUserMaybe = this._currentAuthenticatedUserProvider.CurrentAuthenticatedUser; if (currentUserMaybe.HasNoValue) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound))); } var userMaybe = await this._userRepository.Find(currentUserMaybe.Value.UserId, cancellationToken); if (userMaybe.HasNoValue) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound))); } var user = userMaybe.Value; var totp = new Totp(user.SecurityStamp.ToByteArray()); var token = totp.ComputeTotp(); user.AddDomainEvent(new EmailMfaTokenGeneratedEvent( user.EmailAddress, user.Profile.FirstName, user.Profile.LastName, token)); user.ProcessPartialSuccessfulAuthenticationAttempt( this._clock.GetCurrentInstant().ToDateTimeUtc(), AuthenticationHistoryType.EmailMfaRequested); return(ResultWithError.Ok <ErrorData>()); }
public string GenerateTotpCode(User user) { var totpSecretKey = Base32Encoding.ToBytes(user.TotpSecretKey); var totp = new Totp(totpSecretKey); return(totp.ComputeTotp()); }
public string Generate(string purpose, string entity) { byte[] secret = Encoding.Unicode.GetBytes(entity + purpose); Totp code = new Totp(secret, step: _expire, mode: OtpHashMode.Sha512, totpSize: _length); return(code.ComputeTotp()); }
public static string GenerateVoucherCode(string userNumber) { var secretKey = Encoding.UTF8.GetBytes(userNumber); var totp = new Totp(secretKey); return(totp.ComputeTotp()); }
static int Main(string[] args) { if (!CommandLineSwitch.TryParse <Options>(ref args, out var options, out var err)) { Console.WriteLine($"ERROR: {err}"); return(-1); } if (string.IsNullOrEmpty(options.Key)) { Console.WriteLine("ERROR: Secret Key is not specified."); ShowUsage(); return(-1); } var secretKey = default(byte[]); try { secretKey = Base32Encoding.ToBytes(options.Key); } catch (ArgumentException) { Console.WriteLine("ERROR: Invalid key format."); return(-1); } var totp = new Totp(secretKey); var totpCode = totp.ComputeTotp(); Console.WriteLine(totpCode); return(0); }
/// <summary> /// 计算token-指定时间 /// </summary> /// <param name="secretKey"></param> /// <param name="timestamp"></param> /// <returns></returns> public static string ComputeToken(string secretKey, long timestamp) { var otp = new Totp(GetSecretKeyBytes(secretKey)); var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp); return(otp.ComputeTotp(dt.UtcDateTime)); }
public string sendOTP(string _phonenumber) { var totp = new Totp(Encoding.ASCII.GetBytes(_reusablekey), step: 300, totpSize: 4); var totpCode = totp.ComputeTotp(DateTime.UtcNow); return(totpCode); }
public async Task Handle_GiveUserDoesExistButHasNoAuthApp_ExpectFailedResult() { var user = new Mock <IUser>(); var userId = Guid.NewGuid(); user.Setup(x => x.Id).Returns(userId); user.Setup(x => x.AuthenticatorApps).Returns(new List <AuthenticatorApp>()); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(user.Object)); var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>(); currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser) .Returns(Maybe.From(new UnauthenticatedUser(TestVariables.UserId, MfaProvider.None) as ISystemUser)); var handler = new ValidateAppMfaCodeAgainstCurrentUserCommandHandler( userRepository.Object, currentAuthenticatedUserProvider.Object); var totp = new Totp(Base32Encoding.ToBytes("key")); var code = totp.ComputeTotp(); var cmd = new ValidateAppMfaCodeAgainstCurrentUserCommand(code); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsFailure); Assert.Equal(ErrorCodes.NoAuthenticatorAppEnrolled, result.Error.Code); }
public async Task Handle_GivenSavingFails_ExpectFailedResult() { var user = new Mock <IUser>(); user.Setup(x => x.AuthenticatorApps).Returns(() => new List <AuthenticatorApp>()); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => false); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(user.Object)); var clock = new Mock <IClock>(); var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>(); currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser) .Returns(Maybe.From(new AuthenticatedUser(TestVariables.UserId, "email-address", "first-name", "last-name") as ISystemUser)); var commandHandler = new EnrollAuthenticatorAppCommandHandler(userRepository.Object, clock.Object, currentAuthenticatedUserProvider.Object); var key = KeyGeneration.GenerateRandomKey(); var keyAsBase32String = Base32Encoding.ToString(key); var totp = new Totp(key); var code = totp.ComputeTotp(); var cmd = new EnrollAuthenticatorAppCommand(keyAsBase32String, code); var result = await commandHandler.Handle(cmd, CancellationToken.None); Assert.True(result.IsFailure); Assert.Equal(ErrorCodes.SavingChanges, result.Error.Code); }
public async Task UpdateDanceCampBookingPaymentStatus(string transactionId, bool success) { try { _logger.Information($"transactionID: {transactionId}"); var booking = _bookingPaymentRepository.GetBookingPayment(transactionId); _logger.Information($"booking ID is: {booking.BookingId}"); byte[] secretKeyByteArray = Base32Encoding.ToBytes(_danceCampOptions.SecretKey); var totp = new Totp(secretKeyByteArray, 30, OtpHashMode.Sha1, 6); var totpCode = totp.ComputeTotp(); string status = success ? "Completed" : "Payment Failed"; var formContent = new FormUrlEncodedContent( new[] { new KeyValuePair <string, string>("BookingID", booking.BookingId.ToString()), new KeyValuePair <string, string>("APIToken", _danceCampOptions.ApiToken), new KeyValuePair <string, string>("Token", totpCode), new KeyValuePair <string, string>("Status", status), new KeyValuePair <string, string>("Amount", booking.Amount.ToString("F02", CultureInfo.InvariantCulture)), new KeyValuePair <string, string>("Currency", "EUR"), new KeyValuePair <string, string>("TxnID", transactionId), new KeyValuePair <string, string>("FeeAmount", "0"), new KeyValuePair <string, string>("Notes", ""), new KeyValuePair <string, string>("EmailNotes", "") }); var response = await _httpClient.PostAsync(_danceCampOptions.PaymentReceiveDanceCampUrl, formContent); if (response.StatusCode == HttpStatusCode.OK) { var stringContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject <DanceCampResponse>(stringContent); if (result.Status != "success") { //TODO: discuss notification options. //There is a chance that mollie payment is successful but update to dancecamp system failed //Generate notification email? _logger.Error($"Request to Dance Camp was not successfull, transaction id {transactionId}", response); } } else { _logger.Error($"Request to Dance Camp was not successfull, transaction id {transactionId}", response); } } catch (Exception e) { //TODO: discuss notification options. //There is a chance that mollie payment is successful but update to dancecamp system failed //Generate notification email? _logger.Error($"Error occured while sending Payment Receive to Dance Camp for transaction {transactionId}. Error: {e.Message}", e); } }
public async Task Handle_GivenCodeDoesVerify_ExpectSuccessfulResultAndEnrollAttempted() { var user = new Mock <IUser>(); user.Setup(x => x.AuthenticatorApps).Returns(() => new List <AuthenticatorApp>()); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(user.Object)); var clock = new Mock <IClock>(); var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>(); currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser) .Returns(Maybe.From(new AuthenticatedUser(TestVariables.UserId, "email-address", "first-name", "last-name") as ISystemUser)); var commandHandler = new EnrollAuthenticatorAppCommandHandler(userRepository.Object, clock.Object, currentAuthenticatedUserProvider.Object); var key = KeyGeneration.GenerateRandomKey(); var keyAsBase32String = Base32Encoding.ToString(key); var totp = new Totp(key); var code = totp.ComputeTotp(); var cmd = new EnrollAuthenticatorAppCommand(keyAsBase32String, code); var result = await commandHandler.Handle(cmd, CancellationToken.None); Assert.True(result.IsSuccess); user.Verify( x => x.EnrollAuthenticatorApp(It.IsAny <Guid>(), It.IsAny <string>(), It.IsAny <DateTime>()), Times.Once); }
public TotpModel GetPassword(int secret) { _totp = new Totp(BitConverter.GetBytes(secret)); return(new TotpModel { TotpPassword = _totp.ComputeTotp(DateTime.UtcNow), RemainingTime = _totp.RemainingSeconds() }); }
public async Task Handle_GivenSavingFails_ExpectFailedResult() { var securityStamp = Guid.NewGuid(); var user = new Mock <IUser>(); user.Setup(x => x.Profile).Returns(new Profile(TestVariables.UserId, "first-name", "last-name")); user.Setup(x => x.SecurityStamp).Returns(securityStamp); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => false); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From <IUser>(user.Object)); var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>(); currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser) .Returns(Maybe.From(new UnauthenticatedUser(TestVariables.UserId, MfaProvider.None) as ISystemUser)); var clock = new Mock <IClock>(); var handler = new ValidateEmailMfaCodeAgainstCurrentUserCommandHandler(userRepository.Object, currentAuthenticatedUserProvider.Object, clock.Object); var totp = new Totp(securityStamp.ToByteArray()); var code = totp.ComputeTotp(); var cmd = new ValidateEmailMfaCodeAgainstCurrentUserCommand(code); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsFailure); Assert.Equal(ErrorCodes.SavingChanges, result.Error.Code); }
static public bool CheckOtp(string otpValue) { Logger.Log("Start CheckOtp"); try { Init(); if (lastCheckValue == otpValue) { return(false); } long timeStepMatched = 0; string computeValue = otp.ComputeTotp(); var window = new VerificationWindow(previous: 1, future: 1); if (otp.VerifyTotp(otpValue, out timeStepMatched, window)) { lastCheckValue = otpValue; return(true); } } catch (Exception e) { Logger.Log(e.ToString()); } Logger.Log("Finish CheckOtp"); return(false); }
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 async Task Handle_GivenSavingSucceeds_ExpectSuccessfulResult() { var user = new Mock <IUser>(); user.Setup(x => x.Profile).Returns(new Profile(TestVariables.UserId, "first-name", "last-name")); user.Setup(x => x.AuthenticatorApps).Returns(new List <AuthenticatorApp> { new AuthenticatorApp(Guid.NewGuid(), "key", DateTime.UtcNow), }); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.Find(It.IsAny <Guid>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(user.Object)); var currentAuthenticatedUserProvider = new Mock <ICurrentAuthenticatedUserProvider>(); currentAuthenticatedUserProvider.Setup(x => x.CurrentAuthenticatedUser) .Returns(Maybe.From(new UnauthenticatedUser(TestVariables.UserId, MfaProvider.None) as ISystemUser)); var handler = new ValidateAppMfaCodeAgainstCurrentUserCommandHandler( userRepository.Object, currentAuthenticatedUserProvider.Object); var totp = new Totp(Base32Encoding.ToBytes("key")); var code = totp.ComputeTotp(); var cmd = new ValidateAppMfaCodeAgainstCurrentUserCommand(code); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsSuccess); }
public static async Task <bool> CheckToken(Token token, byte[] otpSecret, HttpClient httpClient) { var totp = new Totp(otpSecret, token.Period); var totpToken = totp.ComputeTotp(DateTime.UtcNow); var data = new List <string>(); data.AddRange(totpToken.Select((t, i) => $"cr{i + 1}={t}")); data.Add($"cred={token.Id}"); data.Add("continue=otp_check"); var request = string.Join("&", data); var content = new StringContent(request, Encoding.UTF8, "application/x-www-form-urlencoded"); var req = new HttpRequestMessage(HttpMethod.Post, TEST_URL); req.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("*/*")); req.Content = content; var result = await httpClient.SendAsync(req); var resultTxt = await result.Content.ReadAsStringAsync(); if (resultTxt.Contains("Your VIP Credential is working correctly")) { return(true); } else { return(false); } }
public string Generate() { var secret = BotConfigurator.SecureCode; var totpgen = new Totp(Base32Encoding.Standard.ToBytes(secret), timeCorrection: new TimeCorrection(System.DateTime.UtcNow)); return(totpgen.ComputeTotp()); }
public void TotpAppendixBTests(Rfc6238AppendixBData data) { Assert.IsNotNull(data, "data was null"); var totpCalculator = new Totp(data.RfcTestKey.ToArray(), mode: data.Mode, totpSize: 8); var totp = totpCalculator.ComputeTotp(data.Time); Assert.AreEqual(data.Totp, totp); }
public void ComputeTOTPTest(string secret, OtpHashMode hash, long timestamp, string expectedOtp) { Totp otpCalc = new Totp(Encoding.UTF8.GetBytes(secret), 30, hash, expectedOtp.Length); DateTime time = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime; string otp = otpCalc.ComputeTotp(time); Assert.That(otp, Is.EqualTo(expectedOtp)); }
/// <summary> /// 获取 验证码 /// </summary> /// <param name="publicKey">base32密钥</param> /// <returns></returns> public string VerificationCode(string publicKey) { var key = Base32Encoding.ToBytes(publicKey); Totp totp = new Totp(key); var result = totp.ComputeTotp(DateTime.UtcNow); return(result); }
private string GetTOTPCode(string token) { var bytes = Base32Encoding.ToBytes(token); var totp = new Totp(bytes); return(totp.ComputeTotp()); }
public void Totp6DigitPaddingTest() { var totpCalculator = new Totp(RfcTestKey, totpSize: 6); var date = new DateTime(1970, 1, 19, 13, 23, 00); var totp = totpCalculator.ComputeTotp(date); Assert.AreEqual("003322", totp); }