如何在 Flutter/Dart 中对 Base64 和 Base64Url 进行编码和解码 [英] How to encode and decode Base64 and Base64Url in Flutter / Dart

查看:112
本文介绍了如何在 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 中进行编码和解码.您可以将它们与 结合使用,而不是分别进行这两种编码熔断器.

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

另见

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆