summaryrefslogtreecommitdiffstats
path: root/gac.go
blob: 11d1910c6b5ea2e6fb60f09869b7b659b639d2e2 (plain)
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
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base32"
	"encoding/binary"
	"fmt"
	"strconv"
	"strings"
	"time"
)

const period = 30

func Code(secret string) (string, int) {
	t := time.Now().Unix()
	numIntervals := t / period
	remaining := period - (t - (numIntervals * period))
	return hotp(secret, numIntervals), int(remaining)
}

func hotp(secret string, counter int64) string {
	// algorithm from wikipedia (http://en.wikipedia.org/wiki/Google_Authenticator)

	key, err := base32.StdEncoding.DecodeString(secret)
	if err != nil {
		fmt.Println("secret is not base32 encoded.")
		return ""
	}

	message := make([]byte, 8)
	binary.BigEndian.PutUint64(message, uint64(counter))

	mac := hmac.New(sha1.New, key)
	mac.Write(message)
	hash := mac.Sum(nil)

	offset := hash[len(hash)-1] & 0xF
	truncatedHash := hash[offset : offset+4]

	var code int32
	truncatedBytes := bytes.NewBuffer(truncatedHash)
	err = binary.Read(truncatedBytes, binary.BigEndian, &code)
	if err != nil {
		fmt.Printf("could not read HMAC sum: %v\n", err)
		return ""
	}

	code = (code & 0x7FFFFFFF) % 1000000
	converted := strconv.Itoa(int(code))
	padLength := 6 - len(converted)
	return strings.Repeat("0", padLength) + converted
}