Skip to content

Commit

Permalink
Add tests for new secret key byte size
Browse files Browse the repository at this point in the history
  • Loading branch information
zesik committed Dec 18, 2016
1 parent cbe94ed commit 5255a9e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
20 changes: 12 additions & 8 deletions otp.go
Expand Up @@ -30,11 +30,11 @@ const (
)

const (
// Maximum digits of password code.
// maxCodeDigits represents maximum digits of password code.
maxCodeDigits = 8
)

// Gets the hash function specified by the algorithm enum.
// hash gets the hash function specified by the algorithm enum.
func (algorithm HashAlgorithm) hash() (func() hash.Hash, error) {
switch algorithm {
case HashAlgorithmSHA1:
Expand All @@ -48,19 +48,23 @@ func (algorithm HashAlgorithm) hash() (func() hash.Hash, error) {
}
}

// Generate new secret key.
func (algorithm HashAlgorithm) generateSecret() ([]byte, error) {
var keyByteSize int
// defaultKeyByteSize gets the default value of HMAC key size in bytes.
func (algorithm HashAlgorithm) defaultKeyByteSize() int {
switch algorithm {
case HashAlgorithmSHA1:
keyByteSize = 20
return 20
case HashAlgorithmSHA256:
keyByteSize = 32
return 32
case HashAlgorithmSHA512:
keyByteSize = 64
return 64
default:
panic("unknown hash algorithm")
}
}

// generateSecret generates a new secret key.
func (algorithm HashAlgorithm) generateSecret() ([]byte, error) {
keyByteSize := algorithm.defaultKeyByteSize()
secret := make([]byte, keyByteSize)
_, err := rand.Read(secret)
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions otp_test.go
Expand Up @@ -12,6 +12,9 @@ func TestNewHOTP(t *testing.T) {
generator, err := NewHOTP(algorithm, nil, 6)
assert.NoError(t, err)
assert.IsType(t, &hotpManager{}, generator)
hotp := generator.(*hotpManager)
assert.NotNil(t, hotp.secret)
assert.Len(t, hotp.secret, algorithm.defaultKeyByteSize())
}
}

Expand Down

0 comments on commit 5255a9e

Please sign in to comment.