Dart Base64 encode decode with validation
Dart
import 'dart:convert';
String encodeBase64(List<int> bytes) => base64Encode(bytes);
List<int> decodeBase64(String text) {
final cleaned = text.replaceAll(RegExp(r'\s'), '');
final padded = cleaned.padRight((cleaned.length + 3) ~/ 4 * 4, '=');
if (!RegExp(r'^[A-Za-z0-9+/]*={0,2}$').hasMatch(padded)) {
throw const FormatException('Invalid Base64 characters');
}
try {
return base64Decode(padded);
} on FormatException {
throw const FormatException('Invalid Base64 payload or length');
}
}
String decodeBase64Text(String text) => utf8.decode(decodeBase64(text), allowMalformed: false);