github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/daemon/trustkey.go (about) 1 package daemon 2 3 import ( 4 "encoding/json" 5 "encoding/pem" 6 "fmt" 7 "os" 8 "path/filepath" 9 10 "github.com/docker/docker/pkg/ioutils" 11 "github.com/docker/docker/pkg/system" 12 "github.com/docker/libtrust" 13 ) 14 15 // LoadOrCreateTrustKey attempts to load the libtrust key at the given path, 16 // otherwise generates a new one 17 // TODO: this should use more of libtrust.LoadOrCreateTrustKey which may need 18 // a refactor or this function to be moved into libtrust 19 func loadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) { 20 err := system.MkdirAll(filepath.Dir(trustKeyPath), 0700, "") 21 if err != nil { 22 return nil, err 23 } 24 trustKey, err := libtrust.LoadKeyFile(trustKeyPath) 25 if err == libtrust.ErrKeyFileDoesNotExist { 26 trustKey, err = libtrust.GenerateECP256PrivateKey() 27 if err != nil { 28 return nil, fmt.Errorf("Error generating key: %s", err) 29 } 30 encodedKey, err := serializePrivateKey(trustKey, filepath.Ext(trustKeyPath)) 31 if err != nil { 32 return nil, fmt.Errorf("Error serializing key: %s", err) 33 } 34 if err := ioutils.AtomicWriteFile(trustKeyPath, encodedKey, os.FileMode(0600)); err != nil { 35 return nil, fmt.Errorf("Error saving key file: %s", err) 36 } 37 } else if err != nil { 38 return nil, fmt.Errorf("Error loading key file %s: %s", trustKeyPath, err) 39 } 40 return trustKey, nil 41 } 42 43 func serializePrivateKey(key libtrust.PrivateKey, ext string) (encoded []byte, err error) { 44 if ext == ".json" || ext == ".jwk" { 45 encoded, err = json.Marshal(key) 46 if err != nil { 47 return nil, fmt.Errorf("unable to encode private key JWK: %s", err) 48 } 49 } else { 50 pemBlock, err := key.PEMBlock() 51 if err != nil { 52 return nil, fmt.Errorf("unable to encode private key PEM: %s", err) 53 } 54 encoded = pem.EncodeToMemory(pemBlock) 55 } 56 return 57 }