github.com/trustbloc/kms-go@v1.1.2/secretlock/local/local_secret_masterkey_reader.go (about) 1 /* 2 Copyright SecureKey Technologies Inc. All Rights Reserved. 3 SPDX-License-Identifier: Apache-2.0 4 */ 5 6 package local 7 8 import ( 9 "bytes" 10 "errors" 11 "fmt" 12 "io" 13 "os" 14 "path/filepath" 15 "strings" 16 ) 17 18 // MasterKeyFromPath creates a new instance of a local secret lock Reader to read a master key stored in `path`. 19 func MasterKeyFromPath(path string) (io.Reader, error) { 20 masterKeyFile, err := os.OpenFile(filepath.Clean(path), os.O_RDONLY, 0o600) 21 if err != nil { 22 return nil, err 23 } 24 25 defer func() { 26 err = masterKeyFile.Close() 27 if err != nil { 28 logger.Printf("failed to close file: %v", err) 29 } 30 }() 31 32 mkData := make([]byte, masterKeyLen) 33 34 n, err := io.ReadFull(masterKeyFile, mkData) 35 if err != nil { 36 if !errors.Is(err, io.ErrUnexpectedEOF) { 37 return nil, err 38 } 39 } 40 41 mkData = mkData[0:n] 42 43 return bytes.NewReader(mkData), nil 44 } 45 46 // MasterKeyFromEnv creates a new instance of a local secret lock Reader 47 // to read a master key found in a env variable with key: `envPrefix` + `keyURI`. 48 func MasterKeyFromEnv(envPrefix, keyURI string) (io.Reader, error) { 49 mk := os.Getenv(envPrefix + strings.ReplaceAll(keyURI, "/", "_")) 50 if mk == "" { 51 return nil, fmt.Errorf("masterKey not set") 52 } 53 54 return bytes.NewReader([]byte(mk)), nil 55 }