...
1 package keys
2
3 import (
4 "crypto/ecdsa"
5 "crypto/rand"
6 "crypto/x509"
7 "encoding/json"
8 "encoding/pem"
9 "errors"
10 "io"
11
12 . "gopkg.in/check.v1"
13 )
14
15 const ecdsaKey = `-----BEGIN PUBLIC KEY-----
16 MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEftgasQA68yvumeXZmcOTSIHKfbmx
17 WT1oYuRF0Un3tKxnzip6xAYwlz0Dt96DUh+0P7BruHH2O6s4MiRR9/TuNw==
18 -----END PUBLIC KEY-----
19 `
20
21 type PKIXSuite struct{}
22
23 var _ = Suite(&PKIXSuite{})
24
25 func (PKIXSuite) TestMarshalJSON(c *C) {
26 block, _ := pem.Decode([]byte(ecdsaKey))
27 key, err := x509.ParsePKIXPublicKey(block.Bytes)
28 c.Assert(err, IsNil)
29 k := PKIXPublicKey{PublicKey: key}
30 buf, err := json.Marshal(&k)
31 c.Assert(err, IsNil)
32 var val string
33 err = json.Unmarshal(buf, &val)
34 c.Assert(err, IsNil)
35 c.Assert(val, Equals, ecdsaKey)
36 }
37
38 func (PKIXSuite) TestUnmarshalJSON(c *C) {
39 buf, err := json.Marshal(ecdsaKey)
40 c.Assert(err, IsNil)
41 var k PKIXPublicKey
42 err = json.Unmarshal(buf, &k)
43 c.Assert(err, IsNil)
44 c.Assert(k.PublicKey, FitsTypeOf, (*ecdsa.PublicKey)(nil))
45 }
46
47 func (PKIXSuite) TestUnmarshalPKIX_TooLongContent(c *C) {
48 randomSeed := make([]byte, MaxJSONKeySize)
49 _, err := io.ReadFull(rand.Reader, randomSeed)
50 c.Assert(err, IsNil)
51
52 pemBytes := pem.EncodeToMemory(&pem.Block{
53 Type: "PUBLIC KEY",
54 Bytes: randomSeed,
55 })
56 tooLongPayload, err := json.Marshal(string(pemBytes))
57 c.Assert(err, IsNil)
58
59 var k PKIXPublicKey
60 err = json.Unmarshal(tooLongPayload, &k)
61 c.Assert(errors.Is(err, io.ErrUnexpectedEOF), Equals, true)
62 }
63
View as plain text