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

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: Remove newlines after dart-docs 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 const Base64Encoder({bool urlSafe: false, bool addLineSeparator: false})
114 : _urlSafe = urlSafe,
115 _addLineSeparator = addLineSeparator;
116
117 /**
118 * Converts [bytes] to its Base64 representation as a string.
119 *
120 * if [start] and [end] are provided, only the sublist
121 * `bytes.sublist(start, end)` is converted.
122 */
123
124 String convert(List<int> bytes, [int start = 0, int end]) {
125 int bytes_length = bytes.length;
126 RangeError.checkValidRange(start, end, bytes_length);
127 if (end == null) end = bytes_length;
128 int length = end - start;
129 if (length == 0) {
130 return "";
131 }
132 final String lookup = _urlSafe ? _encodeTableUrlSafe : _encodeTable;
133 // Size of 24 bit chunks.
134 final int remainderLength = length.remainder(3);
135 final int chunkLength = length - remainderLength;
136 // Size of base output.
137 int baseOutputLength = ((length ~/ 3) * 4);
138 int remainderOutputLength = ((remainderLength > 0) ? 4 : 0);
139 int outputLength = baseOutputLength + remainderOutputLength;
140 // Add extra for line separators.
141 if (_addLineSeparator) {
142 outputLength += ((outputLength - 1) ~/ _LINE_LENGTH) << 1;
143 }
144 List<int> out = new List<int>(outputLength);
145
146 // Encode 24 bit chunks.
147 int j = 0, i = start, c = 0;
148 while (i < chunkLength) {
149 int x = ((bytes[i++] << 16) & 0x00FFFFFF) |
150 ((bytes[i++] << 8) & 0x00FFFFFF) |
151 bytes[i++];
152 out[j++] = lookup.codeUnitAt(x >> 18);
153 out[j++] = lookup.codeUnitAt((x >> 12) & 0x3F);
154 out[j++] = lookup.codeUnitAt((x >> 6) & 0x3F);
155 out[j++] = lookup.codeUnitAt(x & 0x3F);
156 // Add optional line separator for each 76 char output.
157 if (_addLineSeparator && ++c == 19 && j < outputLength - 2) {
158 out[j++] = _CR;
159 out[j++] = _LF;
160 c = 0;
161 }
162 }
163
164 // If input length if not a multiple of 3, encode remaining bytes and
165 // add padding.
166 if (remainderLength == 1) {
167 int x = bytes[i];
168 out[j++] = lookup.codeUnitAt(x >> 2);
169 out[j++] = lookup.codeUnitAt((x << 4) & 0x3F);
170 out[j++] = _PAD;
171 out[j++] = _PAD;
172 } else if (remainderLength == 2) {
173 int x = bytes[i];
174 int y = bytes[i + 1];
175 out[j++] = lookup.codeUnitAt(x >> 2);
176 out[j++] = lookup.codeUnitAt(((x << 4) | (y >> 4)) & 0x3F);
177 out[j++] = lookup.codeUnitAt((y << 2) & 0x3F);
178 out[j++] = _PAD;
179 }
180
181 return new String.fromCharCodes(out);
182 }
183
184 _Base64EncoderSink startChunkedConversion(Sink<String> sink) {
185 StringConversionSink stringSink;
186 if (sink is StringConversionSink) {
187 stringSink = sink;
188 } else {
189 stringSink = new StringConversionSink.from(sink);
190 }
191 return new _Base64EncoderSink(stringSink, _urlSafe, _addLineSeparator);
192 }
193 }
194
195 class _Base64EncoderSink extends ChunkedConversionSink<List<int>> {
196
197 final Base64Encoder _encoder;
198 final ChunkedConversionSink<String> _outSink;
199 final List<int> _buffer = new List<int>();
200 int _bufferCount = 0;
201
202 _Base64EncoderSink(this._outSink, urlSafe, addLineSeparator)
203 : _encoder = new Base64Encoder(urlSafe: urlSafe,
204 addLineSeparator: addLineSeparator);
205
206
207 void add(List<int> chunk) {
208 var nextBufferCount = (chunk.length + _bufferCount) % 3;
209
210 int decodableLength = _bufferCount + chunk.length - nextBufferCount;
211
212 if (_bufferCount + chunk.length > _buffer.length) {
213 _buffer.replaceRange(_bufferCount,
214 _buffer.length,
215 chunk.sublist(0, _buffer.length - _bufferCount));
216 _buffer.addAll(chunk.sublist(_buffer.length - _bufferCount));
217 } else {
218 _buffer.replaceRange(_bufferCount, _bufferCount + chunk.length, chunk);
219 }
220
221 _outSink.add(_encoder.convert(_buffer, 0, decodableLength));
222 _buffer.removeRange(0, decodableLength);
223 _bufferCount = nextBufferCount;
224 }
225
226 void close() {
227 if (_bufferCount > 0) {
228 _outSink.add(_encoder.convert(_buffer.sublist(0, _bufferCount)));
229 }
230 _outSink.close();
231 }
232 }
233
234 /**
235 * This class decodes strings to lists of bytes(lists of
236 * unsigned 8-bit integers) according to Base64.
237 */
238 class Base64Decoder extends Converter<String, List<int>> {
239
240 /**
241 * Instantiates a new [Base64Decoder]
242 */
243 const Base64Decoder();
244
245 List<int> convert(String input, {bool alwaysPadding: false}) {
246 int length = input.length;
247 if (length == 0) {
248 return new List<int>(0);
249 }
250
251 // Count '\r', '\n' and illegal characters, check if
252 // '/', '+' / '-', '_' are used consistently, for illegal characters,
253 // throw an exception.
254 int extrasLength = 0;
255 bool expectedSafe = false;
256 bool expectedUnsafe = false;
257
258 for (int i = 0; i < length; i++) {
259 int c = _decodeTable[input.codeUnitAt(i)];
260 if (c < 0) {
261 extrasLength++;
262 if (c == -2) {
263 throw new FormatException('Invalid character', input, i);
264 }
265 } else if (input[i] == _URL_UNSAFE_CHARACTERS[0] ||
266 input[i] == _URL_UNSAFE_CHARACTERS[1]) {
267
268 if (expectedSafe) {
269 throw new FormatException('Unsafe character in URL-safe string',
270 input, i);
271 }
272 expectedUnsafe = true;
273 } else if (input[i] == _URL_SAFE_CHARACTERS[0] ||
274 input[i] == _URL_SAFE_CHARACTERS[1]) {
275 if (expectedUnsafe) {
276 throw new FormatException('Invalid character', input, i);
277 }
278 expectedSafe = true;
279 }
280 }
281
282 if ((length - extrasLength) % 4 != 0) {
283 throw new FormatException('''Size of Base 64 characters in Input
284 must be a multiple of 4''', input, length - extrasLength);
285 }
286
287 // Count pad characters.
288 int padLength = 0;
289 for (int i = length - 1; i >= 0; i--) {
290 int currentCodeUnit = input.codeUnitAt(i);
291 if (_decodeTable[currentCodeUnit] > 0) break;
292 if (currentCodeUnit == _PAD) padLength++;
293 }
294 int outputLength = (((length - extrasLength) * 6) >> 3) - padLength;
295 List<int> out = new List<int>(outputLength);
296
297 for (int i = 0, o = 0; o < outputLength; ) {
298 // Accumulate 4 valid 6 bit Base 64 characters into an int.
299 int x = 0;
300 for (int j = 4; j > 0; ) {
301 int c = _decodeTable[input.codeUnitAt(i++)];
302 if (c >= 0) {
303 x = ((x << 6) & 0x00FFFFFF) | c;
304 j--;
305 }
306 }
307 out[o++] = x >> 16;
308 if (o < outputLength) {
309 out[o++] = (x >> 8) & 0xFF;
310 if (o < outputLength) out[o++] = x & 0xFF;
311 }
312 }
313
314 return out;
315 }
316
317 _Base64DecoderSink startChunkedConversion(Sink<List<int>> sink) {
318 if (sink is! ByteConversionSink) {
319 sink = new ByteConversionSink.from(sink);
320 }
321 return new _Base64DecoderSink(sink);
322 }
323 }
324
325
326 class _Base64DecoderSink extends ChunkedConversionSink<String> {
327
328 final Base64Decoder _decoder = new Base64Decoder();
329 final ChunkedConversionSink<List<int>> _outSink;
330 String _buffer = "";
331 bool _isSafe = false;
332 bool _isUnsafe = false;
333
334 _Base64DecoderSink(this._outSink);
335
336 void add(String chunk) {
337 int nextBufferLength = (chunk.length + _buffer.length) % 4;
338
339 if (chunk.length + _buffer.length >= 4) {
340 int remainder = chunk.length - nextBufferLength;
341 String decodable = _buffer + chunk.substring(0, remainder);
342 _buffer = chunk.substring(remainder);
343
344 for (int i = 0;i < decodable.length; i++) {
345 if (decodable[i] == _URL_UNSAFE_CHARACTERS[0] ||
346 decodable[i] == _URL_UNSAFE_CHARACTERS[1]) {
347 if (_isSafe) {
348 throw new FormatException('Unsafe character in URL-safe string',
349 decodable, i);
350 }
351 _isUnsafe = true;
352 } else if (decodable[i] == _URL_SAFE_CHARACTERS[0] ||
353 decodable[i] == _URL_SAFE_CHARACTERS[1]) {
354 if (_isUnsafe) {
355 throw new FormatException('Invalid character', decodable, i);
356 }
357 _isSafe = true;
358 }
359 }
360
361 _outSink.add(_decoder.convert(decodable));
362 } else {
363 _buffer += chunk;
364 }
365 }
366
367 void close() {
368 if (!_buffer.isEmpty) {
369 throw new FormatException(
370 "Size of Base 64 input must be a multiple of 4",
371 _buffer,
372 _buffer.length);
373 }
374 _outSink.close();
375 }
376 }
377
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