Created
November 27, 2021 09:46
-
-
Save ulexxander/f6d172ae2376eb9956d61c3c020704f1 to your computer and use it in GitHub Desktop.
Generate random hex token
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 random | |
import ( | |
"crypto/rand" | |
"encoding/hex" | |
"fmt" | |
) | |
func TokenHex(length int) (string, error) { | |
// Base 16 is 2x longer than Base 256 | |
// 2^8 vs 2^4 | |
// 8bits / 4bits = 2x ratio | |
buf := make([]byte, length/2) | |
_, err := rand.Read(buf) | |
if err != nil { | |
return "", fmt.Errorf("reading rand: %w", err) | |
} | |
h := hex.EncodeToString(buf) | |
return h, nil | |
} | |
func TestTokenHex(t *testing.T) { | |
l := 16 | |
h, err := random.TokenHex(l) | |
if err != nil { | |
t.Fatalf("unexpected error: %s", err) | |
} | |
if len(h) != l { | |
t.Errorf("expected len %d, got: %d", l, len(h)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment