diff options
| author | ishaan <contact@ishaan.cc> | 2026-08-03 11:14:58 +0530 |
|---|---|---|
| committer | ishaan <contact@ishaan.cc> | 2026-08-03 11:14:58 +0530 |
| commit | b65769aadfc79d22672d4bd512443f0dda8cf6ad (patch) | |
| tree | d3f216e0139e665478ee799297c00ed089ea612c /internal/crypt/rekey.go | |
| parent | cc4b5b69f1befe84551c0dbcb3df61eeea165cf7 (diff) | |
feat: add rekeying for notes with passphrases or SSH
Diffstat (limited to 'internal/crypt/rekey.go')
| -rw-r--r-- | internal/crypt/rekey.go | 74 |
1 files changed, 74 insertions, 0 deletions
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 +} |