Last active
December 15, 2016 20:50
-
-
Save jittuu/f21bd23270fb734edfb6092451ab159c to your computer and use it in GitHub Desktop.
This file contains 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 main | |
import ( | |
"encoding/base32" | |
"encoding/binary" | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
const fourDays = time.Hour * 24 * 4 | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
for i := 0; i < 5; i++ { | |
data := gen(uint16(randInt(0, 6454))) | |
crockford := base32.NewEncoding("0123456789ABCDEFGHJKMNPQRSTVWXYZ") | |
str := crockford.EncodeToString(data[:]) | |
fmt.Println(data) | |
fmt.Println(str) | |
} | |
} | |
func gen(counter uint16) [5]byte { | |
// 1 byte => random number | |
// 2 bytes => epoch / 4 days (so it will change every 4 days) (2 bytes is enough for until year 2500) | |
// 2 bytes => counter (auto increase number) | |
var buf [5]byte | |
r := byte(randInt(0, 256)) | |
buf[0] = r | |
ts := uint16(time.Now().UTC().UnixNano() / int64(fourDays)) | |
binary.LittleEndian.PutUint16(buf[1:3], ts) | |
binary.LittleEndian.PutUint16(buf[3:], counter) | |
return buf | |
} | |
func randInt(min int, max int) int { | |
return min + rand.Intn(max-min) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment