|
| 1 | +package a2acrypto |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto" |
| 5 | + "crypto/ecdsa" |
| 6 | + "crypto/rand" |
| 7 | + "encoding/base64" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + |
| 11 | + "github.com/a2aproject/a2a-go/v2/a2a" |
| 12 | +) |
| 13 | + |
| 14 | +// Sign computes a JWS signature for the given AgentCard. |
| 15 | +// It serializes the card to JSON, builds the protected header, and signs. |
| 16 | +func (s *Signer) Sign(card *a2a.AgentCard) (*a2a.AgentCardSignature, error) { |
| 17 | + payload, err := json.Marshal(card) |
| 18 | + if err != nil { |
| 19 | + return nil, fmt.Errorf("failed to marshal agent card: %w", err) |
| 20 | + } |
| 21 | + |
| 22 | + protected := map[string]any{ |
| 23 | + "alg": s.algorithm, |
| 24 | + "kid": s.kid, |
| 25 | + } |
| 26 | + if s.jwksURL != "" { |
| 27 | + protected["jku"] = s.jwksURL |
| 28 | + } |
| 29 | + |
| 30 | + protectedJSON, err := json.Marshal(protected) |
| 31 | + if err != nil { |
| 32 | + return nil, fmt.Errorf("failed to marshal protected header: %w", err) |
| 33 | + } |
| 34 | + |
| 35 | + protectedB64 := base64.RawURLEncoding.EncodeToString(protectedJSON) |
| 36 | + payloadB64 := base64.RawURLEncoding.EncodeToString(payload) |
| 37 | + signingInput := protectedB64 + "." + payloadB64 |
| 38 | + |
| 39 | + hash, err := algToHash(s.algorithm) |
| 40 | + if err != nil { |
| 41 | + return nil, err |
| 42 | + } |
| 43 | + |
| 44 | + var signature []byte |
| 45 | + if hash == 0 { |
| 46 | + signature, err = s.key.Sign(rand.Reader, []byte(signingInput), crypto.Hash(0)) |
| 47 | + } else { |
| 48 | + h := hash.New() |
| 49 | + h.Write([]byte(signingInput)) |
| 50 | + signature, err = s.key.Sign(rand.Reader, h.Sum(nil), hash) |
| 51 | + } |
| 52 | + if err != nil { |
| 53 | + return nil, fmt.Errorf("failed to sign: %w", err) |
| 54 | + } |
| 55 | + |
| 56 | + // Convert ECDSA DER output to raw R||S for JWS compatibility. |
| 57 | + if _, ok := s.key.Public().(*ecdsa.PublicKey); ok { |
| 58 | + signature, err = marshalECDSASignature(signature, s.key.Public().(*ecdsa.PublicKey).Curve) |
| 59 | + if err != nil { |
| 60 | + return nil, fmt.Errorf("failed to convert ECDSA signature: %w", err) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return &a2a.AgentCardSignature{ |
| 65 | + Protected: protectedB64, |
| 66 | + Signature: base64.RawURLEncoding.EncodeToString(signature), |
| 67 | + }, nil |
| 68 | +} |
0 commit comments