github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/updater/util/rand.go (about) 1 // Copyright 2015 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package util 5 6 import ( 7 "crypto/rand" 8 "encoding/base32" 9 "strings" 10 ) 11 12 var randRead = rand.Read 13 14 // RandomID returns random ID (base32) string with prefix, using 256 bits as 15 // recommended by tptacek: https://gist.github.com/tqbf/be58d2d39690c3b366ad 16 func RandomID(prefix string) (string, error) { 17 buf, err := RandBytes(32) 18 if err != nil { 19 return "", err 20 } 21 str := base32.StdEncoding.EncodeToString(buf) 22 str = strings.ReplaceAll(str, "=", "") 23 str = prefix + str 24 return str, nil 25 } 26 27 // RandBytes returns random bytes of length 28 func RandBytes(length int) ([]byte, error) { 29 buf := make([]byte, length) 30 if _, err := randRead(buf); err != nil { 31 return nil, err 32 } 33 return buf, nil 34 }