package totp import ( "testing" "time" ) // RFC 6238 appendix B, SHA1 test vectors for the ASCII key "12345678901234567890". func TestRFC6238Vectors(t *testing.T) { const secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" // base32 of the RFC key for _, tc := range []struct { unix int64 want string }{ {59, "287082"}, {1111111109, "081804"}, {1111111111, "050471"}, {1234567890, "005924"}, {2000000000, "279037"}, } { got, err := Code(secret, time.Unix(tc.unix, 0)) if err != nil { t.Fatal(err) } if got != tc.want { t.Errorf("Code at %d = %s, want %s", tc.unix, got, tc.want) } } } func TestCheckAcceptsDriftAndRejectsJunk(t *testing.T) { s := NewSecret() now := time.Now() c, _ := Code(s, now) if !Check(s, c, now.Add(29*time.Second)) { t.Fatal("code within drift window rejected") } if Check(s, c, now.Add(5*time.Minute)) { t.Fatal("stale code accepted") } for _, bad := range []string{"", "12345", "abcdef", "1234567"} { if Check(s, bad, now) { t.Fatalf("junk code %q accepted", bad) } } }