66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
package pass
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"filippo.io/age"
|
|
"filippo.io/age/armor"
|
|
)
|
|
|
|
func DecryptFile(password []byte, file string) ([]byte, error) {
|
|
identity, err := age.NewScryptIdentity(string(password))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("błąd przetwarzania hasła: %w", err)
|
|
}
|
|
fd, err := os.Open(file)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("błąd otwarcia pliku: %w", err)
|
|
}
|
|
defer fd.Close()
|
|
|
|
in := armor.NewReader(fd)
|
|
|
|
r, err := age.Decrypt(in, identity)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("błąd deszyfrowania #01: %w", err)
|
|
}
|
|
|
|
out := &bytes.Buffer{}
|
|
if _, err := io.Copy(out, r); err != nil {
|
|
return nil, fmt.Errorf("błąd deszyfrowania #02: %v", err)
|
|
}
|
|
return out.Bytes(), nil
|
|
}
|
|
|
|
func EncryptFile(password []byte, file string, data []byte) error {
|
|
recipient, err := age.NewScryptRecipient(string(password))
|
|
if err != nil {
|
|
return fmt.Errorf("błąd przetwarzania hasła: %w", err)
|
|
}
|
|
fd, err := os.OpenFile(file, os.O_WRONLY | os.O_CREATE | os.O_EXCL, 0o600)
|
|
if err != nil {
|
|
return fmt.Errorf("błąd tworzenia pliku: %w", err)
|
|
}
|
|
defer fd.Close()
|
|
|
|
out := armor.NewWriter(fd) // armor
|
|
defer out.Close()
|
|
|
|
w, err := age.Encrypt(out, recipient)
|
|
if err != nil {
|
|
return fmt.Errorf("błąd szyfrowania #01: %w", err)
|
|
}
|
|
_, err = w.Write(data)
|
|
if err != nil {
|
|
return fmt.Errorf("błąd szyfrowania #02: %w", err)
|
|
}
|
|
err = w.Close()
|
|
if err != nil {
|
|
return fmt.Errorf("błąd szyfrowania #03: %w", err)
|
|
}
|
|
return nil
|
|
}
|