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

use custom io.Reader to generate Keys #45

Merged
merged 1 commit into from Oct 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion hotp/hotp.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package hotp

import (
"github.com/pquerna/otp"
"io"

"crypto/hmac"
"crypto/rand"
Expand Down Expand Up @@ -152,6 +153,8 @@ type GenerateOpts struct {
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
// Reader to use for generating HOTP Key.
Rand io.Reader
}

var b32NoPadding = base32.StdEncoding.WithPadding(base32.NoPadding)
Expand All @@ -175,14 +178,18 @@ func Generate(opts GenerateOpts) (*otp.Key, error) {
opts.Digits = otp.DigitsSix
}

if opts.Rand == nil {
opts.Rand = rand.Reader
}

// otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example

v := url.Values{}
if len(opts.Secret) != 0 {
v.Set("secret", b32NoPadding.EncodeToString(opts.Secret))
} else {
secret := make([]byte, opts.SecretSize)
_, err := rand.Read(secret)
_, err := opts.Rand.Read(secret)
if err != nil {
return nil, err
}
Expand Down
9 changes: 8 additions & 1 deletion totp/totp.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package totp
import (
"github.com/pquerna/otp"
"github.com/pquerna/otp/hotp"
"io"

"crypto/rand"
"encoding/base32"
Expand Down Expand Up @@ -142,6 +143,8 @@ type GenerateOpts struct {
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
// Reader to use for generating TOTP Key.
Rand io.Reader
}

var b32NoPadding = base32.StdEncoding.WithPadding(base32.NoPadding)
Expand Down Expand Up @@ -169,14 +172,18 @@ func Generate(opts GenerateOpts) (*otp.Key, error) {
opts.Digits = otp.DigitsSix
}

if opts.Rand == nil {
opts.Rand = rand.Reader
}

// otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example

v := url.Values{}
if len(opts.Secret) != 0 {
v.Set("secret", b32NoPadding.EncodeToString(opts.Secret))
} else {
secret := make([]byte, opts.SecretSize)
_, err := rand.Read(secret)
_, err := opts.Rand.Read(secret)
if err != nil {
return nil, err
}
Expand Down