达特编码和解码base64字符串

18

如何将字符串转换为 base64,以及如何将 base64 转换为字符串。

我只找到了这个将字节转换为base64字符串的方法

我想要的是:

String Base64String.encode();
String Base64String.decode();

从另一种语言移植是否更容易?

5个回答

13

从0.9.2版本开始,crypto包中的CryptoUtils已过时。请改用dart:convert中的Base64 API以及convert包中的hex API。

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);
}

DartPad 中尝试它


7

您可以使用convert库中的BASE64编解码器(在Dart 2中更名为base64)和LATIN1编解码器(在Dart 2中更名为latin1)。

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

如果您始终使用 LATIN1 生成编码后的字符串,您可以通过创建一个编解码器来直接将字符串转换为/从编码后的字符串来避免2次转换调用。
var codec = LATIN1.fuse(BASE64);

print(codec.encode('Dart is awesome'));
// RGFydCBpcyBhd2Vzb21l

print(codec.decode('RGFydCBpcyBhd2Vzb21l'));
// Dart is awesome

这个来自2013年的答案现在已经过时了。 - Mathieu J.

7
我想评论Günter在2016年4月10日的帖子,但我没有声望。正如他所说,现在应该使用dart:convert库。你必须组合一些编解码器才能从base64字符串中获取utf8字符串,反之亦然。 这篇文章说,融合你的编解码器会更快。
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


为什么这不是内置在dart:convert库中的?! - Pat
这并没有内置在转换库中,因为该库有许多不同的转换器、编码器和编解码器,如果也包含所有这些组合,那将会是过度杀伤力。fuse操作存在的目的是让您自己制作所需的组合。 - lrn
这对我不起作用,我的字符串是二进制的,我无法对其进行UTF8解码。 - Mathieu J.
如果您正在使用DartPad并且在渲染具有长字符串变量的应用程序时遇到问题,我创建了此解决方案。https://github.com/dart-lang/dart-pad/issues/1342#issuecomment-862016884 - Marcello DeSales

4
以下是在dart中进行编码/解码的示例:
main.dart:
import 'dart:convert';

main() {
  // encode
  var str = "Hello world";
  var bytes = utf8.encode(str);
  var base64Str = base64.encode(bytes);
  print(base64Str);

  // decode
  var decoded_bytes = base64.decode(base64Str);
  var decoded_str = utf8.decode(decoded_bytes);
  print(decoded_str);
}

1
我学习了一门名为 dart.io -> base64.dart 的课程,并对其进行了一些修改,现在它就变成了这个样子。
使用方法如下:
var somestring = 'Hello dart!';

var base64string = Base64String.encode( somestring );
var mystring = Base64String.decode( base64string );

pastbin.com上的源代码

gist.github.com上的源代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接