From 3003b010e22f64d92fd9526945484052d8e25445 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Lukas=20=7E=20Znox=20/=20Pl=C3=A4nkler?= <60503970+Plaenkler@users.noreply.github.com> Date: Fri, 11 Aug 2023 20:34:05 +0200 Subject: [PATCH 1/2] [ADD] Possibility to regenerate key --- otp.go | 5 ++++- totp/totp.go | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/otp.go b/otp.go index 02b08f3..d66823d 100644 --- a/otp.go +++ b/otp.go @@ -46,6 +46,9 @@ var ErrGenerateMissingIssuer = errors.New("Issuer must be set") // When generating a Key, the Account Name must be set. var ErrGenerateMissingAccountName = errors.New("AccountName must be set") +// When regenerating a Key, the Secret must be set. +var ErrRegenerateMissingSecret = errors.New("Secret must be set") + // Key represents an TOTP or HTOP key. type Key struct { orig string @@ -55,8 +58,8 @@ type Key struct { // NewKeyFromURL creates a new Key from an TOTP or HOTP url. // // The URL format is documented here: -// https://github.com/google/google-authenticator/wiki/Key-Uri-Format // +// https://github.com/google/google-authenticator/wiki/Key-Uri-Format func NewKeyFromURL(orig string) (*Key, error) { s := strings.TrimSpace(orig) diff --git a/totp/totp.go b/totp/totp.go index a2fb7d5..d37a790 100644 --- a/totp/totp.go +++ b/totp/totp.go @@ -18,10 +18,11 @@ package totp import ( + "io" + "github.com/pquerna/otp" "github.com/pquerna/otp/hotp" "github.com/pquerna/otp/internal" - "io" "crypto/rand" "encoding/base32" @@ -205,3 +206,17 @@ func Generate(opts GenerateOpts) (*otp.Key, error) { return otp.NewKeyFromURL(u.String()) } + +// Restores a key from a secret opts.Secret must be set +func Regenerate(opts GenerateOpts) (*otp.Key, error) { + if opts.SecretSize == 0 { + return nil, otp.ErrRegenerateMissingSecret + } + var secret []byte + _, err := base32.StdEncoding.Decode(secret, opts.Secret) + if err != nil { + return nil, err + } + opts.Secret = secret + return Generate(opts) +} From 7e6936b68a0a773fd67d624da55c93106fc23979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Lukas=20=7E=20Znox=20/=20Pl=C3=A4nkler?= <60503970+Plaenkler@users.noreply.github.com> Date: Mon, 4 Sep 2023 00:16:45 +0200 Subject: [PATCH 2/2] [FIX] Secret size --- totp/totp.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/totp/totp.go b/totp/totp.go index d37a790..76f32c8 100644 --- a/totp/totp.go +++ b/totp/totp.go @@ -212,7 +212,7 @@ func Regenerate(opts GenerateOpts) (*otp.Key, error) { if opts.SecretSize == 0 { return nil, otp.ErrRegenerateMissingSecret } - var secret []byte + secret := make([]byte, base32.StdEncoding.DecodedLen(len(opts.Secret))) _, err := base32.StdEncoding.Decode(secret, opts.Secret) if err != nil { return nil, err