| 1 |
package sign |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"errors" |
| 6 |
|
| 7 |
"github.com/secure-systems-lab/go-securesystemslib/cjson" |
| 8 |
"github.com/theupdateframework/go-tuf/data" |
| 9 |
"github.com/theupdateframework/go-tuf/pkg/keys" |
| 10 |
) |
| 11 |
|
| 12 |
const maxSignatures = 1024 |
| 13 |
|
| 14 |
// MakeSignatures creates data.Signatures for canonical using signer k. |
| 15 |
// |
| 16 |
// There will be one data.Signature for each of k's IDs, each wih the same |
| 17 |
// signature data. |
| 18 |
func MakeSignatures(canonical []byte, k keys.Signer) ([]data.Signature, error) { |
| 19 |
sigData, err := k.SignMessage(canonical) |
| 20 |
if err != nil { |
| 21 |
return nil, err |
| 22 |
} |
| 23 |
|
| 24 |
ids := k.PublicData().IDs() |
| 25 |
signatures := make([]data.Signature, 0, len(ids)) |
| 26 |
for _, id := range ids { |
| 27 |
signatures = append(signatures, data.Signature{ |
| 28 |
KeyID: id, |
| 29 |
Signature: sigData, |
| 30 |
}) |
| 31 |
} |
| 32 |
|
| 33 |
return signatures, nil |
| 34 |
} |
| 35 |
|
| 36 |
// Sign signs the to-be-signed part of s using the signer k. |
| 37 |
// |
| 38 |
// The new signature(s) (one for each of k's key IDs) are appended to |
| 39 |
// s.Signatures. Existing signatures for the Key IDs are replaced. |
| 40 |
func Sign(s *data.Signed, k keys.Signer) error { |
| 41 |
canonical, err := cjson.EncodeCanonical(s.Signed) |
| 42 |
if err != nil { |
| 43 |
return err |
| 44 |
} |
| 45 |
|
| 46 |
size := len(s.Signatures) |
| 47 |
if size > maxSignatures-1 { |
| 48 |
return errors.New("value too large") |
| 49 |
} |
| 50 |
signatures := make([]data.Signature, 0, size+1) |
| 51 |
for _, oldSig := range s.Signatures { |
| 52 |
if !k.PublicData().ContainsID(oldSig.KeyID) { |
| 53 |
signatures = append(signatures, oldSig) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
newSigs, err := MakeSignatures(canonical, k) |
| 58 |
if err != nil { |
| 59 |
return err |
| 60 |
} |
| 61 |
signatures = append(signatures, newSigs...) |
| 62 |
|
| 63 |
s.Signatures = signatures |
| 64 |
return nil |
| 65 |
} |
| 66 |
|
| 67 |
func Marshal(v interface{}, keys ...keys.Signer) (*data.Signed, error) { |
| 68 |
b, err := json.Marshal(v) |
| 69 |
if err != nil { |
| 70 |
return nil, err |
| 71 |
} |
| 72 |
s := &data.Signed{Signed: b, Signatures: make([]data.Signature, 0)} |
| 73 |
for _, k := range keys { |
| 74 |
if err := Sign(s, k); err != nil { |
| 75 |
return nil, err |
| 76 |
} |
| 77 |
|
| 78 |
} |
| 79 |
return s, nil |
| 80 |
} |