2FA为two Factor-Authentication,双因素验证,也就是账户的二级密码。常见的就是TOTP(Time-Based One-Time Password algorithm)基于时间的一次性密码
还有基于计数的一次性密码HOTP(HMAC-Based One-Time Password algorithm)、基于手机短信的SMS 2FA,等生物身份认证标志来保护账号安全。
用户可以在移动设备中安装如Google Authentication或Microsoft Authentication这类应用,将密钥存入,并为添加的密钥设置标志名称(Issuer),用于辨别。
安装依赖
go get github.com/pquerna/otpTOTP代码
关键数据只有密钥,密钥和AccountName之间没有联系。
package main
import (
"fmt"
"image/png"
"log"
"os"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
func main() {
// 生成密钥
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "My First App", //应用名称
AccountName: "123456@qq.com", //用户账号
Period: 30, //每个一次性密码的有效时间,默认30秒
Digits: 6, //一次性密码(令牌)的位数,默认6,改成其它的值好像无效,验证器里还是6位~~
Algorithm: otp.AlgorithmSHA512, //默认SHA1,列表:MD5、SHA1、SHA256、SHA512
})
if err != nil {
log.Fatal(err)
}
// 打印密钥(用户可以将这个密钥保存在安全地方)
fmt.Println("Secret Key:", key.Secret())
//输出如:otpauth://totp/My%20First%20App:82406064@qq.com?algorithm=SHA1&digits=8&issuer=My%20First%20App&period=30&secret=L5PUWWG4EXUEQ2NWREUP7TUQGJP5HK3B
fmt.Println("Scan QR Code at URL:", key.URL())
//上面URL的二维码形式:
img, err := key.Image(200, 200)
file, _ := os.Create("./1.png")
defer file.Close()
png.Encode(file, img)
}
验证一次性密码:
totp.Validate("123456", "L51UWWG4EXU3Q2NWR7UP7TUQGJP5HK3B")