Scott Baker | 8461e15 | 2019-10-01 14:44:30 -0700 | [diff] [blame] | 1 | package uuid |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/hex" |
| 6 | "fmt" |
| 7 | ) |
| 8 | |
| 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) |
| 14 | } |
| 15 | return buf, nil |
| 16 | } |
| 17 | |
| 18 | const uuidLen = 16 |
| 19 | |
| 20 | // GenerateUUID is used to generate a random UUID |
| 21 | func GenerateUUID() (string, error) { |
| 22 | buf, err := GenerateRandomBytes(uuidLen) |
| 23 | if err != nil { |
| 24 | return "", err |
| 25 | } |
| 26 | return FormatUUID(buf) |
| 27 | } |
| 28 | |
| 29 | func FormatUUID(buf []byte) (string, error) { |
| 30 | if buflen := len(buf); buflen != uuidLen { |
| 31 | return "", fmt.Errorf("wrong length byte slice (%d)", buflen) |
| 32 | } |
| 33 | |
| 34 | return fmt.Sprintf("%x-%x-%x-%x-%x", |
| 35 | buf[0:4], |
| 36 | buf[4:6], |
| 37 | buf[6:8], |
| 38 | buf[8:10], |
| 39 | buf[10:16]), nil |
| 40 | } |
| 41 | |
| 42 | func ParseUUID(uuid string) ([]byte, error) { |
| 43 | if len(uuid) != 2 * uuidLen + 4 { |
| 44 | return nil, fmt.Errorf("uuid string is wrong length") |
| 45 | } |
| 46 | |
| 47 | if uuid[8] != '-' || |
| 48 | uuid[13] != '-' || |
| 49 | uuid[18] != '-' || |
| 50 | uuid[23] != '-' { |
| 51 | return nil, fmt.Errorf("uuid is improperly formatted") |
| 52 | } |
| 53 | |
| 54 | hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36] |
| 55 | |
| 56 | ret, err := hex.DecodeString(hexStr) |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | if len(ret) != uuidLen { |
| 61 | return nil, fmt.Errorf("decoded hex is the wrong length") |
| 62 | } |
| 63 | |
| 64 | return ret, nil |
| 65 | } |