aboutsummaryrefslogtreecommitdiff
path: root/internal
diff options
context:
space:
mode:
Diffstat (limited to 'internal')
-rw-r--r--internal/config/config.go194
-rw-r--r--internal/config/config_file.go47
-rw-r--r--internal/config/config_ops.go163
-rw-r--r--internal/crud/cli_edit.go24
-rw-r--r--internal/crud/cli_new_pass.go161
-rw-r--r--internal/crud/cli_new_ssh.go (renamed from internal/crud/cli_new.go)160
-rw-r--r--internal/crypt/headers.go33
-rw-r--r--internal/crypt/raw_decrypt.go (renamed from internal/crypt/rawDecrypt.go)73
-rw-r--r--internal/crypt/raw_encrypt.go (renamed from internal/crypt/rawEncrypt.go)0
-rw-r--r--internal/crypt/ssh_key.go (renamed from internal/crypt/sshKey.go)32
-rw-r--r--internal/crypt/ssh_key_io.go39
-rw-r--r--internal/utils/utils.go24
12 files changed, 453 insertions, 497 deletions
diff --git a/internal/config/config.go b/internal/config/config.go
index baf50c6..5e5fcf9 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -6,7 +6,6 @@ import (
"fmt"
"os"
"path/filepath"
- "sort"
"strconv"
"strings"
)
@@ -167,196 +166,3 @@ func init() {
configKeyField[key] = field
}
}
-
-func Set(key, value string) error {
- key = strings.ToUpper(key)
- field, ok := configKeyField[key]
- if !ok {
- return fmt.Errorf("unknown config key: %s", key)
- }
-
- switch field {
- case "PubkeyServices":
- Conf.PubkeyServices = ParsePubkeyServices(value)
- lines, err := readConfigLines()
- if err != nil {
- return err
- }
- return writeConfigLines(replaceOrAppend(lines, key, value))
- case "SSHInitialized":
- b, err := strconv.ParseBool(value)
- if err != nil {
- return fmt.Errorf("SSH_INIT must be true or false: %w", err)
- }
- return Update(field, b)
- default:
- return Update(field, value)
- }
-}
-
-func Get(key string) (string, error) {
- key = strings.ToUpper(key)
- field, ok := configKeyField[key]
- if !ok {
- return "", fmt.Errorf("unknown config key: %s", key)
- }
-
- switch field {
- case "EditorString":
- return Conf.EditorString, nil
- case "DataDir":
- return Conf.DataDir, nil
- case "DefaultSSHPrivPath":
- return Conf.DefaultSSHPrivPath, nil
- case "DefaultSSHPubPath":
- return Conf.DefaultSSHPubPath, nil
- case "SSHInitialized":
- return strconv.FormatBool(Conf.SSHInitialized), nil
- case "PubkeyServices":
- return SerializePubkeyServices(Conf.PubkeyServices), nil
- default:
- return "", fmt.Errorf("unknown config key: %s", key)
- }
-}
-
-func Remove(key string) error {
- key = strings.ToUpper(key)
- _, ok := configKeyField[key]
- if !ok {
- return fmt.Errorf("unknown config key: %s", key)
- }
-
- lines, err := readConfigLines()
- if err != nil {
- return err
- }
-
- filtered := make([]string, 0, len(lines))
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed == "" || strings.HasPrefix(trimmed, "#") {
- filtered = append(filtered, line)
- continue
- }
- k, _, ok := strings.Cut(trimmed, "=")
- if ok && strings.TrimSpace(k) == key {
- continue
- }
- filtered = append(filtered, line)
- }
-
- if err := writeConfigLines(filtered); err != nil {
- return err
- }
- return Init()
-}
-
-func readConfigLines() ([]string, error) {
- data, err := os.ReadFile(Conf.ConfPath)
- if err != nil {
- if errors.Is(err, os.ErrNotExist) {
- return nil, nil
- }
- return nil, fmt.Errorf("reading config: %w", err)
- }
- return strings.Split(string(data), "\n"), nil
-}
-
-func replaceOrAppend(lines []string, key, value string) []string {
- newLine := fmt.Sprintf("%s=%s", key, value)
- found := false
-
- for i, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed == "" || strings.HasPrefix(trimmed, "#") {
- continue
- }
- k, _, ok := strings.Cut(trimmed, "=")
- if ok && strings.TrimSpace(k) == key {
- lines[i] = newLine
- found = true
- break
- }
- }
-
- if !found {
- lines = append(lines, newLine)
- }
- return lines
-}
-
-func writeConfigLines(lines []string) error {
- content := strings.Join(lines, "\n")
- return os.WriteFile(Conf.ConfPath, []byte(content), 0600)
-}
-
-func List() []string {
- keys := make([]string, 0, len(configKeyField))
- for k := range configKeyField {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- result := make([]string, 0, len(keys))
- for _, key := range keys {
- val, err := Get(key)
- if err != nil {
- continue
- }
- result = append(result, fmt.Sprintf("%s=%s", key, val))
- }
- return result
-}
-
-func Update(key string, val any) error {
- configKey, ok := configFieldKey[key]
- if !ok {
- return fmt.Errorf("unknown config field: %s", key)
- }
-
- var valStr string
- switch v := val.(type) {
- case bool:
- valStr = strconv.FormatBool(v)
- case string:
- valStr = v
- default:
- valStr = fmt.Sprintf("%v", v)
- }
-
- data, err := os.ReadFile(Conf.ConfPath)
- if err != nil {
- return fmt.Errorf("reading config: %w", err)
- }
-
- lines := strings.Split(string(data), "\n")
- newLine := fmt.Sprintf("%s=%s", configKey, valStr)
- found := false
-
- for i, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed == "" || strings.HasPrefix(trimmed, "#") {
- continue
- }
- k, _, ok := strings.Cut(trimmed, "=")
- if !ok {
- continue
- }
- if strings.TrimSpace(k) == configKey {
- lines[i] = newLine
- found = true
- break
- }
- }
-
- if !found {
- lines = append(lines, newLine)
- }
-
- err = os.WriteFile(Conf.ConfPath, []byte(strings.Join(lines, "\n")), 0600)
- if err != nil {
- return err
- }
-
- return Init()
-}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
new file mode 100644
index 0000000..31045f8
--- /dev/null
+++ b/internal/config/config_file.go
@@ -0,0 +1,47 @@
+package config
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+)
+
+func readConfigLines() ([]string, error) {
+ data, err := os.ReadFile(Conf.ConfPath)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("reading config: %w", err)
+ }
+ return strings.Split(string(data), "\n"), nil
+}
+
+func replaceOrAppend(lines []string, key, value string) []string {
+ newLine := fmt.Sprintf("%s=%s", key, value)
+ found := false
+
+ for i, line := range lines {
+ trimmed := strings.TrimSpace(line)
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ continue
+ }
+ k, _, ok := strings.Cut(trimmed, "=")
+ if ok && strings.TrimSpace(k) == key {
+ lines[i] = newLine
+ found = true
+ break
+ }
+ }
+
+ if !found {
+ lines = append(lines, newLine)
+ }
+ return lines
+}
+
+func writeConfigLines(lines []string) error {
+ content := strings.Join(lines, "\n")
+ return os.WriteFile(Conf.ConfPath, []byte(content), 0600)
+}
diff --git a/internal/config/config_ops.go b/internal/config/config_ops.go
new file mode 100644
index 0000000..06966f7
--- /dev/null
+++ b/internal/config/config_ops.go
@@ -0,0 +1,163 @@
+package config
+
+import (
+ "fmt"
+ "os"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+func Set(key, value string) error {
+ key = strings.ToUpper(key)
+ field, ok := configKeyField[key]
+ if !ok {
+ return fmt.Errorf("unknown config key: %s", key)
+ }
+
+ switch field {
+ case "PubkeyServices":
+ Conf.PubkeyServices = ParsePubkeyServices(value)
+ lines, err := readConfigLines()
+ if err != nil {
+ return err
+ }
+ return writeConfigLines(replaceOrAppend(lines, key, value))
+ case "SSHInitialized":
+ b, err := strconv.ParseBool(value)
+ if err != nil {
+ return fmt.Errorf("SSH_INIT must be true or false: %w", err)
+ }
+ return Update(field, b)
+ default:
+ return Update(field, value)
+ }
+}
+
+func Get(key string) (string, error) {
+ key = strings.ToUpper(key)
+ field, ok := configKeyField[key]
+ if !ok {
+ return "", fmt.Errorf("unknown config key: %s", key)
+ }
+
+ switch field {
+ case "EditorString":
+ return Conf.EditorString, nil
+ case "DataDir":
+ return Conf.DataDir, nil
+ case "DefaultSSHPrivPath":
+ return Conf.DefaultSSHPrivPath, nil
+ case "DefaultSSHPubPath":
+ return Conf.DefaultSSHPubPath, nil
+ case "SSHInitialized":
+ return strconv.FormatBool(Conf.SSHInitialized), nil
+ case "PubkeyServices":
+ return SerializePubkeyServices(Conf.PubkeyServices), nil
+ default:
+ return "", fmt.Errorf("unknown config key: %s", key)
+ }
+}
+
+func Remove(key string) error {
+ key = strings.ToUpper(key)
+ _, ok := configKeyField[key]
+ if !ok {
+ return fmt.Errorf("unknown config key: %s", key)
+ }
+
+ lines, err := readConfigLines()
+ if err != nil {
+ return err
+ }
+
+ filtered := make([]string, 0, len(lines))
+ for _, line := range lines {
+ trimmed := strings.TrimSpace(line)
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ filtered = append(filtered, line)
+ continue
+ }
+ k, _, ok := strings.Cut(trimmed, "=")
+ if ok && strings.TrimSpace(k) == key {
+ continue
+ }
+ filtered = append(filtered, line)
+ }
+
+ if err := writeConfigLines(filtered); err != nil {
+ return err
+ }
+ return Init()
+}
+
+func List() []string {
+ keys := make([]string, 0, len(configKeyField))
+ for k := range configKeyField {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+
+ result := make([]string, 0, len(keys))
+ for _, key := range keys {
+ val, err := Get(key)
+ if err != nil {
+ continue
+ }
+ result = append(result, fmt.Sprintf("%s=%s", key, val))
+ }
+ return result
+}
+
+func Update(key string, val any) error {
+ configKey, ok := configFieldKey[key]
+ if !ok {
+ return fmt.Errorf("unknown config field: %s", key)
+ }
+
+ var valStr string
+ switch v := val.(type) {
+ case bool:
+ valStr = strconv.FormatBool(v)
+ case string:
+ valStr = v
+ default:
+ valStr = fmt.Sprintf("%v", v)
+ }
+
+ data, err := os.ReadFile(Conf.ConfPath)
+ if err != nil {
+ return fmt.Errorf("reading config: %w", err)
+ }
+
+ lines := strings.Split(string(data), "\n")
+ newLine := fmt.Sprintf("%s=%s", configKey, valStr)
+ found := false
+
+ for i, line := range lines {
+ trimmed := strings.TrimSpace(line)
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ continue
+ }
+ k, _, ok := strings.Cut(trimmed, "=")
+ if !ok {
+ continue
+ }
+ if strings.TrimSpace(k) == configKey {
+ lines[i] = newLine
+ found = true
+ break
+ }
+ }
+
+ if !found {
+ lines = append(lines, newLine)
+ }
+
+ err = os.WriteFile(Conf.ConfPath, []byte(strings.Join(lines, "\n")), 0600)
+ if err != nil {
+ return err
+ }
+
+ return Init()
+}
diff --git a/internal/crud/cli_edit.go b/internal/crud/cli_edit.go
index 50bb8d2..0683439 100644
--- a/internal/crud/cli_edit.go
+++ b/internal/crud/cli_edit.go
@@ -3,7 +3,6 @@ package crud
import (
"fmt"
"os"
- "strconv"
"gitlab.com/whiteboardguy/eno/internal/crypt"
"gitlab.com/whiteboardguy/eno/internal/editor"
@@ -90,28 +89,7 @@ func EditNoteSSH(notePath, privKeyPath, editorString string) error {
return err
}
- idx := -1
- for i, b := range ciphertext {
- if b == ':' {
- idx = i
- break
- }
- }
- if idx == -1 {
- return fmt.Errorf("invalid file format: no header length prefix found")
- }
-
- headerLen, err := strconv.Atoi(string(ciphertext[:idx]))
- if err != nil {
- return fmt.Errorf("failed to parse header length: %v", err)
- }
-
- if headerLen < 0 || idx+1+headerLen > len(ciphertext) {
- return fmt.Errorf("invalid header length %d", headerLen)
- }
-
- headerBytes := ciphertext[idx+1 : idx+1+headerLen]
- headers, err := crypt.GetFileHeaders(headerBytes)
+ headers, _, err := crypt.ParseFileHeaders(ciphertext)
if err != nil {
return fmt.Errorf("failed to read file headers: %v", err)
}
diff --git a/internal/crud/cli_new_pass.go b/internal/crud/cli_new_pass.go
new file mode 100644
index 0000000..c18ddc6
--- /dev/null
+++ b/internal/crud/cli_new_pass.go
@@ -0,0 +1,161 @@
+package crud
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+
+ "gitlab.com/whiteboardguy/eno/internal/crypt"
+ "gitlab.com/whiteboardguy/eno/internal/editor"
+ "gitlab.com/whiteboardguy/eno/internal/utils"
+)
+
+func NewNotePass(output string) error {
+ fmt.Printf("Enter the passphrase: ")
+ password, err := utils.TakeSecureUserInput()
+ if err != nil {
+ return fmt.Errorf("failed to read passphrase: %v", err)
+ }
+ crypt.TryMlock(password)
+ defer clear(password)
+
+ fmt.Printf("Confirm the passphrase: ")
+ passwordConfirm, err := utils.TakeSecureUserInput()
+ if err != nil {
+ return fmt.Errorf("failed to read passphrase: %v", err)
+ }
+ crypt.TryMlock(passwordConfirm)
+ defer clear(passwordConfirm)
+
+ if !bytes.Equal(password, passwordConfirm) {
+ return fmt.Errorf("passphrases do not match")
+ }
+
+ encrypted, err := crypt.EncryptBytesPass(
+ append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...),
+ password,
+ )
+ if err != nil {
+ return err
+ }
+
+ fmt.Println(output)
+ file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+
+ _, err = file.Write(encrypted)
+ if err != nil {
+ return err
+ }
+
+ file.Sync()
+
+ // utils.ClearTerm()
+ fmt.Println("New note saved at:", file.Name())
+
+ return nil
+}
+
+func NewNotePassEdit(output, editorString string) error {
+ fmt.Printf("Enter the passphrase: ")
+ password, err := utils.TakeSecureUserInput()
+ if err != nil {
+ return fmt.Errorf("failed to read passphrase: %v", err)
+ }
+ crypt.TryMlock(password)
+ defer clear(password)
+
+ fmt.Printf("Confirm the passphrase: ")
+ passwordConfirm, err := utils.TakeSecureUserInput()
+ if err != nil {
+ return fmt.Errorf("failed to read passphrase: %v", err)
+ }
+ crypt.TryMlock(passwordConfirm)
+ defer clear(passwordConfirm)
+
+ if !bytes.Equal(password, passwordConfirm) {
+ return fmt.Errorf("passphrases do not match")
+ }
+
+ noteInfo, err := os.Stat(output)
+ preExisting := err == nil
+
+ initialContent := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...)
+ encrypted, err := crypt.EncryptBytesPass(initialContent, password)
+ if err != nil {
+ return err
+ }
+
+ file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
+ if err != nil {
+ return err
+ }
+
+ _, err = file.Write(encrypted)
+ if err != nil {
+ return err
+ }
+
+ file.Sync()
+ file.Close()
+
+ ciphertext, err := os.ReadFile(output)
+ if err != nil {
+ return err
+ }
+
+ tmpFile, err := utils.SecureTempFile()
+ if err != nil {
+ return err
+ }
+
+ plaintext, err := crypt.DecryptBytesPass(ciphertext, password)
+ if err != nil {
+ return err
+ }
+ crypt.TryMlock(plaintext)
+ defer clear(plaintext)
+
+ defer deferredCleanTmpFile(tmpFile, len(plaintext))
+ defer os.Remove(tmpFile.Name())
+
+ _, err = tmpFile.Write(plaintext)
+ if err != nil {
+ return err
+ }
+
+ err = editor.OpenWithEditor(tmpFile.Name(), editorString)
+ if err != nil {
+ return err
+ }
+
+ newContent, err := os.ReadFile(tmpFile.Name())
+ if err != nil {
+ return err
+ }
+ crypt.TryMlock(newContent)
+ defer clear(newContent)
+
+ if err := os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600); err != nil {
+ fmt.Fprintf(os.Stderr, "warning: failed to wipe temp file %s: %v\n", tmpFile.Name(), err)
+ }
+
+ encrypted, err = crypt.EncryptBytesPass(newContent, password)
+ if err != nil {
+ return err
+ }
+
+ perm := os.FileMode(0600)
+ if preExisting {
+ perm = noteInfo.Mode().Perm()
+ }
+
+ err = os.WriteFile(output, encrypted, perm)
+
+ fmt.Println("New note saved at:", output)
+
+ return err
+}
diff --git a/internal/crud/cli_new.go b/internal/crud/cli_new_ssh.go
index 8e56490..5479490 100644
--- a/internal/crud/cli_new.go
+++ b/internal/crud/cli_new_ssh.go
@@ -11,156 +11,6 @@ import (
"gitlab.com/whiteboardguy/eno/internal/utils"
)
-func NewNotePass(output string) error {
- fmt.Printf("Enter the passphrase: ")
- password, err := utils.TakeSecureUserInput()
- if err != nil {
- return fmt.Errorf("failed to read passphrase: %v", err)
- }
- crypt.TryMlock(password)
- defer clear(password)
-
- fmt.Printf("Confirm the passphrase: ")
- passwordConfirm, err := utils.TakeSecureUserInput()
- if err != nil {
- return fmt.Errorf("failed to read passphrase: %v", err)
- }
- crypt.TryMlock(passwordConfirm)
- defer clear(passwordConfirm)
-
- if !bytes.Equal(password, passwordConfirm) {
- return fmt.Errorf("passphrases do not match")
- }
-
- encrypted, err := crypt.EncryptBytesPass(
- append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...),
- password,
- )
- if err != nil {
- return err
- }
-
- fmt.Println(output)
- file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
- if err != nil {
- return err
- }
- defer file.Close()
-
- _, err = file.Write(encrypted)
- if err != nil {
- return err
- }
-
- file.Sync()
-
- // utils.ClearTerm()
- fmt.Println("New note saved at:", file.Name())
-
- return nil
-}
-
-func NewNotePassEdit(output, editorString string) error {
- fmt.Printf("Enter the passphrase: ")
- password, err := utils.TakeSecureUserInput()
- if err != nil {
- return fmt.Errorf("failed to read passphrase: %v", err)
- }
- crypt.TryMlock(password)
- defer clear(password)
-
- fmt.Printf("Confirm the passphrase: ")
- passwordConfirm, err := utils.TakeSecureUserInput()
- if err != nil {
- return fmt.Errorf("failed to read passphrase: %v", err)
- }
- crypt.TryMlock(passwordConfirm)
- defer clear(passwordConfirm)
-
- if !bytes.Equal(password, passwordConfirm) {
- return fmt.Errorf("passphrases do not match")
- }
-
- noteInfo, err := os.Stat(output)
- preExisting := err == nil
-
- initialContent := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...)
- encrypted, err := crypt.EncryptBytesPass(initialContent, password)
- if err != nil {
- return err
- }
-
- file, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
- if err != nil {
- return err
- }
-
- _, err = file.Write(encrypted)
- if err != nil {
- return err
- }
-
- file.Sync()
- file.Close()
-
- ciphertext, err := os.ReadFile(output)
- if err != nil {
- return err
- }
-
- tmpFile, err := utils.SecureTempFile()
- if err != nil {
- return err
- }
-
- plaintext, err := crypt.DecryptBytesPass(ciphertext, password)
- if err != nil {
- return err
- }
- crypt.TryMlock(plaintext)
- defer clear(plaintext)
-
- defer deferredCleanTmpFile(tmpFile, len(plaintext))
- defer os.Remove(tmpFile.Name())
-
- _, err = tmpFile.Write(plaintext)
- if err != nil {
- return err
- }
-
- err = editor.OpenWithEditor(tmpFile.Name(), editorString)
- if err != nil {
- return err
- }
-
- newContent, err := os.ReadFile(tmpFile.Name())
- if err != nil {
- return err
- }
- crypt.TryMlock(newContent)
- defer clear(newContent)
-
- if err := os.WriteFile(tmpFile.Name(), make([]byte, len(newContent)), 0600); err != nil {
- fmt.Fprintf(os.Stderr, "warning: failed to wipe temp file %s: %v\n", tmpFile.Name(), err)
- }
-
- encrypted, err = crypt.EncryptBytesPass(newContent, password)
- if err != nil {
- return err
- }
-
- perm := os.FileMode(0600)
- if preExisting {
- perm = noteInfo.Mode().Perm()
- }
-
- err = os.WriteFile(output, encrypted, perm)
-
- fmt.Println("New note saved at:", output)
-
- return err
-}
-
func PromptRecipientKeys(defaultPubKeyBytes []byte) ([][]byte, bool, error) {
useDefault, err := utils.AskUserYesNo("Do you want to encrypt the note with your own default Public Key?", true)
if err != nil {
@@ -214,11 +64,11 @@ func PromptRecipientKeys(defaultPubKeyBytes []byte) ([][]byte, bool, error) {
if err != nil {
return nil, false, fmt.Errorf("failed to get public key from %s: %v", part, err)
}
- selectedKeys, err := selectServiceKeys(part, body)
- if err != nil {
- fmt.Printf("Warning: %s: %v\n", service, err)
- continue
- }
+ selectedKeys, err := selectServiceKeys(part, body)
+ if err != nil {
+ fmt.Printf("Warning: %s: %v\n", service, err)
+ continue
+ }
for _, k := range selectedKeys {
pubKeys = append(pubKeys, bytes.TrimSpace(k))
}
diff --git a/internal/crypt/headers.go b/internal/crypt/headers.go
index 8f9dac2..c47d39c 100644
--- a/internal/crypt/headers.go
+++ b/internal/crypt/headers.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/gob"
"fmt"
+ "strconv"
)
type DataType string
@@ -55,3 +56,35 @@ func FileHeadersBytes(headers FileHeaders) ([]byte, error) {
return buf.Bytes(), nil
}
+
+func ParseFileHeaders(data []byte) (FileHeaders, []byte, error) {
+ idx := -1
+ for i, b := range data {
+ if b == ':' {
+ idx = i
+ break
+ }
+ }
+ if idx == -1 {
+ return FileHeaders{}, nil, fmt.Errorf("invalid file format: no header length prefix found")
+ }
+
+ headerLen, err := strconv.Atoi(string(data[:idx]))
+ if err != nil {
+ return FileHeaders{}, nil, fmt.Errorf("failed to parse header length: %w", err)
+ }
+
+ if headerLen <= 0 || idx+1+headerLen > len(data) {
+ return FileHeaders{}, nil, fmt.Errorf("invalid header length %d", headerLen)
+ }
+
+ headerBytes := data[idx+1 : idx+1+headerLen]
+ headers, err := GetFileHeaders(headerBytes)
+ if err != nil {
+ return FileHeaders{}, nil, fmt.Errorf("failed to decode headers: %w", err)
+ }
+
+ ciphertext := data[idx+1+headerLen:]
+
+ return headers, ciphertext, nil
+}
diff --git a/internal/crypt/rawDecrypt.go b/internal/crypt/raw_decrypt.go
index ede063c..050a4ec 100644
--- a/internal/crypt/rawDecrypt.go
+++ b/internal/crypt/raw_decrypt.go
@@ -2,35 +2,13 @@ package crypt
import (
"fmt"
- "strconv"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/chacha20poly1305"
)
func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) {
- idx := -1
- for i, b := range inputBytes {
- if b == ':' {
- idx = i
- break
- }
- }
- if idx == -1 {
- return nil, fmt.Errorf("decrypt: invalid file format: no header length prefix found")
- }
-
- headerLen, err := strconv.Atoi(string(inputBytes[:idx]))
- if err != nil {
- return nil, fmt.Errorf("decrypt: failed to parse header length: %w", err)
- }
-
- if headerLen <= 0 || idx+1+headerLen > len(inputBytes) {
- return nil, fmt.Errorf("decrypt: invalid header length %d", headerLen)
- }
-
- headerBytes := inputBytes[idx+1 : idx+1+headerLen]
- headers, err := GetFileHeaders(headerBytes)
+ headers, ciphertext, err := ParseFileHeaders(inputBytes)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
}
@@ -47,7 +25,6 @@ func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) {
return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err)
}
- ciphertext := inputBytes[idx+1+headerLen:]
plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
@@ -57,28 +34,7 @@ func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) {
}
func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) {
- idx := -1
- for i, b := range inputBytes {
- if b == ':' {
- idx = i
- break
- }
- }
- if idx == -1 {
- return nil, fmt.Errorf("decrypt: invalid file format: no header length prefix found")
- }
-
- headerLen, err := strconv.Atoi(string(inputBytes[:idx]))
- if err != nil {
- return nil, fmt.Errorf("decrypt: failed to parse header length: %w", err)
- }
-
- if headerLen <= 0 || idx+1+headerLen > len(inputBytes) {
- return nil, fmt.Errorf("decrypt: invalid header length %d", headerLen)
- }
-
- headerBytes := inputBytes[idx+1 : idx+1+headerLen]
- headers, err := GetFileHeaders(headerBytes)
+ headers, ciphertext, err := ParseFileHeaders(inputBytes)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
}
@@ -111,7 +67,6 @@ func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) {
return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err)
}
- ciphertext := inputBytes[idx+1+headerLen:]
plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
@@ -121,28 +76,7 @@ func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) {
}
func DecryptBytesSSHWithKey(inputBytes []byte, noteKey []byte) ([]byte, error) {
- idx := -1
- for i, b := range inputBytes {
- if b == ':' {
- idx = i
- break
- }
- }
- if idx == -1 {
- return nil, fmt.Errorf("decrypt: invalid file format: no header length prefix found")
- }
-
- headerLen, err := strconv.Atoi(string(inputBytes[:idx]))
- if err != nil {
- return nil, fmt.Errorf("decrypt: failed to parse header length: %w", err)
- }
-
- if headerLen <= 0 || idx+1+headerLen > len(inputBytes) {
- return nil, fmt.Errorf("decrypt: invalid header length %d", headerLen)
- }
-
- headerBytes := inputBytes[idx+1 : idx+1+headerLen]
- headers, err := GetFileHeaders(headerBytes)
+ headers, ciphertext, err := ParseFileHeaders(inputBytes)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
}
@@ -156,7 +90,6 @@ func DecryptBytesSSHWithKey(inputBytes []byte, noteKey []byte) ([]byte, error) {
return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err)
}
- ciphertext := inputBytes[idx+1+headerLen:]
plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
diff --git a/internal/crypt/rawEncrypt.go b/internal/crypt/raw_encrypt.go
index 03f742f..03f742f 100644
--- a/internal/crypt/rawEncrypt.go
+++ b/internal/crypt/raw_encrypt.go
diff --git a/internal/crypt/sshKey.go b/internal/crypt/ssh_key.go
index 2062ebd..a043f75 100644
--- a/internal/crypt/sshKey.go
+++ b/internal/crypt/ssh_key.go
@@ -10,11 +10,8 @@ import (
"crypto/sha512"
"fmt"
"os"
- "os/signal"
- "syscall"
"filippo.io/edwards25519/field"
- "github.com/charmbracelet/x/term"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/ssh"
@@ -54,35 +51,6 @@ func ed25519SeedToX25519Priv(seed []byte) []byte {
return scalar
}
-func promptSSHKeyPassphrase(privKeyPath string) []byte {
- fd := os.Stdin.Fd()
- oldState, err := term.GetState(fd)
- if err != nil {
- fmt.Fprintf(os.Stderr, "eno: failed to get terminal state: %v\n", err)
- return nil
- }
-
- sigCh := make(chan os.Signal, 1)
- signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
- defer signal.Stop(sigCh)
-
- go func() {
- <-sigCh
- term.Restore(fd, oldState)
- os.Exit(130)
- }()
-
- fmt.Fprintf(os.Stderr, "Enter passphrase for SSH key %s: ", privKeyPath)
- passphrase, err := term.ReadPassword(fd)
- fmt.Fprintln(os.Stderr)
- if err != nil {
- fmt.Fprintf(os.Stderr, "eno: failed to read passphrase: %v\n", err)
- return nil
- }
-
- return passphrase
-}
-
// Wraps noteKey once per PubKey. Returns WrappedKey for each.
func WrapNoteKeyForRecipients(noteKey []byte, pubKeys [][]byte) ([]WrappedKey, error) {
recipients := make([]WrappedKey, 0, len(pubKeys))
diff --git a/internal/crypt/ssh_key_io.go b/internal/crypt/ssh_key_io.go
new file mode 100644
index 0000000..59ea448
--- /dev/null
+++ b/internal/crypt/ssh_key_io.go
@@ -0,0 +1,39 @@
+package crypt
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/charmbracelet/x/term"
+)
+
+func promptSSHKeyPassphrase(privKeyPath string) []byte {
+ fd := os.Stdin.Fd()
+ oldState, err := term.GetState(fd)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "eno: failed to get terminal state: %v\n", err)
+ return nil
+ }
+
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
+ defer signal.Stop(sigCh)
+
+ go func() {
+ <-sigCh
+ term.Restore(fd, oldState)
+ os.Exit(130)
+ }()
+
+ fmt.Fprintf(os.Stderr, "Enter passphrase for SSH key %s: ", privKeyPath)
+ passphrase, err := term.ReadPassword(fd)
+ fmt.Fprintln(os.Stderr)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "eno: failed to read passphrase: %v\n", err)
+ return nil
+ }
+
+ return passphrase
+}
diff --git a/internal/utils/utils.go b/internal/utils/utils.go
index cea00a3..329128a 100644
--- a/internal/utils/utils.go
+++ b/internal/utils/utils.go
@@ -5,7 +5,6 @@ import (
"fmt"
"os"
"os/signal"
- "strconv"
"syscall"
"github.com/charmbracelet/x/term"
@@ -72,28 +71,7 @@ func CheckFileAuthMode(notePath string) (crypt.AuthMode, error) {
return "", fmt.Errorf("failed to read file: %w", err)
}
- idx := -1
- for i, b := range data {
- if b == ':' {
- idx = i
- break
- }
- }
- if idx == -1 {
- return "", fmt.Errorf("invalid file format: no header length prefix found")
- }
-
- headerLen, err := strconv.Atoi(string(data[:idx]))
- if err != nil {
- return "", fmt.Errorf("failed to parse header length: %w", err)
- }
-
- if headerLen < 0 || idx+1+headerLen > len(data) {
- return "", fmt.Errorf("invalid header length %d", headerLen)
- }
-
- headerBytes := data[idx+1 : idx+1+headerLen]
- headers, err := crypt.GetFileHeaders(headerBytes)
+ headers, _, err := crypt.ParseFileHeaders(data)
if err != nil {
return "", fmt.Errorf("failed to decode headers: %w", err)
}