otp
otp copied to clipboard
OTP Generated by Google Authenticator not validated by the Library's OTP
I am using this library to generate a QR code that I connect to Google Authenticator. However, the OTP generated by Google Authenticator doesn't get validated by the library.
version of package
github.com/pquerna/otp v1.4.0
go version
go version go1.22.4 linux/amd64
code:
package main
import (
"fmt"
"image/png"
"log"
"os"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
func main() {
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "localhost:8000",
AccountName: "[email protected]",
SecretSize: 32,
})
if err != nil {
log.Fatalf("Failed to generate OTP: %v", err)
}
qrImage, err := key.Image(256, 256)
if err != nil {
log.Fatalf("Failed to generate QR code image: %v", err)
}
file, err := os.Create("otp_qrcode.png")
if err != nil {
log.Fatalf("Failed to create file for QR code: %v", err)
}
defer file.Close()
if err := png.Encode(file, qrImage); err != nil {
log.Fatalf("Failed to save QR code image: %v", err)
}
fmt.Println("QR code generated and saved as otp_qrcode.png")
fmt.Print("Enter the OTP code from your authenticator app: ")
var otpCode string
fmt.Scanln(&otpCode)
valid := totp.Validate(otpCode, key.Secret())
if valid {
fmt.Println("OTP verified successfully!")
} else {
fmt.Println("Invalid OTP code.")
}
}
to reproduce: Run the code provided above. Scan the generated QR code using Google Authenticator. Enter the OTP code displayed in Google Authenticator into the terminal.