How to native convert string -> base64 and base64 -> string
I\'m find only this bytes to base64string
would like this:
As of 0.9.2 of the crypto
package
CryptoUtils
is deprecated. Use theBase64
APIs indart:convert
and the hex APIs in theconvert
package instead.
import 'dart:convert' show utf8, base64;
main() {
final str = 'https://dartpad.dartlang.org/';
final encoded = base64.encode(UTF8.encode(str));
print('base64: $encoded');
final str2 = utf8.decode(base64.decode(encoded));
print(str2);
print(str == str2);
}
Try it in DartPad
You can use the BASE64 codec (renamed base64
in Dart 2) and the LATIN1 codec (renamed latin1
in Dart 2) from convert library.
var stringToEncode = 'Dart is awesome';
// encoding
var bytesInLatin1 = LATIN1.encode(stringToEncode);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]
var base64encoded = BASE64.encode(bytesInLatin1);
// RGFydCBpcyBhd2Vzb21l
// decoding
var bytesInLatin1_decoded = BASE64.decode(base64encoded);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]
var initialValue = LATIN1.decode(bytesInLatin1_decoded);
// Dart is awesome
If you always use LATIN1
to generate the encoded String you can avoid the 2 convert calls by creating a codec to directly convert a String to/from an encoded String.
var codec = LATIN1.fuse(BASE64);
print(codec.encode('Dart is awesome'));
// RGFydCBpcyBhd2Vzb21l
print(codec.decode('RGFydCBpcyBhd2Vzb21l'));
// Dart is awesome
I would comment on Günter's April 10th, 2016, post, but I don't have the reputation. As he says, you should use the dart:convert
library, now. You have to combine a couple of codecs to get a utf8 string out of a base64 string and vice-versa. This article says that fusing your codecs is faster.
import 'dart:convert';
void main() {
var base64 = 'QXdlc29tZSE=';
var utf8 = 'Awesome!';
// Combining the codecs
print(utf8 == UTF8.decode(BASE64.decode(base64)));
print(base64 == BASE64.encode(UTF8.encode(utf8)));
// Output:
// true
// true
// Fusing is faster, and you don't have to worry about reversing your codecs
print(utf8 == UTF8.fuse(BASE64).decode(base64));
print(base64 == UTF8.fuse(BASE64).encode(utf8));
// Output:
// true
// true
}
https://dartpad.dartlang.org/5c0e1cfb6d1d640cdc902fe57a2a687d
I took a class dart.io -> base64.dart, modified it a bit, and there you are
how to use:
var somestring = 'Hello dart!';
var base64string = Base64String.encode( somestring );
var mystring = Base64String.decode( base64string );
source on pastbin.com
source on gist.github.com