2024-03-11 20:23:36 -04:00
|
|
|
package encrypt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"filippo.io/age"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Encrypt encrypts bytes into filename
|
2024-03-23 17:07:48 -04:00
|
|
|
func Encrypt(data []byte, filename string, recipients ...age.Recipient) error {
|
2024-03-11 20:23:36 -04:00
|
|
|
var (
|
|
|
|
w io.WriteCloser
|
|
|
|
out = &bytes.Buffer{}
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
2024-03-23 17:07:48 -04:00
|
|
|
if len(recipients) == 0 {
|
|
|
|
return errors.New("no recepients? who's trying to encrypt?")
|
2024-03-11 20:23:36 -04:00
|
|
|
}
|
|
|
|
|
2024-03-23 17:07:48 -04:00
|
|
|
if w, err = age.Encrypt(out, recipients...); err != nil {
|
2024-03-11 20:23:36 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
io.WriteString(w, string(data))
|
|
|
|
if err = w.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
os.Truncate(filename, 0) // in case it exists already
|
|
|
|
if err = os.WriteFile(filename, out.Bytes(), fs.FileMode(0600)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|