// MarshalJSON serializes the given key to its JSON representation. func (k JsonWebKey) MarshalJSON() ([]byte, error) { var raw *rawJsonWebKey var err error switch key := k.Key.(type) { case *ecdsa.PublicKey: raw, err = fromEcPublicKey(key) case *rsa.PublicKey: raw = fromRsaPublicKey(key) case *ecdsa.PrivateKey: raw, err = fromEcPrivateKey(key) case *rsa.PrivateKey: raw, err = fromRsaPrivateKey(key) case []byte: raw, err = fromSymmetricKey(key) default: return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key)) } if err != nil { return nil, err } raw.Kid = k.KeyID raw.Alg = k.Algorithm raw.Use = k.Use for _, cert := range k.Certificates { raw.X5c = append(raw.X5c, base64.StdEncoding.EncodeToString(cert.Raw)) } return json.Marshal(raw) }
// Helper function to serialize known-good objects. // Precondition: value is not a nil pointer. func mustSerializeJSON(value interface{}) []byte { out, err := json.Marshal(value) if err != nil { panic(err) } // We never want to serialize the top-level value "null," since it's not a // valid JOSE message. But if a caller passes in a nil pointer to this method, // MarshalJSON will happily serialize it as the top-level value "null". If // that value is then embedded in another operation, for instance by being // base64-encoded and fed as input to a signing algorithm // (https://github.com/square/go-jose/issues/22), the result will be // incorrect. Because this method is intended for known-good objects, and a nil // pointer is not a known-good object, we are free to panic in this case. // Note: It's not possible to directly check whether the data pointed at by an // interface is a nil pointer, so we do this hacky workaround. // https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I if string(out) == "null" { panic("Tried to serialize a nil pointer.") } return out }
func MarshalJSON(v interface{}) ([]byte, error) { return json.Marshal(v) }
func (b *byteBuffer) MarshalJSON() ([]byte, error) { return json.Marshal(b.base64()) }