Skip to content

Instantly share code, notes, and snippets.

@inkeliz
Created March 24, 2019 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inkeliz/9754149ec8e0242d572b746ba7a9bf74 to your computer and use it in GitHub Desktop.
Save inkeliz/9754149ec8e0242d572b746ba7a9bf74 to your computer and use it in GitHub Desktop.
simple-totp
package main
import (
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"crypto/subtle"
"encoding/binary"
"fmt"
prf "hash"
"math"
)
func main() {
key := []byte("1234567890123456789012345678901234567890123456789012345678901234")
for _, unixtime := range []int64{59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000} {
fmt.Printf("%08d \n", Criar(sha1.New, key[0:20], unixtime, 30, 0, 8))
fmt.Printf("%08d \n", Criar(sha256.New, key[0:32], unixtime, 30, 0, 8))
fmt.Printf("%08d \n", Criar(sha512.New, key[0:64], unixtime, 30, 0, 8))
}
}
func Criar(h func() prf.Hash, chave []byte, tempo, intervalo, inicio int64, comprimento int) uint32 {
tempo = (tempo - inicio) / intervalo
derivacao := hmac.New(h, chave)
binary.Write(derivacao, binary.BigEndian, tempo)
hash := derivacao.Sum(nil)
posicao := hash[len(hash)-1] & 0x0F
hash = hash[posicao:posicao+4]
codigo := binary.BigEndian.Uint32(hash) & 0x7FFFFFFF
return codigo % uint32(math.Pow10(comprimento))
}
func Comparar(x, y uint32) int {
var xb, yb = make([]byte, 8), make([]byte, 8)
binary.LittleEndian.PutUint32(xb, x)
binary.LittleEndian.PutUint32(yb, y)
return subtle.ConstantTimeCompare(xb, yb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment