本文介绍了如何在Flutter/Dart中编码和解码Base64和Base64Url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Flutter中的Base64Url中编码以下字符串,并在Dart服务器上对其进行解码.

I want to encode the following string in Base64Url in Flutter and decode it in on a Dart server.

"username:password"

我该怎么做?以及如何在Base64中做到这一点?

How do I do that? And how do I do it in Base64?

推荐答案

dart:convert库包含用于Base64和Base64Url的编码器和解码器.但是,它们对整数列表进行编码和解码,因此对于字符串,您还需要使用UTF-8进行编码和解码.您可以将它们与 fuse .

The dart:convert library contains an encoder and decoder for Base64 and Base64Url. However, they encode and decode Lists of integers, so for strings you also need to encode and decode in UTF-8. Rather than doing these two encodings separately, you can combine them with fuse.

您需要进行以下导入:

import 'dart:convert';

Base64

String credentials = "username:password";
Codec<String, String> stringToBase64 = utf8.fuse(base64);
String encoded = stringToBase64.encode(credentials);      // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = stringToBase64.decode(encoded);          // username:password

请注意,这等效于:

String encoded = base64.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = utf8.decode(base64.decode(encoded));     // username:password

Base64Url

String credentials = "username:password";
Codec<String, String> stringToBase64Url = utf8.fuse(base64Url);
String encoded = stringToBase64Url.encode(credentials);      // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = stringToBase64Url.decode(encoded);          // username:password

同样,它等同于:

String encoded = base64Url.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
String decoded = utf8.decode(base64Url.decode(encoded));     // username:password

另请参见

  • RCF 4648
  • 基于字符串的数据编码:Base64与Base64url
  • See also

    • RCF 4648
    • String based data encoding: Base64 vs Base64url
    • 这篇关于如何在Flutter/Dart中编码和解码Base64和Base64Url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 07:47