Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VerifyTotp always fails #63

Open
zyz opened this issue Jun 19, 2024 · 1 comment
Open

VerifyTotp always fails #63

zyz opened this issue Jun 19, 2024 · 1 comment

Comments

@zyz
Copy link

zyz commented Jun 19, 2024

1.VS 2022:New ASP.NET Core Web (Model-Model-Controller)
2.Install-Package Otp.NET, Install-Package QRCoder
3.HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Web.Models;
using OtpNet;
using QRCoder;
using System.Text;

public class HomeController : Controller
{
private readonly ILogger _logger;
private const string Secret = "JBSWY3DPEHPK3PXP";
private const string BaseUser = "test";
private const string Issuer = "demo";

public HomeController(ILogger<HomeController> logger)
{
    _logger = logger;
}

public IActionResult Index()
{
    return View();
}

public IActionResult Qrcode()
{
    string uriString = new OtpUri(OtpType.Totp, Secret, BaseUser, Issuer).ToString();

    using QRCodeGenerator qrGenerator = new();
    using QRCodeData qrCodeData = qrGenerator.CreateQrCode(uriString, QRCodeGenerator.ECCLevel.Q);
    using PngByteQRCode qrCode = new(qrCodeData);
    {
        byte[] qrCodeImage = qrCode.GetGraphic(20);
        return File(qrCodeImage, "image/jpeg");
    }
}

public IActionResult Validate(string code)
{
    var totp = new Totp(Encoding.UTF8.GetBytes(Secret));
    var verificationWindow = VerificationWindow.RfcSpecifiedNetworkDelay;
    var isValid = totp.VerifyTotp(code, out long timeWindowUsed, verificationWindow);
    return Content(isValid ? "Success" : "Fail");
}

}
4.Views/Home/Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<img src="/Home/Qrcode" style="width: 300px;" />
<form action="/Home/Validate" method="post">
Code: <input name="code" />
<input type="submit" value="Validate" />
</form>
</div>
5.run
6.Scan the QR code using APP Authenticator
7.Enter totp code, VerifyTotp always fails

@zyz
Copy link
Author

zyz commented Jun 20, 2024

Use Base32Encoding.ToBytes to resolve
var totp = new Totp(Base32Encoding.ToBytes(Secret));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant