使用 Scala 或 Java 进行 Base 64 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18241077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base 64 encoding with Scala or Java
提问by Erick Stone
I have tried :
我试过了 :
val md = java.security.MessageDigest.getInstance("SHA-1")
val result = new sun.misc.BASE64Encoder().encode(md.digest("user:pass".getBytes))
RESULT:
结果:
md: java.security.MessageDigest = SHA-1 Message Digest from SUN, <initialized>
result: String = smGaoVKd/cQkjm7b88GyorAUz20=
I also tried :
我也试过:
import java.net.URLEncoder
val result = URLEncoder.encode(user + ":" + pass, "UTF-8")
RESULT:
结果:
result: String = user%3Apass
Based on http://www.base64encode.org/The value I am wanting for result should be "dXNlcjpwYXNz"
基于http://www.base64encode.org/我想要的结果值应该是“dXNlcjpwYXNz”
What is the site doing differently from these encodings? Also, how might I mimic the site in Java/Scala?
该网站与这些编码有何不同?另外,我如何在 Java/Scala 中模仿该站点?
Note, the specific application is for a header using Basic Authentication.
请注意,特定应用程序用于使用基本身份验证的标头。
采纳答案by Louis Wasserman
To get "user:pass" to "dXNlcjpwYXNz", you should be base64-encoding the UTF-8 encoded string, but not hashing.
要将“user:pass”转换为“dXNlcjpwYXNz”,您应该对 UTF-8 编码的字符串进行 base64 编码,而不是散列。
Using the third-party Guava library, I can run
使用第三方番石榴库,我可以运行
System.out.println(BaseEncoding.base64()
.encode("user:pass".getBytes(Charsets.UTF_8)));
and I get out
我出去
dXNlcjpwYXNz
as requested. The other Base64 encoders should work similarly.
按照要求。其他 Base64 编码器应该类似地工作。
回答by Vladimir Matveev
Since Java 8 there are handy utility classes directly in the standard library: Base64.Decoder
and Base64.Encoder
. There are also some static factory methods to construct instances of these classes which perform Base64 encoding/decoding for various flavors of Base64 in Base64
class.
从 Java 8 开始,标准库中直接提供了方便的实用程序类:Base64.Decoder
和Base64.Encoder
. 还有一些静态工厂方法来构造这些类的实例,这些实例为类中的各种 Base64 执行 Base64 编码/解码Base64
。
This is how to use the encoder:
这是使用编码器的方法:
import java.util.Base64
import java.nio.charset.StandardCharsets
Base64.getEncoder.encodeToString("user:pass".getBytes(StandardCharsets.UTF_8))
回答by Epicurist
Scala was asked:
有人问斯卡拉:
import java.nio.charset.StandardCharsets
val (password, expected) = ("user:pass".getBytes(StandardCharsets.UTF_8), "dXNlcjpwYXNz")
assume(java.util.Base64.getEncoder.encodeToString(password)==expected)