简体   繁体   English

我是否需要在Dart中从Base64Url编码的字符串中手动删除=填充?

[英]Do I need to manually remove the = padding from a Base64Url encoded string in Dart?

I was surprised to notice that when I converted a string to Base64Url in Dart I got a string that ended with an = padding character. 我很惊讶地注意到,当我在Dart中将字符串转换为Base64Url时,我得到了一个以=填充字符结尾的字符串。

import 'dart:convert';

main() {
  String credentials = "username:password";
  String encoded = base64Url.encode(utf8.encode(credentials)); 

  print(encoded);  // dXNlcm5hbWU6cGFzc3dvcmQ=
}

I thought that the point of Base64Url was to remove the characters that would not not be good in a URL. 我以为Base64Url的重点是删除URL中不好的字符。 Apparently not. 显然不是。 The docs even have it listed. 文档甚至列出了它。 So does that mean I have to manually remove it myself? 那是否意味着我必须自己手动删除它?

final noPadding = encoded.replaceAll(RegExp('='), ''); // dXNlcm5hbWU6cGFzc3dvcmQ

The spec for base64url (URL and filename safe) only replaces the 62nd ( + ) and 63rd ( / ) characters of normal base64 with - and _ , respectively. base64url规范 (URL和文件名安全)仅分别用-_替换普通base64的第62个( + )和第63个( / )字符。 It does not replace the padding character ( = ), but instead makes this statement: 它不会替换填充字符( = ),而是发出以下语句:

The pad character "=" is typically percent-encoded when used in an URI, but if the data length is known implicitly, this can be avoided by skipping the padding. 填充字符“ =”在URI中使用时通常进行百分比编码,但是如果隐式知道数据长度,则可以通过跳过填充来避免这种情况。

While it is possible to remove the padding, you have to be careful because that is not handled automatically and the decode method will throw an error if you don't make sure to restore the padding first by using something like normalize() . 尽管可以删除填充,但是您必须要小心,因为它不会自动处理,如果您不确定先使用normalize()类的方法来还原填充,则解码方法将引发错误。

I would instead recommend to just use percent encoding which is available in the Uri class, as the Dart base64 implementation already supports percent-encoded strings automatically: 相反,我建议只使用Uri类中可用的百分比编码,因为Dart base64实现已经自动支持百分比编码的字符串:

import 'dart:convert';

main() {
  String input = 'username:password';
  String encoded = Uri.encodeComponent(base64Url.encode(utf8.encode(input)));
  print(encoded); // dXNlcm5hbWU6cGFzc3dvcmQ%3D
  String decoded = utf8.decode(base64Url.decode(encoded));
  print(decoded); // username:password
}

Additionally, if you are passing the base64url encoded strings as part of a URL it makes sense to use percent-encoding anyway because that is expected behavior in a URL and preserves the entire string so it doesn't have to be normalized later. 此外,如果将base64url编码的字符串作为URL的一部分进行传递,则base64url使用百分比编码,因为这是URL中的预期行为,并且保留了整个字符串,因此以后不必进行标准化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM