From e48a02646f60b6fdff8db5c4105896756584ac63 Mon Sep 17 00:00:00 2001 From: ishaan Date: Sun, 19 Jul 2026 18:33:40 +0530 Subject: reorganize --- cmd/eno/cobra.go | 223 ------------------------ internal/config/config.go | 194 --------------------- internal/config/config_file.go | 47 +++++ internal/config/config_ops.go | 163 +++++++++++++++++ internal/crud/cli_edit.go | 24 +-- internal/crud/cli_new.go | 384 ----------------------------------------- internal/crud/cli_new_pass.go | 161 +++++++++++++++++ internal/crud/cli_new_ssh.go | 234 +++++++++++++++++++++++++ internal/crypt/headers.go | 33 ++++ internal/crypt/rawDecrypt.go | 166 ------------------ internal/crypt/rawEncrypt.go | 101 ----------- internal/crypt/raw_decrypt.go | 99 +++++++++++ internal/crypt/raw_encrypt.go | 101 +++++++++++ internal/crypt/sshKey.go | 239 ------------------------- internal/crypt/ssh_key.go | 207 ++++++++++++++++++++++ internal/crypt/ssh_key_io.go | 39 +++++ internal/utils/utils.go | 24 +-- 17 files changed, 1086 insertions(+), 1353 deletions(-) create mode 100644 internal/config/config_file.go create mode 100644 internal/config/config_ops.go delete mode 100644 internal/crud/cli_new.go create mode 100644 internal/crud/cli_new_pass.go create mode 100644 internal/crud/cli_new_ssh.go delete mode 100644 internal/crypt/rawDecrypt.go delete mode 100644 internal/crypt/rawEncrypt.go create mode 100644 internal/crypt/raw_decrypt.go create mode 100644 internal/crypt/raw_encrypt.go delete mode 100644 internal/crypt/sshKey.go create mode 100644 internal/crypt/ssh_key.go create mode 100644 internal/crypt/ssh_key_io.go diff --git a/cmd/eno/cobra.go b/cmd/eno/cobra.go index 93cba8b..7283df1 100644 --- a/cmd/eno/cobra.go +++ b/cmd/eno/cobra.go @@ -1,16 +1,10 @@ package main import ( - "fmt" "os" - "path/filepath" - "strings" "github.com/spf13/cobra" "gitlab.com/whiteboardguy/eno/internal/config" - "gitlab.com/whiteboardguy/eno/internal/crud" - "gitlab.com/whiteboardguy/eno/internal/crypt" - "gitlab.com/whiteboardguy/eno/internal/utils" ) var cobraCmd = &cobra.Command{ @@ -18,173 +12,6 @@ var cobraCmd = &cobra.Command{ Short: "file encryption tool", } -var encryptCmd = &cobra.Command{ - Use: "encrypt ", - Short: "encrypt a file", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - output, err := cmd.Flags().GetString("output") - if err != nil { - return fmt.Errorf("failed to get output flag: %v", err) - } - - if output == "" { - output = args[0] + ".eno" - } - - if _, err := os.Stat(output); err == nil { - ok, err := utils.AskUserYesNo("file '"+output+"' already exists. Overwrite?", false) - if err != nil { - return err - } - if !ok { - return fmt.Errorf("write aborted") - } - } - - fileBytes, err := os.ReadFile(args[0]) - if err != nil { - return fmt.Errorf("failed to read input file: %v", err) - } - crypt.TryMlock(fileBytes) - defer clear(fileBytes) - - sshFlag, err := cmd.Flags().GetBool("ssh") - if err != nil { - return fmt.Errorf("failed to get ssh flag: %v", err) - } - - if sshFlag { - if config.Conf.DefaultSSHPubPath == "" { - return fmt.Errorf("SSH not configured. Run 'eno ssh init' first") - } - defaultPubKeyBytes, err := os.ReadFile(config.Conf.DefaultSSHPubPath) - if err != nil { - return fmt.Errorf("failed to read default SSH public key: %v", err) - } - pubKeys, _, err := crud.PromptRecipientKeys(defaultPubKeyBytes) - if err != nil { - return err - } - if len(pubKeys) == 0 { - return fmt.Errorf("at least one recipient public key is required") - } - encrypted, _, err := crypt.EncryptBytesSSH(fileBytes, pubKeys) - if err != nil { - clear(fileBytes) - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - - if err := os.WriteFile(output, encrypted, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - } - - fmt.Printf("Enter a passphrase: ") - password, err := utils.TakeSecureUserInput() - if err != nil { - return fmt.Errorf("failed to read passphrase: %v", err) - } - crypt.TryMlock(password) - defer clear(password) - - encrypted, err := crypt.EncryptBytesPass(fileBytes, password) - if err != nil { - clear(fileBytes) - clear(password) - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - - if err := os.WriteFile(output, encrypted, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - }, -} - -var decryptCmd = &cobra.Command{ - Use: "decrypt ", - Short: "decrypt a file", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - output, err := cmd.Flags().GetString("output") - if err != nil { - return fmt.Errorf("failed to get output flag: %v", err) - } - - if output == "" { - output = strings.TrimSuffix(args[0], ".eno") - } - - if _, err := os.Stat(output); err == nil { - ok, err := utils.AskUserYesNo("file '"+output+"' already exists. Overwrite?", false) - if err != nil { - return err - } - if !ok { - return fmt.Errorf("write aborted") - } - } - - fileBytes, err := os.ReadFile(args[0]) - if err != nil { - return fmt.Errorf("failed to read input file: %v", err) - } - - authMode, err := utils.CheckFileAuthMode(args[0]) - if err != nil { - return fmt.Errorf("failed to check auth mode: %v", err) - } - - if authMode == crypt.SSH { - if config.Conf.DefaultSSHPrivPath == "" { - return fmt.Errorf("SSH not configured. Run 'eno ssh init' first") - } - plaintext, err := crypt.DecryptBytesSSH(fileBytes, config.Conf.DefaultSSHPrivPath) - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - crypt.TryMlock(plaintext) - defer clear(plaintext) - - if err := os.WriteFile(output, plaintext, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - } - - 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) - - plaintext, err := crypt.DecryptBytesPass(fileBytes, password) - if err != nil { - clear(password) - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - crypt.TryMlock(plaintext) - defer clear(plaintext) - - if err := os.WriteFile(output, plaintext, 0600); err != nil { - return fmt.Errorf("failed to write output file: %v", err) - } - - return nil - }, -} - var initCmd = &cobra.Command{ Use: "init", Short: "intialize Eno config", @@ -200,56 +27,6 @@ var initCmd = &cobra.Command{ }, } -var editCmd = &cobra.Command{ - Use: "edit ", - Short: "edit an existing encrypted note", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { - - target := filepath.Clean(args[0]) - - ok, err := utils.AskUserYesNo("Edit "+target+" ?", true) - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - if !ok { - cmd.PrintErrln("Error: write aborted") - os.Exit(1) - } - - target = strings.TrimSuffix(target, ".eno") - target += ".eno" - - if _, err := os.Stat(target); os.IsNotExist(err) { - alt := filepath.Join(config.Conf.DataDir, target) - if _, err2 := os.Stat(alt); err2 == nil { - target = alt - } - } - - authMode, err := utils.CheckFileAuthMode(target) - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - - switch authMode { - case crypt.SSH: - err = crud.EditNoteSSH(target, config.Conf.DefaultSSHPrivPath, config.Conf.EditorString) - case crypt.Pass: - err = crud.EditNotePass(target, config.Conf.EditorString) - default: - cmd.PrintErrln("Error: unknown auth mode:", authMode) - os.Exit(1) - } - if err != nil { - cmd.PrintErrln("Error:", err) - os.Exit(1) - } - }, -} - func init() { encryptCmd.Flags().StringP("output", "o", "", "output file (required)") encryptCmd.Flags().Bool("ssh", false, "encrypt using SSH public keys (interactive)") 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.go b/internal/crud/cli_new.go deleted file mode 100644 index 8e56490..0000000 --- a/internal/crud/cli_new.go +++ /dev/null @@ -1,384 +0,0 @@ -package crud - -import ( - "bytes" - "fmt" - "os" - "strings" - - "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 -} - -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 { - return nil, false, fmt.Errorf("failed to read confirmation: %v", err) - } - if !useDefault { - fmt.Println("Warning: you will not be able to open or edit this note again.") - fmt.Println(" make sure you've used the '--edit' flag.") - } - - addMore, err := utils.AskUserYesNo("Do you want to add more public keys?", false) - if err != nil { - return nil, false, fmt.Errorf("failed to read confirmation: %v", err) - } - - pubKeys := [][]byte{} - - if useDefault { - pubKeys = append(pubKeys, defaultPubKeyBytes) - } - - if addMore { - for { - fmt.Println("Enter public keys (\033[1mcomma-separated for multiple\033[0m):") - fmt.Println("Example: ~/keys/bob.pub, ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AA..., bob@github, james@gitlab") - fmt.Print("Public Keys: ") - utils.StdinScanner.Scan() - if err := utils.StdinScanner.Err(); err != nil { - return nil, false, fmt.Errorf("failed to read public key: %v", err) - } - - input := strings.TrimSpace(utils.StdinScanner.Text()) - if input == "" { - continue - } - - for part := range strings.SplitSeq(input, ",") { - part = strings.TrimSpace(part) - if part == "" { - continue - } - - if strings.Contains(part, "@") && !strings.HasPrefix(part, "ssh-") { - parts := strings.Split(part, "@") - if len(parts) != 2 { - return nil, false, fmt.Errorf("unsupported source or invalid key format: %s", part) - } - - username, service := parts[0], parts[1] - body, err := utils.GetPubKeyFromService(username, service) - 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 - } - for _, k := range selectedKeys { - pubKeys = append(pubKeys, bytes.TrimSpace(k)) - } - continue - } - - var keyBytes []byte - if strings.HasPrefix(part, "ssh-") { - keyBytes = []byte(part) - } else { - var err error - keyBytes, err = os.ReadFile(part) - if err != nil { - return nil, false, fmt.Errorf("failed to read public key file %s: %v", part, err) - } - } - pubKeys = append(pubKeys, bytes.TrimSpace(keyBytes)) - } - - more, err := utils.AskUserYesNo("Add more public keys?", false) - if err != nil { - return nil, false, fmt.Errorf("failed to read confirmation: %v", err) - } - if !more { - break - } - } - } - - return pubKeys, useDefault, nil -} - -func NewNoteSSH(output string, defaultPubKeyBytes []byte) error { - pubKeys, _, err := PromptRecipientKeys(defaultPubKeyBytes) - if err != nil { - return err - } - if len(pubKeys) == 0 { - return fmt.Errorf("at least one recipient public key is required") - } - - tmptxt := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...) - - encrypted, _, err := crypt.EncryptBytesSSH(tmptxt, pubKeys) - 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 NewNoteSSHEdit(output string, defaultPubKeyBytes []byte, defaultPrivKeyPath string, editorString string) error { - pubKeys, useDefault, err := PromptRecipientKeys(defaultPubKeyBytes) - if err != nil { - return err - } - if len(pubKeys) == 0 { - return fmt.Errorf("at least one recipient public key is required") - } - - noteInfo, err := os.Stat(output) - preExisting := err == nil - - initialContent := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...) - encrypted, noteKey, err := crypt.EncryptBytesSSH(initialContent, pubKeys) - if err != nil { - return err - } - crypt.TryMlock(noteKey) - defer clear(noteKey) - - 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 - } - - var plaintext []byte - if useDefault { - plaintext, err = crypt.DecryptBytesSSH(ciphertext, defaultPrivKeyPath) - } else { - plaintext, err = crypt.DecryptBytesSSHWithKey(ciphertext, noteKey) - } - 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.EncryptBytesSSH(newContent, pubKeys) - 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_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_ssh.go b/internal/crud/cli_new_ssh.go new file mode 100644 index 0000000..5479490 --- /dev/null +++ b/internal/crud/cli_new_ssh.go @@ -0,0 +1,234 @@ +package crud + +import ( + "bytes" + "fmt" + "os" + "strings" + + "gitlab.com/whiteboardguy/eno/internal/crypt" + "gitlab.com/whiteboardguy/eno/internal/editor" + "gitlab.com/whiteboardguy/eno/internal/utils" +) + +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 { + return nil, false, fmt.Errorf("failed to read confirmation: %v", err) + } + if !useDefault { + fmt.Println("Warning: you will not be able to open or edit this note again.") + fmt.Println(" make sure you've used the '--edit' flag.") + } + + addMore, err := utils.AskUserYesNo("Do you want to add more public keys?", false) + if err != nil { + return nil, false, fmt.Errorf("failed to read confirmation: %v", err) + } + + pubKeys := [][]byte{} + + if useDefault { + pubKeys = append(pubKeys, defaultPubKeyBytes) + } + + if addMore { + for { + fmt.Println("Enter public keys (\033[1mcomma-separated for multiple\033[0m):") + fmt.Println("Example: ~/keys/bob.pub, ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AA..., bob@github, james@gitlab") + fmt.Print("Public Keys: ") + utils.StdinScanner.Scan() + if err := utils.StdinScanner.Err(); err != nil { + return nil, false, fmt.Errorf("failed to read public key: %v", err) + } + + input := strings.TrimSpace(utils.StdinScanner.Text()) + if input == "" { + continue + } + + for part := range strings.SplitSeq(input, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + + if strings.Contains(part, "@") && !strings.HasPrefix(part, "ssh-") { + parts := strings.Split(part, "@") + if len(parts) != 2 { + return nil, false, fmt.Errorf("unsupported source or invalid key format: %s", part) + } + + username, service := parts[0], parts[1] + body, err := utils.GetPubKeyFromService(username, service) + 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 + } + for _, k := range selectedKeys { + pubKeys = append(pubKeys, bytes.TrimSpace(k)) + } + continue + } + + var keyBytes []byte + if strings.HasPrefix(part, "ssh-") { + keyBytes = []byte(part) + } else { + var err error + keyBytes, err = os.ReadFile(part) + if err != nil { + return nil, false, fmt.Errorf("failed to read public key file %s: %v", part, err) + } + } + pubKeys = append(pubKeys, bytes.TrimSpace(keyBytes)) + } + + more, err := utils.AskUserYesNo("Add more public keys?", false) + if err != nil { + return nil, false, fmt.Errorf("failed to read confirmation: %v", err) + } + if !more { + break + } + } + } + + return pubKeys, useDefault, nil +} + +func NewNoteSSH(output string, defaultPubKeyBytes []byte) error { + pubKeys, _, err := PromptRecipientKeys(defaultPubKeyBytes) + if err != nil { + return err + } + if len(pubKeys) == 0 { + return fmt.Errorf("at least one recipient public key is required") + } + + tmptxt := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...) + + encrypted, _, err := crypt.EncryptBytesSSH(tmptxt, pubKeys) + 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 NewNoteSSHEdit(output string, defaultPubKeyBytes []byte, defaultPrivKeyPath string, editorString string) error { + pubKeys, useDefault, err := PromptRecipientKeys(defaultPubKeyBytes) + if err != nil { + return err + } + if len(pubKeys) == 0 { + return fmt.Errorf("at least one recipient public key is required") + } + + noteInfo, err := os.Stat(output) + preExisting := err == nil + + initialContent := append(utils.RandomLettersNumbers(37), "\nYou can Delete all of this ^^^"...) + encrypted, noteKey, err := crypt.EncryptBytesSSH(initialContent, pubKeys) + if err != nil { + return err + } + crypt.TryMlock(noteKey) + defer clear(noteKey) + + 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 + } + + var plaintext []byte + if useDefault { + plaintext, err = crypt.DecryptBytesSSH(ciphertext, defaultPrivKeyPath) + } else { + plaintext, err = crypt.DecryptBytesSSHWithKey(ciphertext, noteKey) + } + 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.EncryptBytesSSH(newContent, pubKeys) + 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/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/rawDecrypt.go deleted file mode 100644 index ede063c..0000000 --- a/internal/crypt/rawDecrypt.go +++ /dev/null @@ -1,166 +0,0 @@ -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) - if err != nil { - return nil, fmt.Errorf("decrypt: %w", err) - } - - if headers.Auth != Pass { - return nil, fmt.Errorf("decrypt: expected password auth, got %s", headers.Auth) - } - - key := argon2.IDKey(password, headers.Salt[:], 1, 2*1024*1024, 2, 32) - TryMlock(key) - defer clear(key) - aead, err := chacha20poly1305.New(key) - if err != nil { - 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) - } - - return plaintext, nil -} - -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) - if err != nil { - return nil, fmt.Errorf("decrypt: %w", err) - } - - if headers.Auth != SSH { - return nil, fmt.Errorf("decrypt: expected SSH auth, got %s", headers.Auth) - } - - if len(headers.Recipients) == 0 { - return nil, fmt.Errorf("decrypt: no recipients found in headers") - } - - key := []byte{} - TryMlock(key) - defer clear(key) - if len(headers.Recipients) == 1 { - key, err = UnwrapNoteKey(headers.Recipients[0], privKeyPath) - if err != nil { - return nil, fmt.Errorf("decrypt: failed to unwrap note key: %w", err) - } - } else { - key, err = FindAndUnwrapNoteKey(headers.Recipients, privKeyPath) - if err != nil { - return nil, fmt.Errorf("decrypt: failed to unwrap note key: %w", err) - } - } - - aead, err := chacha20poly1305.New(key) - if err != nil { - 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) - } - - return plaintext, nil -} - -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) - if err != nil { - return nil, fmt.Errorf("decrypt: %w", err) - } - - if headers.Auth != SSH { - return nil, fmt.Errorf("decrypt: expected SSH auth, got %s", headers.Auth) - } - - aead, err := chacha20poly1305.New(noteKey) - if err != nil { - 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) - } - - return plaintext, nil -} diff --git a/internal/crypt/rawEncrypt.go b/internal/crypt/rawEncrypt.go deleted file mode 100644 index 03f742f..0000000 --- a/internal/crypt/rawEncrypt.go +++ /dev/null @@ -1,101 +0,0 @@ -package crypt - -import ( - "crypto/rand" - "fmt" - "strconv" - - "golang.org/x/crypto/argon2" - "golang.org/x/crypto/chacha20poly1305" -) - -func EncryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { - salt, err := NewSalt() - if err != nil { - return nil, fmt.Errorf("encrypt: %w", err) - } - - nonce, err := NewNonce() - if err != nil { - return nil, fmt.Errorf("encrypt: %w", err) - } - - headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: Pass, Recipients: []WrappedKey{}} - - key := argon2.IDKey(password, headers.Salt[:], 1, 2*1024*1024, 2, 32) - TryMlock(key) - defer clear(key) - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, fmt.Errorf("encrypt: failed to create cipher: %w", err) - } - - encrypted := aead.Seal(nil, headers.Nonce[:], inputBytes, nil) - - headerBytes, err := FileHeadersBytes(headers) - if err != nil { - return nil, fmt.Errorf("encrypt: %w", err) - } - - lenLen := len(strconv.Itoa(len(headerBytes))) - target := make([]byte, 0, lenLen+1+len(headerBytes)+len(encrypted)) - target = fmt.Appendf(target, "%d:", len(headerBytes)) - target = append(target, headerBytes...) - target = append(target, encrypted...) - - return target, nil -} - -func EncryptBytesSSH(inputBytes []byte, pubKeys [][]byte) ([]byte, []byte, error) { - salt, err := NewSalt() - if err != nil { - return nil, nil, fmt.Errorf("encrypt: %w", err) - } - - nonce, err := NewNonce() - if err != nil { - return nil, nil, fmt.Errorf("encrypt: %w", err) - } - - key := [32]byte{} - _, err = rand.Read(key[:]) - if err != nil { - return nil, nil, fmt.Errorf("encrypt: failed to generate key: %w", err) - } - TryMlock(key[:]) - defer clear(key[:]) - - noteKey := make([]byte, 32) - copy(noteKey, key[:]) - TryMlock(noteKey) - - recipients, err := WrapNoteKeyForRecipients(key[:], pubKeys) - if err != nil { - clear(noteKey) - return nil, nil, err - } - - headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: SSH, Recipients: recipients} - - aead, err := chacha20poly1305.New(key[:]) - if err != nil { - clear(noteKey) - return nil, nil, fmt.Errorf("encrypt: failed to create cipher: %w", err) - } - - encrypted := aead.Seal(nil, headers.Nonce[:], inputBytes, nil) - - headerBytes, err := FileHeadersBytes(headers) - if err != nil { - clear(noteKey) - return nil, nil, fmt.Errorf("encrypt: %w", err) - } - - lenLen := len(strconv.Itoa(len(headerBytes))) - target := make([]byte, 0, lenLen+1+len(headerBytes)+len(encrypted)) - target = fmt.Appendf(target, "%d:", len(headerBytes)) - target = append(target, headerBytes...) - target = append(target, encrypted...) - - return target, noteKey, nil -} diff --git a/internal/crypt/raw_decrypt.go b/internal/crypt/raw_decrypt.go new file mode 100644 index 0000000..050a4ec --- /dev/null +++ b/internal/crypt/raw_decrypt.go @@ -0,0 +1,99 @@ +package crypt + +import ( + "fmt" + + "golang.org/x/crypto/argon2" + "golang.org/x/crypto/chacha20poly1305" +) + +func DecryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { + headers, ciphertext, err := ParseFileHeaders(inputBytes) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + if headers.Auth != Pass { + return nil, fmt.Errorf("decrypt: expected password auth, got %s", headers.Auth) + } + + key := argon2.IDKey(password, headers.Salt[:], 1, 2*1024*1024, 2, 32) + TryMlock(key) + defer clear(key) + aead, err := chacha20poly1305.New(key) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err) + } + + plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + return plaintext, nil +} + +func DecryptBytesSSH(inputBytes []byte, privKeyPath string) ([]byte, error) { + headers, ciphertext, err := ParseFileHeaders(inputBytes) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + if headers.Auth != SSH { + return nil, fmt.Errorf("decrypt: expected SSH auth, got %s", headers.Auth) + } + + if len(headers.Recipients) == 0 { + return nil, fmt.Errorf("decrypt: no recipients found in headers") + } + + key := []byte{} + TryMlock(key) + defer clear(key) + if len(headers.Recipients) == 1 { + key, err = UnwrapNoteKey(headers.Recipients[0], privKeyPath) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to unwrap note key: %w", err) + } + } else { + key, err = FindAndUnwrapNoteKey(headers.Recipients, privKeyPath) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to unwrap note key: %w", err) + } + } + + aead, err := chacha20poly1305.New(key) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err) + } + + plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + return plaintext, nil +} + +func DecryptBytesSSHWithKey(inputBytes []byte, noteKey []byte) ([]byte, error) { + headers, ciphertext, err := ParseFileHeaders(inputBytes) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + if headers.Auth != SSH { + return nil, fmt.Errorf("decrypt: expected SSH auth, got %s", headers.Auth) + } + + aead, err := chacha20poly1305.New(noteKey) + if err != nil { + return nil, fmt.Errorf("decrypt: failed to create cipher: %w", err) + } + + plaintext, err := aead.Open(nil, headers.Nonce[:], ciphertext, nil) + if err != nil { + return nil, fmt.Errorf("decrypt: %w", err) + } + + return plaintext, nil +} diff --git a/internal/crypt/raw_encrypt.go b/internal/crypt/raw_encrypt.go new file mode 100644 index 0000000..03f742f --- /dev/null +++ b/internal/crypt/raw_encrypt.go @@ -0,0 +1,101 @@ +package crypt + +import ( + "crypto/rand" + "fmt" + "strconv" + + "golang.org/x/crypto/argon2" + "golang.org/x/crypto/chacha20poly1305" +) + +func EncryptBytesPass(inputBytes []byte, password []byte) ([]byte, error) { + salt, err := NewSalt() + if err != nil { + return nil, fmt.Errorf("encrypt: %w", err) + } + + nonce, err := NewNonce() + if err != nil { + return nil, fmt.Errorf("encrypt: %w", err) + } + + headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: Pass, Recipients: []WrappedKey{}} + + key := argon2.IDKey(password, headers.Salt[:], 1, 2*1024*1024, 2, 32) + TryMlock(key) + defer clear(key) + aead, err := chacha20poly1305.New(key) + if err != nil { + return nil, fmt.Errorf("encrypt: failed to create cipher: %w", err) + } + + encrypted := aead.Seal(nil, headers.Nonce[:], inputBytes, nil) + + headerBytes, err := FileHeadersBytes(headers) + if err != nil { + return nil, fmt.Errorf("encrypt: %w", err) + } + + lenLen := len(strconv.Itoa(len(headerBytes))) + target := make([]byte, 0, lenLen+1+len(headerBytes)+len(encrypted)) + target = fmt.Appendf(target, "%d:", len(headerBytes)) + target = append(target, headerBytes...) + target = append(target, encrypted...) + + return target, nil +} + +func EncryptBytesSSH(inputBytes []byte, pubKeys [][]byte) ([]byte, []byte, error) { + salt, err := NewSalt() + if err != nil { + return nil, nil, fmt.Errorf("encrypt: %w", err) + } + + nonce, err := NewNonce() + if err != nil { + return nil, nil, fmt.Errorf("encrypt: %w", err) + } + + key := [32]byte{} + _, err = rand.Read(key[:]) + if err != nil { + return nil, nil, fmt.Errorf("encrypt: failed to generate key: %w", err) + } + TryMlock(key[:]) + defer clear(key[:]) + + noteKey := make([]byte, 32) + copy(noteKey, key[:]) + TryMlock(noteKey) + + recipients, err := WrapNoteKeyForRecipients(key[:], pubKeys) + if err != nil { + clear(noteKey) + return nil, nil, err + } + + headers := FileHeaders{Salt: salt, Nonce: nonce, Type: File, Parts: 1, Auth: SSH, Recipients: recipients} + + aead, err := chacha20poly1305.New(key[:]) + if err != nil { + clear(noteKey) + return nil, nil, fmt.Errorf("encrypt: failed to create cipher: %w", err) + } + + encrypted := aead.Seal(nil, headers.Nonce[:], inputBytes, nil) + + headerBytes, err := FileHeadersBytes(headers) + if err != nil { + clear(noteKey) + return nil, nil, fmt.Errorf("encrypt: %w", err) + } + + lenLen := len(strconv.Itoa(len(headerBytes))) + target := make([]byte, 0, lenLen+1+len(headerBytes)+len(encrypted)) + target = fmt.Appendf(target, "%d:", len(headerBytes)) + target = append(target, headerBytes...) + target = append(target, encrypted...) + + return target, noteKey, nil +} diff --git a/internal/crypt/sshKey.go b/internal/crypt/sshKey.go deleted file mode 100644 index 2062ebd..0000000 --- a/internal/crypt/sshKey.go +++ /dev/null @@ -1,239 +0,0 @@ -package crypt - -// read/thanks to https://words.filippo.io/using-ed25519-keys-for-encryption/ - -import ( - "bytes" - "crypto/ed25519" - "crypto/rand" - "crypto/sha256" - "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" -) - -// Ed25519 pubkey -> X25519 pubkey. Both 32B -func edwardsToMontgomery(edPub []byte) []byte { - edPubCopy := make([]byte, 32) - copy(edPubCopy, edPub) - edPubCopy[31] &= 0x7F - - y := new(field.Element) - y.SetBytes(edPubCopy) - - one := new(field.Element).One() - - var num, denom, inv, u field.Element - num.Add(one, y) - denom.Subtract(one, y) - inv.Invert(&denom) - u.Multiply(&num, &inv) - - return u.Bytes() -} - -// Ed25519 seed -> X25519 private key. -func ed25519SeedToX25519Priv(seed []byte) []byte { - h := sha512.Sum512(seed) - scalar := make([]byte, 32) - copy(scalar, h[:32]) - clear(h[:]) - - scalar[0] &= 248 - scalar[31] &= 127 - scalar[31] |= 64 - - 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)) - for _, pubKeyBytes := range pubKeys { - parsed, _, _, _, err := ssh.ParseAuthorizedKey(pubKeyBytes) - if err != nil { - return nil, fmt.Errorf("parse SSH pub key: %w", err) - } - - cryptoPub := parsed.(ssh.CryptoPublicKey).CryptoPublicKey() - edPub, ok := cryptoPub.(ed25519.PublicKey) - if !ok { - return nil, fmt.Errorf("only Ed25519 SSH keys supported") - } - - xPub := edwardsToMontgomery(edPub) - - ephPriv := make([]byte, 32) - if _, err := rand.Read(ephPriv); err != nil { - return nil, fmt.Errorf("generate ephemeral key: %w", err) - } - ephPub, err := curve25519.X25519(ephPriv, curve25519.Basepoint) - if err != nil { - return nil, fmt.Errorf("ephemeral pub: %w", err) - } - - shared, err := curve25519.X25519(ephPriv, xPub) - if err != nil { - return nil, fmt.Errorf("ECDH: %w", err) - } - - wrapKey := sha256.Sum256(shared) - aead, err := chacha20poly1305.New(wrapKey[:]) - if err != nil { - return nil, fmt.Errorf("wrap cipher: %w", err) - } - - var nonce [12]byte - if _, err := rand.Read(nonce[:]); err != nil { - return nil, fmt.Errorf("nonce: %w", err) - } - - encNoteKey := aead.Seal(nil, nonce[:], noteKey, nil) - - recipients = append(recipients, WrappedKey{ - PKType: "ssh-ed25519", - PubKeyBytes: ssh.MarshalAuthorizedKey(parsed), - EphemeralPub: ephPub, - Nonce: nonce, - EncNoteKey: encNoteKey, - }) - } - return recipients, nil -} - -func parsePrivateKeyFile(privKeyPath string) (*ed25519.PrivateKey, []byte, error) { - pemBytes, err := os.ReadFile(privKeyPath) - if err != nil { - return nil, nil, fmt.Errorf("read SSH key: %w", err) - } - TryMlock(pemBytes) - - parsed, err := ssh.ParseRawPrivateKey(pemBytes) - if err != nil { - if _, ok := err.(*ssh.PassphraseMissingError); ok { - passphrase := promptSSHKeyPassphrase(privKeyPath) - if passphrase == nil { - return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err) - } - defer clear(passphrase) - parsed, err = ssh.ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase) - if err != nil { - return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err) - } - } else { - return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err) - } - } - - edPriv, ok := parsed.(*ed25519.PrivateKey) - if !ok { - return nil, pemBytes, fmt.Errorf("only Ed25519 SSH keys supported") - } - - return edPriv, pemBytes, nil -} - -func unwrapNoteKeyWithKey(wrapped WrappedKey, edPriv *ed25519.PrivateKey) ([]byte, error) { - seed := edPriv.Seed() - TryMlock(seed) - defer clear(seed) - - xPriv := ed25519SeedToX25519Priv(seed) - TryMlock(xPriv) - defer clear(xPriv) - - shared, err := curve25519.X25519(xPriv, wrapped.EphemeralPub) - if err != nil { - return nil, fmt.Errorf("ECDH: %w", err) - } - TryMlock(shared) - defer clear(shared) - - wrapKey := sha256.Sum256(shared) - aead, err := chacha20poly1305.New(wrapKey[:]) - if err != nil { - return nil, fmt.Errorf("unwrap cipher: %w", err) - } - TryMlock(wrapKey[:]) - defer clear(wrapKey[:]) - - noteKey, err := aead.Open(nil, wrapped.Nonce[:], wrapped.EncNoteKey, nil) - if err != nil { - return nil, fmt.Errorf("unwrap note key: %w", err) - } - TryMlock(noteKey) - - return noteKey, nil -} - -// Decrypts the note key using the private key at privKeyPath. -func UnwrapNoteKey(wrapped WrappedKey, privKeyPath string) ([]byte, error) { - edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath) - if err != nil { - return nil, err - } - defer clear(pemBytes) - - return unwrapNoteKeyWithKey(wrapped, edPriv) -} - -// Finds the recipient matching privKeyPath in case of multiple recipients, returns note key. -func FindAndUnwrapNoteKey(recipients []WrappedKey, privKeyPath string) ([]byte, error) { - edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath) - if err != nil { - return nil, err - } - defer clear(pemBytes) - - pubKey := edPriv.Public().(ed25519.PublicKey) - sshPub, err := ssh.NewPublicKey(pubKey) - if err != nil { - return nil, fmt.Errorf("derive SSH pub key: %w", err) - } - ownPubKeyBytes := ssh.MarshalAuthorizedKey(sshPub) - - for _, recipient := range recipients { - if bytes.Equal(recipient.PubKeyBytes, ownPubKeyBytes) { - return unwrapNoteKeyWithKey(recipient, edPriv) - } - } - - return nil, fmt.Errorf("no matching recipient found") -} diff --git a/internal/crypt/ssh_key.go b/internal/crypt/ssh_key.go new file mode 100644 index 0000000..a043f75 --- /dev/null +++ b/internal/crypt/ssh_key.go @@ -0,0 +1,207 @@ +package crypt + +// read/thanks to https://words.filippo.io/using-ed25519-keys-for-encryption/ + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "crypto/sha512" + "fmt" + "os" + + "filippo.io/edwards25519/field" + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/ssh" +) + +// Ed25519 pubkey -> X25519 pubkey. Both 32B +func edwardsToMontgomery(edPub []byte) []byte { + edPubCopy := make([]byte, 32) + copy(edPubCopy, edPub) + edPubCopy[31] &= 0x7F + + y := new(field.Element) + y.SetBytes(edPubCopy) + + one := new(field.Element).One() + + var num, denom, inv, u field.Element + num.Add(one, y) + denom.Subtract(one, y) + inv.Invert(&denom) + u.Multiply(&num, &inv) + + return u.Bytes() +} + +// Ed25519 seed -> X25519 private key. +func ed25519SeedToX25519Priv(seed []byte) []byte { + h := sha512.Sum512(seed) + scalar := make([]byte, 32) + copy(scalar, h[:32]) + clear(h[:]) + + scalar[0] &= 248 + scalar[31] &= 127 + scalar[31] |= 64 + + return scalar +} + +// Wraps noteKey once per PubKey. Returns WrappedKey for each. +func WrapNoteKeyForRecipients(noteKey []byte, pubKeys [][]byte) ([]WrappedKey, error) { + recipients := make([]WrappedKey, 0, len(pubKeys)) + for _, pubKeyBytes := range pubKeys { + parsed, _, _, _, err := ssh.ParseAuthorizedKey(pubKeyBytes) + if err != nil { + return nil, fmt.Errorf("parse SSH pub key: %w", err) + } + + cryptoPub := parsed.(ssh.CryptoPublicKey).CryptoPublicKey() + edPub, ok := cryptoPub.(ed25519.PublicKey) + if !ok { + return nil, fmt.Errorf("only Ed25519 SSH keys supported") + } + + xPub := edwardsToMontgomery(edPub) + + ephPriv := make([]byte, 32) + if _, err := rand.Read(ephPriv); err != nil { + return nil, fmt.Errorf("generate ephemeral key: %w", err) + } + ephPub, err := curve25519.X25519(ephPriv, curve25519.Basepoint) + if err != nil { + return nil, fmt.Errorf("ephemeral pub: %w", err) + } + + shared, err := curve25519.X25519(ephPriv, xPub) + if err != nil { + return nil, fmt.Errorf("ECDH: %w", err) + } + + wrapKey := sha256.Sum256(shared) + aead, err := chacha20poly1305.New(wrapKey[:]) + if err != nil { + return nil, fmt.Errorf("wrap cipher: %w", err) + } + + var nonce [12]byte + if _, err := rand.Read(nonce[:]); err != nil { + return nil, fmt.Errorf("nonce: %w", err) + } + + encNoteKey := aead.Seal(nil, nonce[:], noteKey, nil) + + recipients = append(recipients, WrappedKey{ + PKType: "ssh-ed25519", + PubKeyBytes: ssh.MarshalAuthorizedKey(parsed), + EphemeralPub: ephPub, + Nonce: nonce, + EncNoteKey: encNoteKey, + }) + } + return recipients, nil +} + +func parsePrivateKeyFile(privKeyPath string) (*ed25519.PrivateKey, []byte, error) { + pemBytes, err := os.ReadFile(privKeyPath) + if err != nil { + return nil, nil, fmt.Errorf("read SSH key: %w", err) + } + TryMlock(pemBytes) + + parsed, err := ssh.ParseRawPrivateKey(pemBytes) + if err != nil { + if _, ok := err.(*ssh.PassphraseMissingError); ok { + passphrase := promptSSHKeyPassphrase(privKeyPath) + if passphrase == nil { + return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err) + } + defer clear(passphrase) + parsed, err = ssh.ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase) + if err != nil { + return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err) + } + } else { + return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err) + } + } + + edPriv, ok := parsed.(*ed25519.PrivateKey) + if !ok { + return nil, pemBytes, fmt.Errorf("only Ed25519 SSH keys supported") + } + + return edPriv, pemBytes, nil +} + +func unwrapNoteKeyWithKey(wrapped WrappedKey, edPriv *ed25519.PrivateKey) ([]byte, error) { + seed := edPriv.Seed() + TryMlock(seed) + defer clear(seed) + + xPriv := ed25519SeedToX25519Priv(seed) + TryMlock(xPriv) + defer clear(xPriv) + + shared, err := curve25519.X25519(xPriv, wrapped.EphemeralPub) + if err != nil { + return nil, fmt.Errorf("ECDH: %w", err) + } + TryMlock(shared) + defer clear(shared) + + wrapKey := sha256.Sum256(shared) + aead, err := chacha20poly1305.New(wrapKey[:]) + if err != nil { + return nil, fmt.Errorf("unwrap cipher: %w", err) + } + TryMlock(wrapKey[:]) + defer clear(wrapKey[:]) + + noteKey, err := aead.Open(nil, wrapped.Nonce[:], wrapped.EncNoteKey, nil) + if err != nil { + return nil, fmt.Errorf("unwrap note key: %w", err) + } + TryMlock(noteKey) + + return noteKey, nil +} + +// Decrypts the note key using the private key at privKeyPath. +func UnwrapNoteKey(wrapped WrappedKey, privKeyPath string) ([]byte, error) { + edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath) + if err != nil { + return nil, err + } + defer clear(pemBytes) + + return unwrapNoteKeyWithKey(wrapped, edPriv) +} + +// Finds the recipient matching privKeyPath in case of multiple recipients, returns note key. +func FindAndUnwrapNoteKey(recipients []WrappedKey, privKeyPath string) ([]byte, error) { + edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath) + if err != nil { + return nil, err + } + defer clear(pemBytes) + + pubKey := edPriv.Public().(ed25519.PublicKey) + sshPub, err := ssh.NewPublicKey(pubKey) + if err != nil { + return nil, fmt.Errorf("derive SSH pub key: %w", err) + } + ownPubKeyBytes := ssh.MarshalAuthorizedKey(sshPub) + + for _, recipient := range recipients { + if bytes.Equal(recipient.PubKeyBytes, ownPubKeyBytes) { + return unwrapNoteKeyWithKey(recipient, edPriv) + } + } + + return nil, fmt.Errorf("no matching recipient found") +} 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) } -- cgit v1.3