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

[ADD] Possibility to regenerate key #84

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion otp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand Down
17 changes: 16 additions & 1 deletion totp/totp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
}