File: hotp_test.go

package info (click to toggle)
golang-github-gokyle-twofactor 1.0.1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 120 kB
  • sloc: makefile: 2
file content (67 lines) | stat: -rw-r--r-- 1,625 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package twofactor

import (
	"fmt"
	"testing"
)

var testKey = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

func newZeroHOTP() *HOTP {
	return NewHOTP(testKey, 0, 6)
}

var rfcHotpKey = []byte("12345678901234567890")
var rfcHotpExpected = []string{
	"755224",
	"287082",
	"359152",
	"969429",
	"338314",
	"254676",
	"287922",
	"162583",
	"399871",
	"520489",
}

// This test runs through the test cases presented in the RFC, and
// ensures that this implementation is in compliance.
func TestHotpRFC(t *testing.T) {
	otp := NewHOTP(rfcHotpKey, 0, 6)
	for i := 0; i < len(rfcHotpExpected); i++ {
		if otp.Counter() != uint64(i) {
			fmt.Printf("twofactor: invalid counter (should be %d, is %d",
				i, otp.Counter())
			t.FailNow()
		}
		code := otp.OTP()
		if code == "" {
			fmt.Printf("twofactor: failed to produce an OTP\n")
			t.FailNow()
		} else if code != rfcHotpExpected[i] {
			fmt.Printf("twofactor: invalid OTP\n")
			fmt.Printf("\tExpected: %s\n", rfcHotpExpected[i])
			fmt.Printf("\t  Actual: %s\n", code)
			fmt.Printf("\t Counter: %d\n", otp.counter)
			t.FailNow()
		}
	}
}

// This test uses a different key than the test cases in the RFC,
// but runs through the same test cases to ensure that they fail as
// expected.
func TestHotpBadRFC(t *testing.T) {
	otp := NewHOTP(testKey, 0, 6)
	for i := 0; i < len(rfcHotpExpected); i++ {
		code := otp.OTP()
		if code == "" {
			fmt.Printf("twofactor: failed to produce an OTP\n")
			t.FailNow()
		} else if code == rfcHotpExpected[i] {
			fmt.Printf("twofactor: should not have received a valid OTP\n")
			t.FailNow()
		}
	}
}