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.
Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding. Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.
How does base64 work? Base64 encoding converts every three bytes of data (three bytes is 3*8=24 bits) into four base64 characters. Which makes up a total of three bytes (24 bits). Base64 encoding will divide the binary data up to six-bit chunks and map them to a base64 character according to the table above.
Instances of Base64. Encoder class are safe for use by multiple concurrent threads. Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With