分享
go1.5 动态密码,最简单的实现使用hmac加密
fyxichen · · 2753 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
package main
import (
"crypto/hmac"
"crypto/sha512"
"fmt"
"strconv"
"time"
)
type Key struct {
gkey string
skey string
date func() int64
}
const (
Gkey = "What"
)
func main() {
K := &Key{gkey: Gkey, date: getdate}
b := hmac.New(sha512.New, []byte(K.Hmac("Hello World")))
B := b.Sum(nil)
offset := B[len(B)-1] & 0xf
x := ((int(B[offset+1]) & 0xff) << 16) | ((int(B[offset+2]) & 0xff) << 8) | (int(B[offset+3]) & 0xff)
z := fmt.Sprint(x % 1000000)
for len(z) < 6 {
z = fmt.Sprintf("0%s", z)
}
fmt.Println(z)
}
func (self *Key) Hmac(Skey string) string {
return fmt.Sprintf("%s%s%d", self.gkey, Skey, self.date())
}
func getdate() int64 {
T := time.Now()
format_T := T.Format("0601021504")
unix_T := T.Unix() - T.Unix()%30
num, _ := strconv.Atoi(format_T)
x := num % 10
return unix_T<<uint(x) ^ int64(num)>>uint(x)
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信2753 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
package main
import (
"crypto/hmac"
"crypto/sha512"
"fmt"
"strconv"
"time"
)
type Key struct {
gkey string
skey string
date func() int64
}
const (
Gkey = "What"
)
func main() {
K := &Key{gkey: Gkey, date: getdate}
b := hmac.New(sha512.New, []byte(K.Hmac("Hello World")))
B := b.Sum(nil)
offset := B[len(B)-1] & 0xf
x := ((int(B[offset+1]) & 0xff) << 16) | ((int(B[offset+2]) & 0xff) << 8) | (int(B[offset+3]) & 0xff)
z := fmt.Sprint(x % 1000000)
for len(z) < 6 {
z = fmt.Sprintf("0%s", z)
}
fmt.Println(z)
}
func (self *Key) Hmac(Skey string) string {
return fmt.Sprintf("%s%s%d", self.gkey, Skey, self.date())
}
func getdate() int64 {
T := time.Now()
format_T := T.Format("0601021504")
unix_T := T.Unix() - T.Unix()%30
num, _ := strconv.Atoi(format_T)
x := num % 10
return unix_T<<uint(x) ^ int64(num)>>uint(x)
}