Crypto Rand UUID v4 With RFC 4122 Bits
Assemble RFC 4122 version-4 UUIDs from crypto/rand bytes by setting the version and variant bits, then format canonical hex groups.
Code
package main
import (
"crypto/rand"
"fmt"
)
// NewUUIDv4 从 crypto/rand 取 16 字节,按 RFC 4122 设置版本与变体位
func NewUUIDv4() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40 // version bits -> 0100
b[8] = (b[8] & 0x3f) | 0x80 // variant bits -> 10xx
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
func main() {
for range 3 {
id, err := NewUUIDv4()
if err != nil {
panic(err)
}
fmt.Println(id)
}
}How it works
Everything happens inside the functions NewUUIDv4 and main.
The loop for range 3 is the only repeated construct. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Runs on the standard library alone; nothing to install.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
The callable you reach for: func NewUUIDv4() (string, error)
Running the file executes main, which drives NewUUIDv4 in order.
Key statements worth quoting
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
if err != nil {
panic(err)
}
return "", err
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.UUID Version DetectorValidate the 8-4-4-4-12 UUID layout and read its version (v1 to v8) and variant nibbles per RFC 9562, with full field decomposition.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.
FAQ
- How does the code signal failure?
- As returned `error` values — 2 sites in the snippet check `err` before using other results.
- How do you run Crypto Rand UUID v4 With RFC 4122 Bits?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.