Christian Giacomi

Generate random hex token using Go

Posted — Aug 15, 2019

In my previous post we saw how to create random hex strings in various languages, and since I have started working with Go I found I needed a random hex token again. So like we saw in nodejs when you need to create unique token of some type, which you might use in a user email verification or password reset scenario, you can easily generate a random hex string like this

const Crypto = require('crypto');

const buf = Crypto.randomBytes(30);
const token = buf.toString('hex');

console.log(token);

The following is how you can generate the same kind of hexadecimal string in Go

package main

import (
	"fmt"

	"crypto/rand"
	"encoding/hex"
)

// randToken generates a random hex value.
func randToken(n int) (string, error) {
	bytes := make([]byte, n)
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

func main() {
	token, _ := randToken(30)
	fmt.Println(token)
}

Please note you should not use the code above to generate any kind of password, or password related data in production. The code is meant only for random hex strings which can be used as short lived tokens.

If this post was helpful tweet it or share it.

See Also