use buffered reader to write to encryption mechanism

This commit is contained in:
Frederik Ring 2021-08-23 15:33:49 +02:00
parent ec87bd27e7
commit b1c4bee85d

View File

@ -4,12 +4,10 @@
package main package main
import ( import (
"bytes"
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -264,27 +262,30 @@ func (s *script) encryptBackup() error {
return nil return nil
} }
output := bytes.NewBuffer(nil) gpgFile := fmt.Sprintf("%s.gpg", s.file)
_, name := path.Split(s.file) outFile, err := os.Create(gpgFile)
defer outFile.Close()
if err != nil {
return fmt.Errorf("encryptBackup: error opening out file: %w", err)
}
pt, err := openpgp.SymmetricallyEncrypt(output, []byte(s.passphrase), &openpgp.FileHints{ _, name := path.Split(s.file)
dst, err := openpgp.SymmetricallyEncrypt(outFile, []byte(s.passphrase), &openpgp.FileHints{
IsBinary: true, IsBinary: true,
FileName: name, FileName: name,
}, nil) }, nil)
defer dst.Close()
if err != nil { if err != nil {
return fmt.Errorf("encryptBackup: error encrypting backup file: %w", err) return fmt.Errorf("encryptBackup: error encrypting backup file: %w", err)
} }
b, err := ioutil.ReadFile(s.file) src, err := os.Open(s.file)
if err != nil { if err != nil {
return fmt.Errorf("encryptBackup: error opening unencrypted backup file: %w", err) return fmt.Errorf("encryptBackup: error opening backup file %s: %w", s.file, err)
} }
pt.Write(b)
pt.Close()
gpgFile := fmt.Sprintf("%s.gpg", s.file) if _, err := io.Copy(dst, src); err != nil {
if err := ioutil.WriteFile(gpgFile, output.Bytes(), os.ModeAppend); err != nil { return fmt.Errorf("encryptBackup: error writing ciphertext to file: %w", err)
return fmt.Errorf("encryptBackup: error writing encrypted version of backup: %w", err)
} }
if err := os.Remove(s.file); err != nil { if err := os.Remove(s.file); err != nil {