9 // GenerateRandomBytes is used to generate random bytes of given size.
10 func GenerateRandomBytes(size int) ([]byte, error) {
11 buf := make([]byte, size)
12 if _, err := rand.Read(buf); err != nil {
13 return nil, fmt.Errorf("failed to read random bytes: %v", err)
20 // GenerateUUID is used to generate a random UUID
21 func GenerateUUID() (string, error) {
22 buf, err := GenerateRandomBytes(uuidLen)
26 return FormatUUID(buf)
29 func FormatUUID(buf []byte) (string, error) {
30 if buflen := len(buf); buflen != uuidLen {
31 return "", fmt.Errorf("wrong length byte slice (%d)", buflen)
34 return fmt.Sprintf("%x-%x-%x-%x-%x",
42 func ParseUUID(uuid string) ([]byte, error) {
43 if len(uuid) != 2 * uuidLen + 4 {
44 return nil, fmt.Errorf("uuid string is wrong length")
51 return nil, fmt.Errorf("uuid is improperly formatted")
54 hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36]
56 ret, err := hex.DecodeString(hexStr)
60 if len(ret) != uuidLen {
61 return nil, fmt.Errorf("decoded hex is the wrong length")