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

ValidateTotp Issue #53

Open
x2affy opened this issue Nov 10, 2023 · 0 comments
Open

ValidateTotp Issue #53

x2affy opened this issue Nov 10, 2023 · 0 comments

Comments

@x2affy
Copy link

x2affy commented Nov 10, 2023

Can some please help with this as i am stuck really.
If i create the QRcode and set it up with an authnticator the validate all works fine.
However if i generate the secret and store this, then use it to create a TOTP and try to validate this, it always fails?
I want to use email validation as well as an authenticator app.
So i am generating an email with the totp created using the stored secret, but it fails validation.

Can some please help or point me in the right direction with this?

public class TotpManager : ITotpManager
{
private readonly string _qrCodeImagePrefix = "data:image/png;base64,";
private readonly string _totpAuthPrefix = "otpauth://totp/";

public string GenerateBase32Secret()
{
    var bytes = KeyGeneration.GenerateRandomKey(20);
    return Base32Encoding.ToString(bytes);
}

public string GenerateTotp(string base32Secret)
{
    var secretBytes = Base32Encoding.ToBytes(base32Secret);
    var totp = new Totp(secretBytes);
    return totp.ComputeTotp();
}
public string GenerateTotp(string base32Secret, int step)
{
    var secretBytes = Base32Encoding.ToBytes(base32Secret);
    var totp = new Totp(secretBytes, step);
    return totp.ComputeTotp();
}

public bool ValidateTotp(string base32Secret, string totp)
{
    var secretBytes = Base32Encoding.ToBytes(base32Secret);
    var totpValidator = new Totp(secretBytes);
    return totpValidator.VerifyTotp(totp, out _);
}

public string GenerateQrCodeUrl(string issuer, string accountName, string base32Secret)
{
    string totpUrl =
        $"{_totpAuthPrefix}{Uri.EscapeDataString(issuer)}:{Uri.EscapeDataString(accountName)}?secret={base32Secret}&issuer={Uri.EscapeDataString(issuer)}&algorithm=SHA1&digits=6&period=30";

    var qrGenerator = new QRCodeGenerator();
    var qrCodeData = qrGenerator.CreateQrCode(totpUrl, QRCodeGenerator.ECCLevel.Q);
    var qrCode = new QRCode(qrCodeData);

    using MemoryStream ms = new MemoryStream();
    using Bitmap qrCodeImage = qrCode.GetGraphic(20);
    qrCodeImage.Save(ms, ImageFormat.Png);
    byte[] qrCodeBytes = ms.ToArray();

    return $"{_qrCodeImagePrefix}{Convert.ToBase64String(qrCodeBytes)}";
}

}

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