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 }