From b65769aadfc79d22672d4bd512443f0dda8cf6ad Mon Sep 17 00:00:00 2001 From: ishaan Date: Mon, 3 Aug 2026 11:14:58 +0530 Subject: feat: add rekeying for notes with passphrases or SSH --- internal/crypt/rekey.go | 74 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 internal/crypt/rekey.go (limited to 'internal/crypt/rekey.go') diff --git a/internal/crypt/rekey.go b/internal/crypt/rekey.go new file mode 100644 index 0000000..5b85ba0 --- /dev/null +++ b/internal/crypt/rekey.go @@ -0,0 +1,74 @@ +package crypt + +import ( + "bytes" + "crypto/ed25519" + "fmt" + + "golang.org/x/crypto/ssh" +) + +// Re-wraps the note key for new recipients, replacing only the caller's wrapped key. +func RekeySSH(inputBytes []byte, privKeyPath string, newPubKeys [][]byte) ([]byte, error) { + headers, ciphertext, err := ParseFileHeaders(inputBytes) + if err != nil { + return nil, fmt.Errorf("rekey: %w", err) + } + + if headers.Auth != SSH { + return nil, fmt.Errorf("rekey: expected SSH auth, got %s", headers.Auth) + } + + if len(newPubKeys) == 0 { + return nil, fmt.Errorf("rekey: at least one recipient public key is required") + } + + edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath) + if err != nil { + return nil, fmt.Errorf("rekey: %w", err) + } + defer clear(pemBytes) + + pubKey := edPriv.Public().(ed25519.PublicKey) + sshPub, err := ssh.NewPublicKey(pubKey) + if err != nil { + return nil, fmt.Errorf("rekey: derive SSH pub key: %w", err) + } + ownPubKeyBytes := ssh.MarshalAuthorizedKey(sshPub) + + var noteKey []byte + remaining := make([]WrappedKey, 0, len(headers.Recipients)) + for _, recipient := range headers.Recipients { + if bytes.Equal(recipient.PubKeyBytes, ownPubKeyBytes) { + noteKey, err = unwrapNoteKeyWithKey(recipient, edPriv) + if err != nil { + return nil, fmt.Errorf("rekey: failed to unwrap note key: %w", err) + } + continue + } + remaining = append(remaining, recipient) + } + + if noteKey == nil { + return nil, fmt.Errorf("rekey: no matching recipient found") + } + defer clear(noteKey) + + newRecipients, err := WrapNoteKeyForRecipients(noteKey, newPubKeys) + if err != nil { + return nil, fmt.Errorf("rekey: %w", err) + } + + if len(remaining)+len(newRecipients) == 0 { + return nil, fmt.Errorf("rekey: at least one recipient is required") + } + + headers.Recipients = append(remaining, newRecipients...) + + packed, err := packFile(headers, ciphertext) + if err != nil { + return nil, fmt.Errorf("rekey: %w", err) + } + + return packed, nil +} -- cgit v1.3