Files

66 lines
1.5 KiB
Go
Raw Permalink Normal View History

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