Debian Codegraph @

jwe.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 "fmt"
21 "strings"
22
23 "gopkg.in/square/go-jose.v1/json"
24 )
25
26 // rawJsonWebEncryption represents a raw JWE JSON object. Used for parsing/serializing.
27 type rawJsonWebEncryption struct {
28 Protected *byteBuffer `json:"protected,omitempty"`
29 Unprotected *rawHeader `json:"unprotected,omitempty"`
30 Header *rawHeader `json:"header,omitempty"`
31 Recipients []rawRecipientInfo `json:"recipients,omitempty"`
32 Aad *byteBuffer `json:"aad,omitempty"`
33 EncryptedKey *byteBuffer `json:"encrypted_key,omitempty"`
34 Iv *byteBuffer `json:"iv,omitempty"`
35 Ciphertext *byteBuffer `json:"ciphertext,omitempty"`
36 Tag *byteBuffer `json:"tag,omitempty"`
37 }
38
39 // rawRecipientInfo represents a raw JWE Per-Recipient header JSON object. Used for parsing/serializing.
40 type rawRecipientInfo struct {
41 Header *rawHeader `json:"header,omitempty"`
42 EncryptedKey string `json:"encrypted_key,omitempty"`
43 }
44
45 // JsonWebEncryption represents an encrypted JWE object after parsing.
46 type JsonWebEncryption struct {
47 Header JoseHeader
48 protected, unprotected *rawHeader
49 recipients []recipientInfo
50 aad, iv, ciphertext, tag []byte
51 original *rawJsonWebEncryption
52 }
53
54 // recipientInfo represents a raw JWE Per-Recipient header JSON object after parsing.
55 type recipientInfo struct {
56 header *rawHeader
57 encryptedKey []byte
58 }
59
60 // GetAuthData retrieves the (optional) authenticated data attached to the object.
61 func (obj JsonWebEncryption) GetAuthData() []byte {
62 if obj.aad != nil {
63 out := make([]byte, len(obj.aad))
64 copy(out, obj.aad)
65 return out
66 }
67
68 return nil
69 }
70
71 // Get the merged header values
72 func (obj JsonWebEncryption) mergedHeaders(recipient *recipientInfo) rawHeader {
73 out := rawHeader{}
74 out.merge(obj.protected)
75 out.merge(obj.unprotected)
76
77 if recipient != nil {
78 out.merge(recipient.header)
79 }
80
81 return out
82 }
83
84 // Get the additional authenticated data from a JWE object.
85 func (obj JsonWebEncryption) computeAuthData() []byte {
86 var protected string
87
88 if obj.original != nil && obj.original.Protected != nil {
89 protected = obj.original.Protected.base64()
90 } else if obj.protected != nil {
91 protected = base64URLEncode(mustSerializeJSON((obj.protected)))
92 } else {
93 protected = ""
94 }
95
96 output := []byte(protected)
97 if obj.aad != nil {
98 output = append(output, '.')
99 output = append(output, []byte(base64URLEncode(obj.aad))...)
100 }
101
102 return output
103 }
104
105 // ParseEncrypted parses an encrypted message in compact or full serialization format.
106 func ParseEncrypted(input string) (*JsonWebEncryption, error) {
107 input = stripWhitespace(input)
108 if strings.HasPrefix(input, "{") {
109 return parseEncryptedFull(input)
110 }
111
112 return parseEncryptedCompact(input)
113 }
114
115 // parseEncryptedFull parses a message in compact format.
116 func parseEncryptedFull(input string) (*JsonWebEncryption, error) {
117 var parsed rawJsonWebEncryption
118 err := json.Unmarshal([]byte(input), &parsed)
119 if err != nil {
120 return nil, err
121 }
122
123 return parsed.sanitized()
124 }
125
126 // sanitized produces a cleaned-up JWE object from the raw JSON.
127 func (parsed *rawJsonWebEncryption) sanitized() (*JsonWebEncryption, error) {
128 obj := &JsonWebEncryption{
129 original: parsed,
130 unprotected: parsed.Unprotected,
131 }
132
133 // Check that there is not a nonce in the unprotected headers
134 if (parsed.Unprotected != nil && parsed.Unprotected.Nonce != "") ||
135 (parsed.Header != nil && parsed.Header.Nonce != "") {
136 return nil, ErrUnprotectedNonce
137 }
138
139 if parsed.Protected != nil && len(parsed.Protected.bytes()) > 0 {
140 err := json.Unmarshal(parsed.Protected.bytes(), &obj.protected)
141 if err != nil {
142 return nil, fmt.Errorf("square/go-jose: invalid protected header: %s, %s", err, parsed.Protected.base64())
143 }
144 }
145
146 // Note: this must be called _after_ we parse the protected header,
147 // otherwise fields from the protected header will not get picked up.
148 obj.Header = obj.mergedHeaders(nil).sanitized()
149
150 if len(parsed.Recipients) == 0 {
151 obj.recipients = []recipientInfo{
152 recipientInfo{
153 header: parsed.Header,
154 encryptedKey: parsed.EncryptedKey.bytes(),
155 },
156 }
157 } else {
158 obj.recipients = make([]recipientInfo, len(parsed.Recipients))
159 for r := range parsed.Recipients {
160 encryptedKey, err := base64URLDecode(parsed.Recipients[r].EncryptedKey)
161 if err != nil {
162 return nil, err
163 }
164
165 // Check that there is not a nonce in the unprotected header
166 if parsed.Recipients[r].Header != nil && parsed.Recipients[r].Header.Nonce != "" {
167 return nil, ErrUnprotectedNonce
168 }
169
170 obj.recipients[r].header = parsed.Recipients[r].Header
171 obj.recipients[r].encryptedKey = encryptedKey
172 }
173 }
174
175 for _, recipient := range obj.recipients {
176 headers := obj.mergedHeaders(&recipient)
177 if headers.Alg == "" || headers.Enc == "" {
178 return nil, fmt.Errorf("square/go-jose: message is missing alg/enc headers")
179 }
180 }
181
182 obj.iv = parsed.Iv.bytes()
183 obj.ciphertext = parsed.Ciphertext.bytes()
184 obj.tag = parsed.Tag.bytes()
185 obj.aad = parsed.Aad.bytes()
186
187 return obj, nil
188 }
189
190 // parseEncryptedCompact parses a message in compact format.
191 func parseEncryptedCompact(input string) (*JsonWebEncryption, error) {
192 parts := strings.Split(input, ".")
193 if len(parts) != 5 {
194 return nil, fmt.Errorf("square/go-jose: compact JWE format must have five parts")
195 }
196
197 rawProtected, err := base64URLDecode(parts[0])
198 if err != nil {
199 return nil, err
200 }
201
202 encryptedKey, err := base64URLDecode(parts[1])
203 if err != nil {
204 return nil, err
205 }
206
207 iv, err := base64URLDecode(parts[2])
208 if err != nil {
209 return nil, err
210 }
211
212 ciphertext, err := base64URLDecode(parts[3])
213 if err != nil {
214 return nil, err
215 }
216
217 tag, err := base64URLDecode(parts[4])
218 if err != nil {
219 return nil, err
220 }
221
222 raw := &rawJsonWebEncryption{
223 Protected: newBuffer(rawProtected),
224 EncryptedKey: newBuffer(encryptedKey),
225 Iv: newBuffer(iv),
226 Ciphertext: newBuffer(ciphertext),
227 Tag: newBuffer(tag),
228 }
229
230 return raw.sanitized()
231 }
232
233 // CompactSerialize serializes an object using the compact serialization format.
234 func (obj JsonWebEncryption) CompactSerialize() (string, error) {
235 if len(obj.recipients) != 1 || obj.unprotected != nil ||
236 obj.protected == nil || obj.recipients[0].header != nil {
237 return "", ErrNotSupported
238 }
239
240 serializedProtected := mustSerializeJSON(obj.protected)
241
242 return fmt.Sprintf(
243 "%s.%s.%s.%s.%s",
244 base64URLEncode(serializedProtected),
245 base64URLEncode(obj.recipients[0].encryptedKey),
246 base64URLEncode(obj.iv),
247 base64URLEncode(obj.ciphertext),
248 base64URLEncode(obj.tag)), nil
249 }
250
251 // FullSerialize serializes an object using the full JSON serialization format.
252 func (obj JsonWebEncryption) FullSerialize() string {
253 raw := rawJsonWebEncryption{
254 Unprotected: obj.unprotected,
255 Iv: newBuffer(obj.iv),
256 Ciphertext: newBuffer(obj.ciphertext),
257 EncryptedKey: newBuffer(obj.recipients[0].encryptedKey),
258 Tag: newBuffer(obj.tag),
259 Aad: newBuffer(obj.aad),
260 Recipients: []rawRecipientInfo{},
261 }
262
263 if len(obj.recipients) > 1 {
264 for _, recipient := range obj.recipients {
265 info := rawRecipientInfo{
266 Header: recipient.header,
267 EncryptedKey: base64URLEncode(recipient.encryptedKey),
268 }
269 raw.Recipients = append(raw.Recipients, info)
270 }
271 } else {
272 // Use flattened serialization
273 raw.Header = obj.recipients[0].header
274 raw.EncryptedKey = newBuffer(obj.recipients[0].encryptedKey)
275 }
276
277 if obj.protected != nil {
278 raw.Protected = newBuffer(mustSerializeJSON(obj.protected))
279 }
280
281 return string(mustSerializeJSON(raw))
282 }