使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:40:24  来源:igfitidea点击:

Base 64 encoding with Scala or Java

javascalabase64

提问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.Decoderand 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 Base64class.

从 Java 8 开始,标准库中直接提供了方便的实用程序类:Base64.DecoderBase64.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)

回答by dcastro

If you're using scalaj(I was), you can simply do this:

如果您使用的是scalaj(我是),您可以简单地执行以下操作:

import scalaj.http.Base64

Base64.encodeString(str)

Or

或者

import scalaj.http.HttpConstants._

base64(str)