| 1 |
package keys |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto" |
| 6 |
"crypto/x509" |
| 7 |
"encoding/json" |
| 8 |
"encoding/pem" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
) |
| 13 |
|
| 14 |
type PKIXPublicKey struct { |
| 15 |
crypto.PublicKey |
| 16 |
} |
| 17 |
|
| 18 |
func (p *PKIXPublicKey) MarshalJSON() ([]byte, error) { |
| 19 |
bytes, err := x509.MarshalPKIXPublicKey(p.PublicKey) |
| 20 |
if err != nil { |
| 21 |
return nil, err |
| 22 |
} |
| 23 |
pemBytes := pem.EncodeToMemory(&pem.Block{ |
| 24 |
Type: "PUBLIC KEY", |
| 25 |
Bytes: bytes, |
| 26 |
}) |
| 27 |
return json.Marshal(string(pemBytes)) |
| 28 |
} |
| 29 |
|
| 30 |
func (p *PKIXPublicKey) UnmarshalJSON(b []byte) error { |
| 31 |
var pemValue string |
| 32 |
// Prepare decoder limited to 512Kb |
| 33 |
dec := json.NewDecoder(io.LimitReader(bytes.NewReader(b), MaxJSONKeySize)) |
| 34 |
|
| 35 |
// Unmarshal key value |
| 36 |
if err := dec.Decode(&pemValue); err != nil { |
| 37 |
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { |
| 38 |
return fmt.Errorf("tuf: the public key is truncated or too large: %w", err) |
| 39 |
} |
| 40 |
return err |
| 41 |
} |
| 42 |
|
| 43 |
block, _ := pem.Decode([]byte(pemValue)) |
| 44 |
if block == nil { |
| 45 |
return errors.New("invalid PEM value") |
| 46 |
} |
| 47 |
if block.Type != "PUBLIC KEY" { |
| 48 |
return fmt.Errorf("invalid block type: %s", block.Type) |
| 49 |
} |
| 50 |
pub, err := x509.ParsePKIXPublicKey(block.Bytes) |
| 51 |
if err != nil { |
| 52 |
return err |
| 53 |
} |
| 54 |
p.PublicKey = pub |
| 55 |
return nil |
| 56 |
} |