Created
December 31, 2020 06:18
-
-
Save Mikubill/b29081169776808ccf738a44891daa72 to your computer and use it in GitHub Desktop.
simple otp module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package otp | |
import ( | |
"bytes" | |
"crypto/hmac" | |
"crypto/sha1" | |
"encoding/binary" | |
"strconv" | |
"strings" | |
"time" | |
) | |
func getHOTPToken(key []byte, interval int64) string { | |
bs := make([]byte, 8) | |
binary.BigEndian.PutUint64(bs, uint64(interval)) | |
hash := hmac.New(sha1.New, key) | |
hash.Write(bs) | |
h := hash.Sum(nil) | |
o := (h[19] & 15) | |
var header uint32 | |
r := bytes.NewReader(h[o : o+4]) | |
binary.Read(r, binary.BigEndian, &header) | |
h12 := (int(header) & 0x7fffffff) % 1000000 | |
otp := strconv.Itoa(int(h12)) | |
return strings.Repeat("0", 6 - len(otp)) + otp | |
} | |
func getTOTPToken(key []byte, sep, delta int64) string { | |
interval := time.Now().Unix()/sep + delta | |
return getHOTPToken(key, interval) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment