Debian Codegraph @

encoding.go

raw symbols SCIP
1 /*-
2 * Copyright 2014 Square Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package jose
18
19 import (
20 "bytes"
21 "compress/flate"
22 "encoding/base64"
23 "encoding/binary"
24 "io"
25 "math/big"
26 "regexp"
27 "strings"
28
29 "gopkg.in/square/go-jose.v1/json"
30 )
31
32 var stripWhitespaceRegex = regexp.MustCompile("\\s")
33
34 // Url-safe base64 encode that strips padding
35 func base64URLEncode(data []byte) string {
36 var result = base64.URLEncoding.EncodeToString(data)
37 return strings.TrimRight(result, "=")
38 }
39
40 // Url-safe base64 decoder that adds padding
41 func base64URLDecode(data string) ([]byte, error) {
42 var missing = (4 - len(data)%4) % 4
43 data += strings.Repeat("=", missing)
44 return base64.URLEncoding.DecodeString(data)
45 }
46
47 // Helper function to serialize known-good objects.
48 // Precondition: value is not a nil pointer.
49 func mustSerializeJSON(value interface{}) []byte {
50 out, err := json.Marshal(value)
51 if err != nil {
52 panic(err)
53 }
54 // We never want to serialize the top-level value "null," since it's not a
55 // valid JOSE message. But if a caller passes in a nil pointer to this method,
56 // MarshalJSON will happily serialize it as the top-level value "null". If
57 // that value is then embedded in another operation, for instance by being
58 // base64-encoded and fed as input to a signing algorithm
59 // (https://github.com/square/go-jose/issues/22), the result will be
60 // incorrect. Because this method is intended for known-good objects, and a nil
61 // pointer is not a known-good object, we are free to panic in this case.
62 // Note: It's not possible to directly check whether the data pointed at by an
63 // interface is a nil pointer, so we do this hacky workaround.
64 // https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I
65 if string(out) == "null" {
66 panic("Tried to serialize a nil pointer.")
67 }
68 return out
69 }
70
71 // Strip all newlines and whitespace
72 func stripWhitespace(data string) string {
73 return stripWhitespaceRegex.ReplaceAllString(data, "")
74 }
75
76 // Perform compression based on algorithm
77 func compress(algorithm CompressionAlgorithm, input []byte) ([]byte, error) {
78 switch algorithm {
79 case DEFLATE:
80 return deflate(input)
81 default:
82 return nil, ErrUnsupportedAlgorithm
83 }
84 }
85
86 // Perform decompression based on algorithm
87 func decompress(algorithm CompressionAlgorithm, input []byte) ([]byte, error) {
88 switch algorithm {
89 case DEFLATE:
90 return inflate(input)
91 default:
92 return nil, ErrUnsupportedAlgorithm
93 }
94 }
95
96 // Compress with DEFLATE
97 func deflate(input []byte) ([]byte, error) {
98 output := new(bytes.Buffer)
99
100 // Writing to byte buffer, err is always nil
101 writer, _ := flate.NewWriter(output, 1)
102 _, _ = io.Copy(writer, bytes.NewBuffer(input))
103
104 err := writer.Close()
105 return output.Bytes(), err
106 }
107
108 // Decompress with DEFLATE
109 func inflate(input []byte) ([]byte, error) {
110 output := new(bytes.Buffer)
111 reader := flate.NewReader(bytes.NewBuffer(input))
112
113 _, err := io.Copy(output, reader)
114 if err != nil {
115 return nil, err
116 }
117
118 err = reader.Close()
119 return output.Bytes(), err
120 }
121
122 // byteBuffer represents a slice of bytes that can be serialized to url-safe base64.
123 type byteBuffer struct {
124 data []byte
125 }
126
127 func newBuffer(data []byte) *byteBuffer {
128 if data == nil {
129 return nil
130 }
131 return &byteBuffer{
132 data: data,
133 }
134 }
135
136 func newFixedSizeBuffer(data []byte, length int) *byteBuffer {
137 if len(data) > length {
138 panic("square/go-jose: invalid call to newFixedSizeBuffer (len(data) > length)")
139 }
140 pad := make([]byte, length-len(data))
141 return newBuffer(append(pad, data...))
142 }
143
144 func newBufferFromInt(num uint64) *byteBuffer {
145 data := make([]byte, 8)
146 binary.BigEndian.PutUint64(data, num)
147 return newBuffer(bytes.TrimLeft(data, "\x00"))
148 }
149
150 func (b *byteBuffer) MarshalJSON() ([]byte, error) {
151 return json.Marshal(b.base64())
152 }
153
154 func (b *byteBuffer) UnmarshalJSON(data []byte) error {
155 var encoded string
156 err := json.Unmarshal(data, &encoded)
157 if err != nil {
158 return err
159 }
160
161 if encoded == "" {
162 return nil
163 }
164
165 decoded, err := base64URLDecode(encoded)
166 if err != nil {
167 return err
168 }
169
170 *b = *newBuffer(decoded)
171
172 return nil
173 }
174
175 func (b *byteBuffer) base64() string {
176 return base64URLEncode(b.data)
177 }
178
179 func (b *byteBuffer) bytes() []byte {
180 // Handling nil here allows us to transparently handle nil slices when serializing.
181 if b == nil {
182 return nil
183 }
184 return b.data
185 }
186
187 func (b byteBuffer) bigInt() *big.Int {
188 return new(big.Int).SetBytes(b.data)
189 }
190
191 func (b byteBuffer) toInt() int {
192 return int(b.bigInt().Int64())
193 }