首先安装OTP 库
go get github.com/pquerna/otp
安装完成之后可以用top库生成需要的Authenticator
dataMap := make(map[string]string)
// 生成一个随机的密钥
key, err2 := totp.Generate(totp.GenerateOpts{
Issuer: "xxx",
AccountName: "xxx",
})
//生成的信息可以存储到mysql 或者redis 里面方便下次验证
dataMap["SecretKey"] = key.Secret() //生成的 密钥
dataMap["UrlKey"] = key.URL() //生成的二维码链接 ,可以通过链接进行二维码绑定到应用上
// 验证 OTP 码 code 是用户输入的
valid := totp.Validate(code, dataMap["SecretKey"])
if valid {
fmt.Println("OTP 验证通过")
} else {
fmt.Println("OTP 验证失败")
}
也可以根据业务实现一次性的验证方式
大概步骤就是:
- 使用
totp.Generate
函数生成一个随机的密钥(key),可以指定发行者(Issuer)和账户名(AccountName)。 - 使用
totp.GenerateCode
函数根据密钥和当前时间生成 OTP 码。otp.CurrentTime()
函数用于获取当前时间。code, err := totp.GenerateCode(key.Secret(), otp.CurrentTime()) if err != nil { fmt.Printf("Error generating code: %s\n", err) return }
- 打印生成的 OTP 码。
- 使用
totp.Validate
函数验证 OTP 码是否正确,传入 OTP 码和密钥进行验证。
更多玩法需要大家自己diy了