github.com/jcarley/cli@v0.0.0-20180201210820-966d90434c30/lib/crypto/encrypt.go (about) 1 package crypto 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 8 "github.com/catalyzeio/gcm/gcm" 9 ) 10 11 // EncryptFile takes in an open plaintext file and encrypts it to a temporary 12 // location based on the key and IV. It is up to the caller to ensure the 13 // encrypted file is deleted after it's used. The passed in key and iv should 14 // *NOT* be base64 encoded or hex encoded. 15 func (c *SCrypto) EncryptFile(plainFilePath string, key, iv []byte) (string, error) { 16 if len(key) != KeySize { 17 return "", fmt.Errorf("Invalid key length. Keys must be %d bytes", KeySize) 18 } 19 if len(iv) != IVSize { 20 return "", fmt.Errorf("Invalid IV length. IVs must be %d bytes", IVSize) 21 } 22 outputFile, err := ioutil.TempFile("", "encr") 23 if err != nil { 24 return "", err 25 } 26 outputFile.Close() 27 28 err = gcm.EncryptFile(plainFilePath, outputFile.Name(), key, iv, c.Unhex([]byte(gcm.AAD), AADSize)) 29 if err != nil { 30 return "", err 31 } 32 return outputFile.Name(), nil 33 } 34 35 // NewEncryptReader takes in a Reader and wraps it in a 36 // type that will encrypt the Reader as its read. 37 // The passed in key and iv should *NOT* be base64 encoded or hex encoded. 38 func (c *SCrypto) NewEncryptReader(reader io.Reader, key, iv []byte) (*gcm.EncryptReader, error) { 39 if len(key) != KeySize { 40 return nil, fmt.Errorf("Invalid key length. Keys must be %d bytes", KeySize) 41 } 42 if len(iv) != IVSize { 43 return nil, fmt.Errorf("Invalid IV length. IVs must be %d bytes", IVSize) 44 } 45 return gcm.NewEncryptReader(reader, key, iv, c.Unhex([]byte(gcm.AAD), AADSize)) 46 }