|
| 1 | +import 'package:blockchain_utils/base64/exception/exception.dart'; |
| 2 | +import 'package:blockchain_utils/blockchain_utils.dart'; |
| 3 | + |
| 4 | +class _Base64StreamDecoder { |
| 5 | + static const _base64Table = |
| 6 | + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; |
| 7 | + static final _base64DecodeTable = () { |
| 8 | + final table = List<int>.filled(256, -1); |
| 9 | + for (int i = 0; i < _base64Table.length; i++) { |
| 10 | + table[_base64Table.codeUnitAt(i)] = i; |
| 11 | + } |
| 12 | + return table.immutable; |
| 13 | + }(); |
| 14 | + |
| 15 | + static List<int> _decode(String encoded) { |
| 16 | + final cleaned = encoded.replaceAll('=', ''); |
| 17 | + final output = <int>[]; |
| 18 | + int i = 0; |
| 19 | + |
| 20 | + while (i + 4 <= cleaned.length) { |
| 21 | + int chunk = (_base64DecodeTable[cleaned.codeUnitAt(i)] << 18) | |
| 22 | + (_base64DecodeTable[cleaned.codeUnitAt(i + 1)] << 12) | |
| 23 | + (_base64DecodeTable[cleaned.codeUnitAt(i + 2)] << 6) | |
| 24 | + (_base64DecodeTable[cleaned.codeUnitAt(i + 3)]); |
| 25 | + output.add((chunk >> 16) & 0xFF); |
| 26 | + output.add((chunk >> 8) & 0xFF); |
| 27 | + output.add(chunk & 0xFF); |
| 28 | + i += 4; |
| 29 | + } |
| 30 | + |
| 31 | + int rem = cleaned.length - i; |
| 32 | + if (rem == 2) { |
| 33 | + int chunk = (_base64DecodeTable[cleaned.codeUnitAt(i)] << 18) | |
| 34 | + (_base64DecodeTable[cleaned.codeUnitAt(i + 1)] << 12); |
| 35 | + output.add((chunk >> 16) & 0xFF); |
| 36 | + } else if (rem == 3) { |
| 37 | + int chunk = (_base64DecodeTable[cleaned.codeUnitAt(i)] << 18) | |
| 38 | + (_base64DecodeTable[cleaned.codeUnitAt(i + 1)] << 12) | |
| 39 | + (_base64DecodeTable[cleaned.codeUnitAt(i + 2)] << 6); |
| 40 | + output.add((chunk >> 16) & 0xFF); |
| 41 | + output.add((chunk >> 8) & 0xFF); |
| 42 | + } |
| 43 | + |
| 44 | + return output; |
| 45 | + } |
| 46 | + |
| 47 | + final List<int> _output = []; |
| 48 | + String _carry = ''; |
| 49 | + |
| 50 | + /// Adds Base64 string data to the decoder, buffering as needed. |
| 51 | + /// Strips out newline and carriage return characters. |
| 52 | + void add(String input) { |
| 53 | + _carry += input.replaceAll('\n', '').replaceAll('\r', ''); |
| 54 | + while (_carry.length >= 4) { |
| 55 | + final chunk = _carry.substring(0, 4); |
| 56 | + _output.addAll(_decode(chunk)); |
| 57 | + _carry = _carry.substring(4); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /// Finalizes decoding by processing any remaining buffered data. |
| 62 | + /// Returns the full decoded byte list. |
| 63 | + List<int> finalize() { |
| 64 | + if (_carry.isNotEmpty) { |
| 65 | + _output.addAll(_decode(_carry.padRight(4, '='))); |
| 66 | + } |
| 67 | + return _output; |
| 68 | + } |
| 69 | + |
| 70 | + void clean() { |
| 71 | + _output.clear(); |
| 72 | + _carry = ''; |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +/// A utility class for decoding Base64-encoded strings with options |
| 77 | +/// for URL-safe variant handling and padding validation. |
| 78 | +class B64Decoder { |
| 79 | + /// Decodes a Base64 [data] string into bytes. |
| 80 | + /// |
| 81 | + /// [validatePadding]: If true (default), requires input length to be a multiple of 4. |
| 82 | + /// If false, padding '=' is added automatically to fix length. |
| 83 | + /// |
| 84 | + /// [urlSafe]: If true (default), treats input as URL-safe Base64, converting |
| 85 | + /// '-' to '+' and '_' to '/' before decoding. If false, throws if URL-safe |
| 86 | + /// characters are present. |
| 87 | + /// |
| 88 | + /// Throws [B64ConverterException] on invalid input or length. |
| 89 | + static List<int> decode(String data, |
| 90 | + {bool validatePadding = true, bool urlSafe = true}) { |
| 91 | + if (validatePadding && data.length % 4 != 0) { |
| 92 | + throw B64ConverterException("Invalid length, must be multiple of four"); |
| 93 | + } else if (!validatePadding) { |
| 94 | + while (data.length % 4 != 0) { |
| 95 | + data += '='; |
| 96 | + } |
| 97 | + } |
| 98 | + if (urlSafe) { |
| 99 | + data = data.replaceAll('-', '+').replaceAll('_', '/'); |
| 100 | + } else if (data.contains('-') || data.contains('_')) { |
| 101 | + throw B64ConverterException( |
| 102 | + 'Invalid character in standard Base64 string: found URL-safe characters "-" or "_" but urlSafe is false.'); |
| 103 | + } |
| 104 | + final encoder = _Base64StreamDecoder(); |
| 105 | + try { |
| 106 | + encoder.add(data); |
| 107 | + return encoder.finalize().clone(); |
| 108 | + } finally { |
| 109 | + encoder.clean(); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + /// Tries to decode a Base64 string, returning null if decoding fails. |
| 114 | + /// |
| 115 | + /// Same parameters as [decode], but catches exceptions and returns null on error. |
| 116 | + static List<int>? tryDecode(String data, |
| 117 | + {bool validatePadding = true, bool urlSafe = true}) { |
| 118 | + try { |
| 119 | + return decode(data, urlSafe: urlSafe, validatePadding: validatePadding); |
| 120 | + } catch (_) { |
| 121 | + return null; |
| 122 | + } |
| 123 | + } |
| 124 | +} |
0 commit comments