48

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"

What is the site doing differently from these encodings? Also, how might I mimic the site in Java/Scala?

Note, the specific application is for a header using Basic Authentication.

1

4 Answers 4

98

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.

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))
Sign up to request clarification or add additional context in comments.

1 Comment

What's a suitable Java 7 alternative?
18

To get "user:pass" to "dXNlcjpwYXNz", you should be base64-encoding the UTF-8 encoded string, but not hashing.

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.

2 Comments

(Also, your second version with URLEncoder doesn't appear to actually do any hashing...or Base64 encoding...)
Thank you! That was perfect. As for the second example, it was just to help rule out some of the answers that have been thrown at other similar questions.
12

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)

Comments

7

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

import scalaj.http.Base64

Base64.encodeString(str)

Or

import scalaj.http.HttpConstants._

base64(str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.