github.com/decred/politeia@v1.4.0/util/encrypt.go (about) 1 // Copyright (c) 2020-2021 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package util 6 7 import ( 8 "fmt" 9 "os" 10 11 "github.com/decred/slog" 12 "github.com/marcopeereboom/sbox" 13 ) 14 15 // Zero zeros out a byte slice. 16 func Zero(in []byte) { 17 if in == nil { 18 return 19 } 20 inlen := len(in) 21 for i := 0; i < inlen; i++ { 22 in[i] ^= in[i] 23 } 24 } 25 26 // LoadEncryptionKey loads the encryption key at the provided file path. If a 27 // key does not exists at the file path then a new secretbox key is created 28 // and saved to the file path before returning the key. 29 func LoadEncryptionKey(log slog.Logger, keyFile string) (*[32]byte, error) { 30 if keyFile == "" { 31 return nil, fmt.Errorf("no key file provided") 32 } 33 34 // Setup encryption key file 35 if !FileExists(keyFile) { 36 // Encryption key file does not exist. Create one. 37 log.Infof("Generating encryption key") 38 key, err := sbox.NewKey() 39 if err != nil { 40 return nil, err 41 } 42 err = os.WriteFile(keyFile, key[:], 0400) 43 if err != nil { 44 return nil, err 45 } 46 Zero(key[:]) 47 log.Infof("Encryption key created: %v", keyFile) 48 } 49 50 // Load encryption key 51 f, err := os.Open(keyFile) 52 if err != nil { 53 return nil, err 54 } 55 defer f.Close() 56 57 var key [32]byte 58 n, err := f.Read(key[:]) 59 if n != len(key) { 60 return nil, fmt.Errorf("invalid encryption key length") 61 } 62 if err != nil { 63 return nil, err 64 } 65 66 log.Infof("Encryption key: %v", keyFile) 67 68 return &key, nil 69 }