1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Simplify id generation

Instead of using a SHA-256 of a random number, hex encode 32 bytes
of random data from crypto/rand (sourced from /dev/urandom).
This commit is contained in:
Jonathan Rudenberg 2013-03-26 16:46:27 -04:00
parent 2ee3db6cd2
commit 141b5fc7d7

View file

@ -1,13 +1,12 @@
package docker package docker
import ( import (
"bytes" "crypto/rand"
"crypto/sha256" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"math/rand"
"os" "os"
"path" "path"
"strings" "strings"
@ -162,20 +161,12 @@ func ValidateId(id string) error {
} }
func GenerateId() string { func GenerateId() string {
// FIXME: don't seed every time id := make([]byte, 32)
rand.Seed(time.Now().UTC().UnixNano()) _, err := io.ReadFull(rand.Reader, id)
randomBytes := bytes.NewBuffer([]byte(fmt.Sprintf("%x", rand.Int()))) if err != nil {
id, _ := ComputeId(randomBytes) // can't fail panic(err) // This shouldn't happen
return id
}
// ComputeId reads from `content` until EOF, then returns a SHA of what it read, as a string.
func ComputeId(content io.Reader) (string, error) {
h := sha256.New()
if _, err := io.Copy(h, content); err != nil {
return "", err
} }
return fmt.Sprintf("%x", h.Sum(nil)), nil return hex.EncodeToString(id)
} }
// Image includes convenience proxy functions to its graph // Image includes convenience proxy functions to its graph