Google Authenticator 二次验证

Google Authenticator 使用一次性密码(One-time Passcodes)(OTP)进行两步验证。

广泛应用于网站或APP登录二次验证。

Google Authenticator常用基于时间的一次性密码(Time-based One-time Password,简称TOTP),

只需要在手机上安装该APP,就可以生成一个随着时间变化的一次性密码,用于帐户验证。

另一个采用增量式计数器(HOTP)的方式,需要不断和服务器同步。

Go实现

每隔30s会动态生成一个6位数的数字,只要手机端时间与服务器时间误差不超过30秒,基本上生成生成动态口令一致。

  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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// @Title
// @Description from https://www.jianshu.com/p/5b3ccc5569e6
// @Author  55
// @Date  2021/9/16
package main

import (
    "crypto/hmac"
    "crypto/rand"
    "crypto/sha1"
    "encoding/base32"
    "fmt"
    "strings"
    "time"
)

func main() {

    fmt.Println("----------------- 生成secret -------------------")
    secret := GetSecret()
    fmt.Println("secret:" + secret)

    fmt.Println("----------------- 信息校验----------------------")
    var code int32
    fmt.Print("请输入Google Code:")
    for {
        _, err := fmt.Scan(&code)
        if err == nil {
            break
        }

        fmt.Print("输入错误,请重新输入:")
    }

    b := VerifyCode(secret, code)
    if b {
        fmt.Println("验证成功!")
    } else {
        fmt.Println("验证失败!")
    }
}

func GetSecret() string {
    randomStr := randStr(16)
    return strings.ToUpper(randomStr)
}

func randStr(strSize int) string {
    dictionary := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    var bytes = make([]byte, strSize)
    _, _ = rand.Read(bytes)
    for k, v := range bytes {
        bytes[k] = dictionary[v%byte(len(dictionary))]
    }
    return string(bytes)
}

// 为了考虑时间误差,判断前当前时间及前后30秒时间
func VerifyCode(secret string, code int32) bool {
    // 当前google值
    if getCode(secret, 0) == code {
        return true
    }

    // 前30秒google值
    if getCode(secret, -30) == code {
        return true
    }

    // 后30秒google值
    if getCode(secret, 30) == code {
        return true
    }

    return false
}

// 获取Google Code
func getCode(secret string, offset int64) int32 {
    key, err := base32.StdEncoding.DecodeString(secret)
    if err != nil {
        fmt.Println(err)
        return 0
    }

    // generate a one-time password using the time at 30-second intervals
    epochSeconds := time.Now().Unix() + offset
    return int32(oneTimePassword(key, toBytes(epochSeconds/30)))
}

// from https://github.com/robbiev/two-factor-auth/blob/master/main.go
func toBytes(value int64) []byte {
    var result []byte
    mask := int64(0xFF)
    shifts := [8]uint16{56, 48, 40, 32, 24, 16, 8, 0}
    for _, shift := range shifts {
        result = append(result, byte((value>>shift)&mask))
    }
    return result
}

func toUint32(bytes []byte) uint32 {
    return (uint32(bytes[0]) << 24) + (uint32(bytes[1]) << 16) +
        (uint32(bytes[2]) << 8) + uint32(bytes[3])
}

func oneTimePassword(key []byte, value []byte) uint32 {
    // sign the value using HMAC-SHA1
    hmacSha1 := hmac.New(sha1.New, key)
    hmacSha1.Write(value)
    hash := hmacSha1.Sum(nil)

    // We're going to use a subset of the generated hash.
    // Using the last nibble (half-byte) to choose the index to start from.
    // This number is always appropriate as it's maximum decimal 15, the hash will
    // have the maximum index 19 (20 bytes of SHA1) and we need 4 bytes.
    offset := hash[len(hash)-1] & 0x0F

    // get a 32-bit (4-byte) chunk from the hash starting at offset
    hashParts := hash[offset : offset+4]

    // ignore the most significant bit as per RFC 4226
    hashParts[0] = hashParts[0] & 0x7F

    number := toUint32(hashParts)

    // size to 6 digits
    // one million is the first number with 7 digits so the remainder
    // of the division will always return < 7 digits
    pwd := number % 1000000

    return pwd
}
 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
// from https://github.com/sunreaver/gotools/blob/master/googleauth/google_authenticator.go
package googleauth

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

// MakeGoogleAuthenticator 获取key&t对应的验证码
// key 秘钥
// t 1970年的秒
func MakeGoogleAuthenticator(key string, t int64) (string, error) {
	hs, e := hmacSha1(key, t/30)
	if e != nil {
		return "", e
	}
	snum := lastBit4byte(hs)
	d := snum % 1000000
	return fmt.Sprintf("%06d", d), nil
}

// MakeGoogleAuthenticatorForNow 获取key对应的验证码
func MakeGoogleAuthenticatorForNow(key string) (string, error) {
	return MakeGoogleAuthenticator(key, time.Now().Unix())
}

func lastBit4byte(hmacSha1 []byte) int32 {
	if len(hmacSha1) != sha1.Size {
		return 0
	}
	offsetBits := int8(hmacSha1[len(hmacSha1)-1]) & 0x0f
	p := (int32(hmacSha1[offsetBits]) << 24) | (int32(hmacSha1[offsetBits+1]) << 16) | (int32(hmacSha1[offsetBits+2]) << 8) | (int32(hmacSha1[offsetBits+3]) << 0)
	return (p & 0x7fffffff)
}

func hmacSha1(key string, t int64) ([]byte, error) {
	decodeKey, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(key)
	if err != nil {
		return nil, err
	}

	cData := make([]byte, 8)
	binary.BigEndian.PutUint64(cData, uint64(t))

	h1 := hmac.New(sha1.New, decodeKey)
	_, e := h1.Write(cData)
	if e != nil {
		return nil, e
	}
	return h1.Sum(nil), nil
}

参考