Java 8 中基本和 url base64 编码的区别
Difference between basic and url base64 encoding in Java 8
Java 8 Base64 library has two variants that can be used in URI building: the "Basic" one and the "URL and Filename safe". The documentation points to RFC 4648 Table 2 作为差异的解释。
阅读规范后,我仍然不清楚这两种编码之间的实际区别是什么:这两种标准是否都得到“广泛”支持?具体浏览器呢? URL 和文件名安全编码是否推荐用于数据 URI 编码?是否存在已知的支持限制?
最简单的方法是提供一个例子(恕我直言):
Base64.Encoder enc = Base64.getEncoder();
Base64.Encoder encURL = Base64.getUrlEncoder();
byte[] bytes = enc.encode("subjects?_d".getBytes());
byte[] bytesURL = encURL.encode("subjects?_d".getBytes());
System.out.println(new String(bytes)); // c3ViamVjdHM/X2Q= notice the "/"
System.out.println(new String(bytesURL)); // c3ViamVjdHM_X2Q= notice the "_"
Base64.Decoder dec = Base64.getDecoder();
Base64.Decoder decURL = Base64.getUrlDecoder();
byte[] decodedURL = decURL.decode(bytesURL);
byte[] decoded = dec.decode(bytes);
System.out.println(new String(decodedURL));
System.out.println(new String(decoded));
注意一个是 URL safe
而另一个不是。
事实上,如果您查看实现,有两个用于编码的查找表:toBase64
和 toBase64URL
。只有两个字符不同:
+
和 /
对应 toBase64
与 -
和 _
对应 toBase64URL
.
看来您的问题是一个安全的 URI 并且应该在那里使用?;答案是肯定的。
运行 一些测试,使用 base64 "URL and filename safe" 编码数据 URI 产生的 URI 无法被 Chrome 识别。
示例:data:text/plain;base64,TG9yZW0/aXBzdW0=
被正确解码为 Lorem?ipsum
,而它的 URL-安全对应 data:text/plain;base64,TG9yZW0_aXBzdW0=
不是 (ERR_INVALID_URL).
Java 8 Base64 library has two variants that can be used in URI building: the "Basic" one and the "URL and Filename safe". The documentation points to RFC 4648 Table 2 作为差异的解释。
阅读规范后,我仍然不清楚这两种编码之间的实际区别是什么:这两种标准是否都得到“广泛”支持?具体浏览器呢? URL 和文件名安全编码是否推荐用于数据 URI 编码?是否存在已知的支持限制?
最简单的方法是提供一个例子(恕我直言):
Base64.Encoder enc = Base64.getEncoder();
Base64.Encoder encURL = Base64.getUrlEncoder();
byte[] bytes = enc.encode("subjects?_d".getBytes());
byte[] bytesURL = encURL.encode("subjects?_d".getBytes());
System.out.println(new String(bytes)); // c3ViamVjdHM/X2Q= notice the "/"
System.out.println(new String(bytesURL)); // c3ViamVjdHM_X2Q= notice the "_"
Base64.Decoder dec = Base64.getDecoder();
Base64.Decoder decURL = Base64.getUrlDecoder();
byte[] decodedURL = decURL.decode(bytesURL);
byte[] decoded = dec.decode(bytes);
System.out.println(new String(decodedURL));
System.out.println(new String(decoded));
注意一个是 URL safe
而另一个不是。
事实上,如果您查看实现,有两个用于编码的查找表:toBase64
和 toBase64URL
。只有两个字符不同:
+
和 /
对应 toBase64
与 -
和 _
对应 toBase64URL
.
看来您的问题是一个安全的 URI 并且应该在那里使用?;答案是肯定的。
运行 一些测试,使用 base64 "URL and filename safe" 编码数据 URI 产生的 URI 无法被 Chrome 识别。
示例:data:text/plain;base64,TG9yZW0/aXBzdW0=
被正确解码为 Lorem?ipsum
,而它的 URL-安全对应 data:text/plain;base64,TG9yZW0_aXBzdW0=
不是 (ERR_INVALID_URL).