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