Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(517)

Side by Side Diff: lib/src/base64.dart

Issue 1159093002: Implement a Base64 codec (Closed) Base URL: https://github.com/dart-lang/crypto.git@master
Patch Set: Check safe/unsafe characters in decoder for consistency Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « lib/crypto.dart ('k') | lib/src/crypto_utils.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 part of crypto;
2
3 const Base64Codec BASE64 = const Base64Codec();
4
5 const List<int> _decodeTable =
6 const [ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -1, -2, -2,
7 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
8 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, 62, -2, 63,
9 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, 0, -2, -2,
10 -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
11 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, 63,
12 -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
13 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
14 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
15 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
16 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
17 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
18 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
19 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
20 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
21 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 ];
22
23 const String _encodeTableUrlSafe =
24 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
25
26 const String _encodeTable =
27 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
28
29 const List<String> _URL_SAFE_CHARACTERS = const ['+', '/'];
30 const List<String> _URL_UNSAFE_CHARACTERS = const ['-', '_'];
31
32 const int _LINE_LENGTH = 76;
33 const int _PAD = 61; // '='
34 const int _CR = 13; // '\r'
35 const int _LF = 10; // '\n'
36
37 class Base64Codec extends Codec<List<int>, String> {
38
39 final bool _urlSafe;
40 final bool _addLineSeparator;
41
42 /**
43 * Instantiates a new [Base64Codec].
44 *
45 * The optional [urlSafe] argument specifies if [encoder] and [encode]
46 * should generate a string, that is safe to use in an URL.
47 *
48 * If [urlSafe] is `true` (and not overriden at the method invocation)
49 * the [encoder] and [encode] use '-' instead of '+' and '_' instead of '/'.
50 *
51 * The default value of [urlSafe] is `false`.
52 *
53 * The optional [addLineSeparator] argument specifies if the [encoder] and
54 * [encode] should add line separators.
55 *
56 * If `addLineSeparator` is `true` [encode] adds an
57 * optional line separator (CR + LF) for each 76 char output.
58 *
59 * The default value of [addLineSeparator] if `false`.
60 */
61 const Base64Codec({bool urlSafe: false, bool addLineSeparator: false})
62 : _urlSafe = urlSafe,
63 _addLineSeparator = addLineSeparator;
64
65 String get name => "base64";
66
67 String encode(List<int> bytes,
68 {bool urlSafe,
69 bool addLineSeparator}) {
70 if (urlSafe == null) urlSafe = _urlSafe;
71 if (addLineSeparator == null) addLineSeparator = _addLineSeparator;
72 return new Base64Encoder(urlSafe: urlSafe,
73 addLineSeparator: addLineSeparator).convert(bytes);
74
75
76 }
77
78 Base64Encoder get encoder => new Base64Encoder(
79 urlSafe: _urlSafe,
80 addLineSeparator: _addLineSeparator);
81
82 Base64Decoder get decoder => new Base64Decoder();
83
84 }
85
86 /**
87 * This class encodes byte strings (lists of unsigned
88 * 8-bit integers) to strings according to Base64.
89 */
90 class Base64Encoder extends Converter<List<int>, String> {
91 final bool _urlSafe;
92 final bool _addLineSeparator;
93
94 /**
95 * Instantiates a new [Base64Encoder].
96 *
97 * The optional [urlSafe] argument specifies if [convert]
98 * should generate a string, that is safe to use in an URL.
99 *
100 * If it is `true` the [convert] use
101 * '-' instead of '+' and '_' instead of '/'.
102 *
103 * The default value of [urlSafe] is `false`.
104 *
105 * The optional [addLineSeparator] argument specifies if [convert]
106 * should add line separators.
107 *
108 * If it is `true` [convert] adds an optional line separator(CR + LF)
109 * for each 76 char output.
110 *
111 * The default value of [addLineSeparator] if `false`.
112 */
113
Søren Gjesse 2015/06/03 09:20:58 nit: Please remove the empty line after the dartdo
Alexander Ivanov 2015/06/03 09:32:52 Done.
114 const Base64Encoder({bool urlSafe: false, bool addLineSeparator: false})
115 : _urlSafe = urlSafe,
116 _addLineSeparator = addLineSeparator;
117
118 /**
119 * Converts [bytes] to its Base64 representation as a string.
120 *
121 * if [start] and [end] are provided, only the sublist
122 * `bytes.sublist(start, end)` is converted.
123 */
124
125 String convert(List<int> bytes, [int start = 0, int end]) {
126 int bytes_length = bytes.length;
127 RangeError.checkValidRange(start, end, bytes_length);
128 if (end == null) end = bytes_length;
129 int length = end - start;
130 if (length == 0) {
131 return "";
132 }
133 final String lookup = _urlSafe ? _encodeTableUrlSafe : _encodeTable;
134 // Size of 24 bit chunks.
135 final int remainderLength = length.remainder(3);
136 final int chunkLength = length - remainderLength;
137 // Size of base output.
138 int baseOutputLength = ((length ~/ 3) * 4);
139 int remainderOutputLength = ((remainderLength > 0) ? 4 : 0);
140 int outputLength = baseOutputLength + remainderOutputLength;
141 // Add extra for line separators.
142 if (_addLineSeparator) {
143 outputLength += ((outputLength - 1) ~/ _LINE_LENGTH) << 1;
144 }
145 List<int> out = new List<int>(outputLength);
146
147 // Encode 24 bit chunks.
148 int j = 0, i = start, c = 0;
149 while (i < chunkLength) {
150 int x = ((bytes[i++] << 16) & 0x00FFFFFF) |
151 ((bytes[i++] << 8) & 0x00FFFFFF) |
152 bytes[i++];
153 out[j++] = lookup.codeUnitAt(x >> 18);
154 out[j++] = lookup.codeUnitAt((x >> 12) & 0x3F);
155 out[j++] = lookup.codeUnitAt((x >> 6) & 0x3F);
156 out[j++] = lookup.codeUnitAt(x & 0x3F);
157 // Add optional line separator for each 76 char output.
158 if (_addLineSeparator && ++c == 19 && j < outputLength - 2) {
159 out[j++] = _CR;
160 out[j++] = _LF;
161 c = 0;
162 }
163 }
164
165 // If input length if not a multiple of 3, encode remaining bytes and
166 // add padding.
167 if (remainderLength == 1) {
168 int x = bytes[i];
169 out[j++] = lookup.codeUnitAt(x >> 2);
170 out[j++] = lookup.codeUnitAt((x << 4) & 0x3F);
171 out[j++] = _PAD;
172 out[j++] = _PAD;
173 } else if (remainderLength == 2) {
174 int x = bytes[i];
175 int y = bytes[i + 1];
176 out[j++] = lookup.codeUnitAt(x >> 2);
177 out[j++] = lookup.codeUnitAt(((x << 4) | (y >> 4)) & 0x3F);
178 out[j++] = lookup.codeUnitAt((y << 2) & 0x3F);
179 out[j++] = _PAD;
180 }
181
182 return new String.fromCharCodes(out);
183 }
184
185 _Base64EncoderSink startChunkedConversion(Sink<String> sink) {
186 StringConversionSink stringSink;
187 if (sink is StringConversionSink) {
188 stringSink = sink;
189 } else {
190 stringSink = new StringConversionSink.from(sink);
191 }
192 return new _Base64EncoderSink(stringSink, _urlSafe, _addLineSeparator);
193 }
194 }
195
196 class _Base64EncoderSink extends ChunkedConversionSink<List<int>> {
197
198 final Base64Encoder _encoder;
199 final ChunkedConversionSink<String> _outSink;
200 final List<int> _buffer = new List<int>();
201 int _bufferCount = 0;
202
203 _Base64EncoderSink(this._outSink, urlSafe, addLineSeparator)
204 : _encoder = new Base64Encoder(urlSafe: urlSafe,
205 addLineSeparator: addLineSeparator);
206
207
208 void add(List<int> chunk) {
209 var nextBufferCount = (chunk.length + _bufferCount) % 3;
210
211 int decodableLength = _bufferCount + chunk.length - nextBufferCount;
212
213 if (_bufferCount + chunk.length > _buffer.length) {
214 _buffer.replaceRange(_bufferCount,
215 _buffer.length,
216 chunk.sublist(0, _buffer.length - _bufferCount));
217 _buffer.addAll(chunk.sublist(_buffer.length - _bufferCount));
218 } else {
219 _buffer.replaceRange(_bufferCount, _bufferCount + chunk.length, chunk);
220 }
221
222 _outSink.add(_encoder.convert(_buffer, 0, decodableLength));
223 _buffer.removeRange(0, decodableLength);
224 _bufferCount = nextBufferCount;
225 }
226
227 void close() {
228 if (_bufferCount > 0) {
229 _outSink.add(_encoder.convert(_buffer.sublist(0, _bufferCount)));
230 }
231 _outSink.close();
232 }
233 }
234
235 /**
236 * This class decodes strings to lists of bytes(lists of
237 * unsigned 8-bit integers) according to Base64.
238 */
239 class Base64Decoder extends Converter<String, List<int>> {
240
241 /**
242 * Instantiates a new [Base64Decoder]
243 */
244
Søren Gjesse 2015/06/03 09:20:58 nit: Please remove the empty line after the dartdo
Alexander Ivanov 2015/06/03 09:32:52 Done.
245 const Base64Decoder();
Søren Gjesse 2015/06/03 09:20:58 Having thought about this, I think the decode shou
Alexander Ivanov 2015/06/03 09:32:52 We decided to discuss it in another change.
246
247 List<int> convert(String input, {bool alwaysPadding: false}) {
248 int length = input.length;
249 if (length == 0) {
250 return new List<int>(0);
251 }
252
253 // Count '\r', '\n' and illegal characters, check if
254 // '/', '+' / '-', '_' are used consistently, for illegal characters,
255 // throw an exception.
256 int extrasLength = 0;
257 bool expectedSafe = false;
258 bool expectedUnsafe = false;
259
260 for (int i = 0; i < length; i++) {
261 int c = _decodeTable[input.codeUnitAt(i)];
262 if (c < 0) {
263 extrasLength++;
264 if (c == -2) {
265 throw new FormatException('Invalid character', input, i);
266 }
267 } else if (input[i] == _URL_UNSAFE_CHARACTERS[0] ||
268 input[i] == _URL_UNSAFE_CHARACTERS[1]) {
269
270 if (expectedSafe) {
271 throw new FormatException('Unsafe character in URL-safe string',
272 input, i);
273 }
274 expectedUnsafe = true;
275 } else if (input[i] == _URL_SAFE_CHARACTERS[0] ||
276 input[i] == _URL_SAFE_CHARACTERS[1]) {
277 if (expectedUnsafe) {
278 throw new FormatException('Invalid character', input, i);
279 }
280 expectedSafe = true;
281 }
282 }
283
284 if ((length - extrasLength) % 4 != 0) {
285 throw new FormatException('''Size of Base 64 characters in Input
286 must be a multiple of 4''', input, length - extrasLength);
287 }
288
289 // Count pad characters.
290 int padLength = 0;
291 for (int i = length - 1; i >= 0; i--) {
292 int currentCodeUnit = input.codeUnitAt(i);
293 if (_decodeTable[currentCodeUnit] > 0) break;
294 if (currentCodeUnit == _PAD) padLength++;
295 }
296 int outputLength = (((length - extrasLength) * 6) >> 3) - padLength;
297 List<int> out = new List<int>(outputLength);
298
299 for (int i = 0, o = 0; o < outputLength; ) {
300 // Accumulate 4 valid 6 bit Base 64 characters into an int.
301 int x = 0;
302 for (int j = 4; j > 0; ) {
303 int c = _decodeTable[input.codeUnitAt(i++)];
304 if (c >= 0) {
305 x = ((x << 6) & 0x00FFFFFF) | c;
306 j--;
307 }
308 }
309 out[o++] = x >> 16;
310 if (o < outputLength) {
311 out[o++] = (x >> 8) & 0xFF;
312 if (o < outputLength) out[o++] = x & 0xFF;
313 }
314 }
315
316 return out;
317 }
318
319 _Base64DecoderSink startChunkedConversion(Sink<List<int>> sink) {
320 if (sink is! ByteConversionSink) {
321 sink = new ByteConversionSink.from(sink);
322 }
323 return new _Base64DecoderSink(sink);
324 }
325 }
326
327
328 class _Base64DecoderSink extends ChunkedConversionSink<String> {
329
330 final Base64Decoder _decoder = new Base64Decoder();
331 final ChunkedConversionSink<List<int>> _outSink;
332 String _buffer = "";
333 bool _isSafe = false;
334 bool _isUnsafe = false;
335
336 _Base64DecoderSink(this._outSink);
337
338 void add(String chunk) {
339 int nextBufferLength = (chunk.length + _buffer.length) % 4;
340
341 if (chunk.length + _buffer.length >= 4) {
342 int remainder = chunk.length - nextBufferLength;
343 String decodable = _buffer + chunk.substring(0, remainder);
344 _buffer = chunk.substring(remainder);
345
346 for (int i = 0;i < decodable.length; i++) {
347 if (decodable[i] == _URL_UNSAFE_CHARACTERS[0] ||
348 decodable[i] == _URL_UNSAFE_CHARACTERS[1]) {
349 if (_isSafe) {
350 throw new FormatException('Unsafe character in URL-safe string',
351 decodable, i);
352 }
353 _isUnsafe = true;
354 } else if (decodable[i] == _URL_SAFE_CHARACTERS[0] ||
355 decodable[i] == _URL_SAFE_CHARACTERS[1]) {
356 if (_isUnsafe) {
357 throw new FormatException('Invalid character', decodable, i);
358 }
359 _isSafe = true;
360 }
361 }
362
363 _outSink.add(_decoder.convert(decodable));
364 } else {
365 _buffer += chunk;
366 }
367 }
368
369 void close() {
370 if (!_buffer.isEmpty) {
371 throw new FormatException(
372 "Size of Base 64 input must be a multiple of 4",
373 _buffer,
374 _buffer.length);
375 }
376 _outSink.close();
377 }
378 }
379
OLDNEW
« no previous file with comments | « lib/crypto.dart ('k') | lib/src/crypto_utils.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698